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.

Require Lead decisions for finished Swarm workers and safely stop released sessions (#1527)

0xken15591b056a3d06
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 2327ef5c6..8ef8b2ac9 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -1120,6 +1120,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
.rejects.toMatchObject({ code: 'WORK_ACTIVE' })
await store.stopped(host, tab, first, 'handover-stop-receipt')
expect(await store.routeDecision(owner, tab, id)).toMatchObject({ outcome: null, assignmentId: null, final: null })
+ await run(tab, { type: 'agent.release', agentId: picked, decision: 'keep' }, host, lead)
const second = (await run(tab, { type: 'work.assign', conversationId: group, agentId: chosen, routeDecisionId: id } as Command, host, lead)).result.assignmentId as string
expect(await store.routeDecision(owner, tab, id)).toMatchObject({ outcome: null, assignmentId: second, final: { kind: 'member', agentId: chosen } })
const check = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!.checks[0]!.id
@@ -1270,3 +1271,149 @@ describe('Super Tab chat attachments', () => {
expect(files.objects.size).toBe(before)
})
})
+
+it('releases a finished worker through its execution host, cancels deliveries and returns the machine slot', async () => {
+ const { tab, lead } = await fixture()
+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ await run(tab, { type: 'machine.contribute', machineId: 'test-host', name: 'Host', cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)
+ const group = (await run(tab, { type: 'conversation.create', title: 'Task', brief: 'Deliver it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId as string
+ const native = randomUUID()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
+ const pool = (await store.hostPools(host, 'test-host')).find(p => p.tabId === tab)!.machine
+ const oldObservation = { generation: pool.generation,
+ resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: {}, runningHarnessIds: [native], stoppedHarnessIds: [] }
+ await store.observeMachine(host, tab, 'test-host', oldObservation)
+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ await expect(run(tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, lead)).rejects.toMatchObject({ code: 'WORK_ACTIVE' })
+ await store.stopped(host, tab, assignmentId, 'fixture-native-stop')
+ const before = (await store.read(owner, tab)).state
+ expect(before.agents.find(a => a.id === worker)!.workDecision).toBe('awaiting')
+ const { machineSlots } = await import('../src/superTabs/machines.js')
+ expect(machineSlots(before, before.machines![0]!)).toBe(2)
+ await run(tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, lead)
+ expect((await store.hostTabs(host, 'test-host')).find(r => r.agent.id === worker)).toMatchObject({ stopRequested: true })
+ await expect(run(tab, { type: 'agent.remove', agentId: worker }, owner, worker)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ const operation = randomUUID()
+ const releaseId = (await store.read(owner, tab)).state.agents.find(a => a.id === worker)!.releaseId!
+ const removal = { type: 'agent.remove', agentId: worker, releaseId } as Command
+ await expect(run(tab, { ...removal, releaseId: 'old-release' } as Command, host, worker)).rejects.toMatchObject({ code: 'STALE_RELEASE' })
+ const receipt = await run(tab, removal, host, worker, operation)
+ expect(await run(tab, removal, host, worker, operation)).toEqual(receipt)
+ const after = (await store.read(owner, tab)).state
+ expect(after.agents.some(a => a.id === worker)).toBe(false)
+ expect(machineSlots(after, after.machines![0]!)).toBe(1)
+ await store.observeMachine(host, tab, 'test-host', oldObservation)
+ const delayed = (await store.read(owner, tab)).state
+ expect(delayed.machines![0]!.availableSlots).toBe(3)
+ expect(await db.superTabDelivery.count({ where: { tabId: tab, agentId: worker, status: { in: ['queued', 'claimed', 'uncertain'] } } })).toBe(0)
+ expect((await store.hostTabs(host, 'test-host')).some(r => r.agent.id === worker)).toBe(false)
+ // Re-contribution reserves a new runtime; ordinary removal must not reuse its old stop proof.
+ await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Renewed worker', configuration: config, lead: false })
+ await run(tab, { type: 'agent.remove', agentId: worker })
+ const hostPool = (await store.hostPools(host, 'test-host')).find(p => p.tabId === tab)!
+ expect(hostPool.harnessIds).toContain(native)
+ const reservation = hostPool.reservations.find(r => r.harnessId === native)!
+ await store.observeMachine(host, tab, 'test-host', { ...oldObservation, runningHarnessIds: [], stoppedHarnessIds: [native],
+ stoppedReservations: [{ harnessId: native, generation: 'old-generation' }] })
+ const stillReserved = (await store.read(owner, tab)).state
+ expect(stillReserved.machines![0]!.availableSlots).toBe(2)
+ await store.observeMachine(host, tab, 'test-host', { ...oldObservation, runningHarnessIds: [], stoppedHarnessIds: [native],
+ stoppedReservations: [reservation] })
+ const physicallyStopped = (await store.read(owner, tab)).state
+ expect(physicallyStopped.machines![0]!.availableSlots).toBe(3)
+ await store.observeMachine(host, tab, 'test-host', oldObservation)
+ const delayedAgain = (await store.read(owner, tab)).state
+ expect(delayedAgain.machines![0]!.availableSlots).toBe(3)
+})
+
+it('fences a shared native session globally while its release is pending', async () => {
+ const a = await fixture(), b = await fixture(), native = randomUUID()
+ const add = async (tab: string) => {
+ const group = (await run(tab, { type: 'conversation.create', title: 'Shared worker task', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Shared worker', configuration: config, lead: false })).result.agentId as string
+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ return { group, worker, assignmentId }
+ }
+ const first = await add(a.tab)
+ await store.stopped(host, a.tab, first.assignmentId, 'first-finished')
+ const second = await add(b.tab)
+ await expect(run(a.tab, { type: 'agent.release', agentId: first.worker, decision: 'stop' }, host, a.lead)).rejects.toMatchObject({ code: 'AGENT_BUSY' })
+ await store.stopped(host, b.tab, second.assignmentId, 'second-finished')
+ await run(b.tab, { type: 'agent.remove', agentId: second.worker })
+ await run(a.tab, { type: 'agent.release', agentId: first.worker, decision: 'stop' }, host, a.lead)
+ await expect(run(b.tab, { type: 'agent.add', conversationId: second.group, machineId: 'test-host', harnessId: native, name: 'Shared worker', configuration: config, lead: false })).rejects.toMatchObject({ code: 'STOP_REQUESTED' })
+ await expect(run(a.tab, { type: 'agent.remove', agentId: first.worker }, host, a.lead)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ const state = (await store.read(owner, a.tab)).state
+ const releaseId = state.agents.find(x => x.id === first.worker)!.releaseId!
+ await run(a.tab, { type: 'agent.remove', agentId: first.worker, releaseId } as Command, host, first.worker)
+ expect(await db.superTabRun.findUnique({ where: { id: first.worker } })).toBeNull()
+})
+
+it('lets a person force-withdraw a stuck stop, clears its fence and retires the old session', async () => {
+ const { tab, lead } = await fixture(), native = randomUUID()
+ const group = (await run(tab, { type: 'conversation.create', title: 'Offline worker', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ await store.stopped(host, tab, assignmentId, 'completed-before-offline')
+ await run(tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, lead)
+ const forced = { type: 'agent.remove', agentId: worker } as Command
+ await expect(run(tab, forced, host, lead)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ await run(tab, forced)
+ expect(await db.superTabRun.findUnique({ where: { id: worker } })).toBeNull()
+ expect((await store.read(owner, tab)).state.agents.some(a => a.id === worker)).toBe(false)
+ // The old native identity cannot receive new work while a delayed close may still be finishing.
+ await expect(run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Retired worker', configuration: config, lead: false })).rejects.toMatchObject({ code: 'SESSION_RELEASED' })
+ const other = await fixture()
+ const reused = await run(other.tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: native, name: 'Contributor reuse', configuration: config, lead: false })
+ expect(reused.result.agentId).toBe(worker)
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
+})
+
+it('refuses to stop a finished worker that is the Lead of another Swarm', async () => {
+ const first = await fixture(), second = await fixture(), native = randomUUID()
+ const group = (await run(first.tab, { type: 'conversation.create', title: 'Finished worker', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
+ const worker = (await run(first.tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
+ const assignmentId = (await run(first.tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ await store.stopped(host, first.tab, assignmentId, 'completed')
+ await run(second.tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: native, name: 'Other Lead', configuration: config, lead: true })
+ await expect(run(first.tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, first.lead)).rejects.toMatchObject({ code: 'SESSION_SHARED' })
+ expect((await store.read(owner, first.tab)).state.agents.find(a => a.id === worker)!.workDecision).toBe('awaiting')
+})
+
+
+it('makes a project private while its worker is stopping', async () => {
+ const { tab, lead } = await fixture(), native = randomUUID()
+ const group = (await run(tab, { type: 'conversation.create', title: 'Finished task', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
+ const assignmentId = (await run(tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ await store.stopped(host, tab, assignmentId, 'completed')
+ await run(tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, lead)
+ await run(tab, { type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })
+ const state = (await store.read(owner, tab)).state
+ expect(state.projects!.find(p => p.id === 'lead')!.visibility).toBe('private')
+ expect(state.agents.find(a => a.id === worker)!.workDecision).toBe('stop')
+})
+
+
+it.each(['finished', 'expired'] as const)('lets another Swarm reuse after the native close lease is %s', async outcome => {
+ const first = await fixture(), other = await fixture(), native = randomUUID()
+ const group = (await run(first.tab, { type: 'conversation.create', title: 'Task', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
+ const worker = (await run(first.tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
+ const assignmentId = (await run(first.tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
+ await store.stopped(host, first.tab, assignmentId, 'completed')
+ await run(first.tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, first.lead)
+ const leased = await run(first.tab, { type: 'agent.stopLease', agentId: worker, releaseId: (await store.read(owner, first.tab)).state.agents.find(a => a.id === worker)!.releaseId! } as Command, host, worker)
+ const reuse = { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: native, name: 'Reused', configuration: config, lead: false } as Command
+ if (outcome === 'expired') await run(first.tab, { type: 'agent.remove', agentId: worker })
+ await expect(run(other.tab, reuse)).rejects.toMatchObject({ code: 'CLOSE_PENDING' })
+ if (outcome === 'finished') {
+ const releaseId = (await store.read(owner, first.tab)).state.agents.find(a => a.id === worker)!.releaseId!
+ await run(first.tab, { type: 'agent.remove', agentId: worker, releaseId }, host, worker)
+ expect((await run(other.tab, reuse)).result.agentId).toBe(worker)
+ } else {
+ const later = new SuperTabStore(db, () => Number(leased.result.expiresAt) + 1)
+ expect((await later.execute(owner, other.tab, { operationId: randomUUID(), command: reuse })).result.agentId).toBe(worker)
+ }
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 3ea43910f..a398e75ef 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1002,6 +1002,14 @@ model SuperTab {
// A terminal retains its history when removed from a roster. These bindings
// prevent contributing a private session to another project's audience later.
model SuperTabSessionScope {
+ /// Administrative retirement belongs only to the Swarm that withdrew this session.
+ releasedTabIds String[] @default([])
+ /// A bounded native close may finish after membership is withdrawn.
+ closeLeaseId String?
+ closeLeaseUntil DateTime?
+ closeLeaseGeneration String?
+ /// Serializes contribution changes with stop intent across public Swarms.
+ stopReleaseId String?
id String @id @map("_id")
scopeIds String[]
privateScope String?
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 5696eece9..616f856eb 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { machineSlots } from './machines.js'
import { activeWork, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
import type { RouteDecision } from './routeRecord.js'
@@ -98,6 +99,42 @@ describe('Super Tab collaboration policy', () => {
expect(f.state.agents[0]!.configurationVersion).not.toBe(before)
})
+ it('counts a fresh contribution despite a stopped proof from its previous removal', () => {
+ const f = fixture(), worker = f.add('worker')
+ f.state.machines = [{ machineId: 'host', name: 'Host', contributorId: 'owner', membershipGeneration: f.state.people[0]!.generation,
+ generation: 'pool', cwd: '/work', engines: ['codex'], maxAgents: 1, paused: false,
+ observation: { generation: 'pool', receivedAt: 1000, resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null,
+ diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null, deviceType: null, chip: null, os: null, gpuPercent: null },
+ tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: ['worker'] } }]
+ f.run({ type: 'agent.remove', agentId: worker })
+ f.state.releasedHarnesses = [{ machineId: 'host', harnessId: 'worker' }]
+ f.add('worker')
+ expect(machineSlots(f.state, f.state.machines![0]!)).toBe(1)
+ // A delayed machine observation from the stopped runtime arrives after re-contribution.
+ f.state.machines![0]!.observation!.stoppedHarnessIds = ['worker']
+ expect(machineSlots(f.state, f.state.machines![0]!)).toBe(1)
+ f.state.machines![0]!.observation!.stoppedHarnessIds = []
+ f.state.machines![0]!.observation!.runningHarnessIds = ['worker']
+ f.run({ type: 'agent.remove', agentId: worker })
+ expect(machineSlots(f.state, f.state.machines![0]!)).toBe(1)
+ f.add('worker')
+ f.state.machines![0]!.observation!.stoppedHarnessIds = ['worker']
+ expect(machineSlots(f.state, f.state.machines![0]!)).toBe(1)
+ })
+
+ it('a person withdrawing a stuck stop keeps its native slot until the host reports stopping', () => {
+ const f = fixture(), worker = f.add('worker')
+ f.state.agents[0]!.workDecision = 'awaiting'
+ f.run({ type: 'agent.release', agentId: worker, decision: 'stop' })
+ const pool = { machineId: 'host', name: 'Host', contributorId: 'owner', membershipGeneration: f.state.people[0]!.generation,
+ generation: 'pool', cwd: '/work', engines: ['codex'], maxAgents: 1, paused: false }
+ f.state.machines = [pool]
+ f.run({ type: 'agent.remove', agentId: worker })
+ expect(f.state.releasedHarnesses ?? []).toEqual([])
+ expect(machineSlots(f.state, pool)).toBe(1)
+ // An old/offline host has not sent any observation; no physical stop is implied by Remove.
+ })
+
it('fences observations from an earlier contribution of the same native harness', () => {
const f = fixture(), worker = f.add('worker')
const before = f.state.agents[0]!.configurationVersion!
@@ -520,8 +557,9 @@ describe('decisions linked to work', () => {
requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
expect(() => f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ assignmentId }), contribution: f.contribution }))
.toThrow('already has running work')
- // Once that work ended, the decision may be linked again.
+ // Once that work ended and the worker is kept, the decision may be linked again.
f.state.conversations.find(c => c.id === 'lead')!.assignment!.status = 'stopped'
+ f.run({ type: 'agent.release', agentId: f.worker, decision: 'keep' }, f.leadActor)
expect(f.run({ type: 'agent.start', request, routeDecisionId: 'd1' }, f.leadActor, { routeDecision: open({ assignmentId }), contribution: f.contribution }).routeDecisions).toHaveLength(1)
})
@@ -643,3 +681,96 @@ describe('message attachments', () => {
expect(resent.messages[0]).toMatchObject({ recipients: [lead], attachments: [file] })
})
})
+
+ describe('finished worker decisions', () => {
+ function finished() {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()
+ const worker = f.add('worker', 'owner', group), other = f.add('other', 'owner', group)
+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
+ const workerActor: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ return { f, group, worker, other, leadActor, workerActor }
+ }
+ it('requires a decision after completion, preserves it across a new brief, and clears it on reuse', () => {
+ const { f, group, worker, other, leadActor } = finished()
+ expect(visibleState(f.state, owner).agents.find(a => a.id === worker)).toHaveProperty('workDecision', 'awaiting')
+ f.run({ type: 'work.define', conversationId: group, brief: 'Next task', checks: [{ description: 'Done', independent: false }] })
+ expect(() => f.run({ type: 'work.assign', conversationId: group, agentId: other }, leadActor)).toThrow('reuse, keep or stop')
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker }, leadActor)
+ expect(f.state.agents.find(a => a.id === worker)).not.toHaveProperty('workDecision')
+ expect(() => f.run({ type: 'agent.release', agentId: worker, decision: 'stop' } as Command, leadActor)).toThrow('active work')
+ })
+ it('permits the Lead or owner to keep or stop, refuses workers, and fences reuse after stop', () => {
+ const { f, group, worker, other, leadActor, workerActor } = finished()
+ const release = { type: 'agent.release', agentId: worker, decision: 'keep' } as Command
+ expect(() => f.run(release, workerActor)).toThrow('Lead')
+ f.run(release, leadActor)
+ expect(f.state.agents.find(a => a.id === worker)).toHaveProperty('workDecision', 'keep')
+ f.run({ ...release, decision: 'stop' } as Command)
+ expect(() => f.run({ type: 'work.assign', conversationId: group, agentId: worker }, leadActor)).toThrow('stopping')
+ expect(() => f.run(release, leadActor)).toThrow('stopping')
+ f.run({ type: 'work.assign', conversationId: group, agentId: other }, leadActor)
+ })
+ it('allows only the execution host of a requested stop to acknowledge removal', () => {
+ const { f, worker, other, leadActor, workerActor } = finished()
+ expect(() => f.run({ type: 'agent.remove', agentId: worker }, workerActor)).toThrow()
+ f.run({ type: 'agent.release', agentId: worker, decision: 'stop' } as Command, leadActor)
+ expect(() => f.run({ type: 'agent.remove', agentId: worker }, { ...workerActor, agentId: other })).toThrow()
+ const releaseId = f.state.agents.find(a => a.id === worker)!.releaseId!
+ const removed = f.run({ type: 'agent.remove', agentId: worker, releaseId }, workerActor)
+ expect(removed.cancelledAgents).toContain(worker)
+ expect(f.state.agents.some(a => a.id === worker)).toBe(false)
+ })
+ })
+
+it('blocks routing and starts until a finished worker is kept or stopped', () => {
+ const f = routed(), group = f.group()
+ f.run({ type: 'work.assign', conversationId: group, agentId: f.worker })
+ const assignmentId = f.state.conversations.find(c => c.id === group)!.assignment!.id
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ const route = { type: 'route.record', conversationId: group, decision: record() } as Command
+ const request = { conversationId: group, machineId: 'machine', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: false,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
+ expect(() => f.run(route, f.leadActor)).toThrow('reuse, keep or stop')
+ expect(() => f.run({ type: 'agent.start', request }, f.leadActor, { contribution: f.contribution })).toThrow('reuse, keep or stop')
+ f.run({ type: 'agent.release', agentId: f.worker, decision: 'keep' }, f.leadActor)
+ expect(f.run(route, f.leadActor).routeDecisions).toHaveLength(1)
+ expect(f.run({ type: 'agent.start', request }, f.leadActor, { contribution: f.contribution }).result.startId).toBeTruthy()
+})
+
+it('requires the exact stop request for host acknowledgement and prevents promotion while stopping', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)
+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
+ const workerActor: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ f.run({ type: 'agent.release', agentId: worker, decision: 'stop' }, leadActor)
+ expect(() => f.run({ type: 'agent.remove', agentId: worker, releaseId: 'old-release' } as Command, workerActor)).toThrow('stop request')
+ expect(() => f.run({ type: 'conversation.agent', conversationId: group, agentId: worker, present: true, lead: true })).toThrow('stopping')
+ expect(() => f.add('worker', 'owner', group, true)).toThrow('stopping')
+})
+
+it('allows the contributor to keep a completed worker and refuses another project’s Lead', () => {
+ const f = fixture(); f.invite()
+ f.add('lead', 'owner', 'lead', true)
+ const group = f.group(), worker = f.add('worker', 'peer', group)
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
+ const checkId = f.state.conversations.find(c => c.id === group)!.checks[0]!.id
+ f.run({ type: 'work.check', conversationId: group, assignmentId, checkId, passed: true, evidence: 'Verified' })
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'done', result: 'Delivered' })
+ expect(f.state.agents.find(a => a.id === worker)!.workDecision).toBe('awaiting')
+ f.run({ type: 'agent.release', agentId: worker, decision: 'keep' }, peer)
+ expect(f.state.agents.find(a => a.id === worker)!.workDecision).toBe('keep')
+ const project = f.run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result
+ const otherLead = f.add('other-lead', 'owner', project.conversationId as string, true)
+ expect(() => f.run({ type: 'agent.release', agentId: worker, decision: 'stop' }, { kind: 'agent', agentId: otherLead, machineOwnerId: 'host-owner' })).toThrow()
+})
+
+it('allows routing directly to the awaiting worker without first keeping it', () => {
+ const f = routed(), group = f.group()
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: f.worker }).result.assignmentId as string
+ f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ const decision = record({ candidates: [candidate('c0', { kind: 'member', agentId: f.worker, machineId: 'host' })], pick: 'c0' })
+ expect(f.run({ type: 'route.record', conversationId: group, decision } as Command, f.leadActor).routeDecisions).toHaveLength(1)
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 89cdc6090..c1eecd0c4 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -3,6 +3,7 @@ import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,
+ finishWorker, requireWorkerDecisions,
type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,
} from './model.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
@@ -68,10 +69,13 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), initialMessage: text.optional() }).strict(),
z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
- z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration }).strict(),
+ z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration,
+ startedSession: z.object({ sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
z.object({ type: z.literal('agent.startSettled'), startId: id, warning: z.string().max(2000).nullable() }).strict(),
z.object({ type: z.literal('agent.startFailed'), startId: id, error: text }).strict(),
- z.object({ type: z.literal('agent.remove'), agentId: id }).strict(),
+ z.object({ type: z.literal('agent.stopLease'), agentId: id, releaseId: id }).strict(),
+ z.object({ type: z.literal('agent.remove'), agentId: id, releaseId: id.optional() }).strict(),
+ z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),
z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),
z.object({ type: z.literal('conversation.agent'), conversationId: id, agentId: id, present: z.boolean(), lead: z.boolean() }).strict(),
z.object({ type: z.literal('invite.create'), email: z.email().max(320), role: z.enum(['collaborator', 'viewer']), conversationId: id }).strict(),
@@ -384,6 +388,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const agentId = stableId(command.machineId, command.harnessId)
const existing = state.agents.find(a => a.id === agentId)
if (existing) sameProject(state, group, existing)
+ if (existing?.workDecision === 'stop' && command.lead) fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
+ if (!existing) reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)
if (!existing) state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId,
...(state.projects ? { projectId: project.id } : {}),
machineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,
@@ -412,7 +418,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
case 'agent.start': {
controls(state, actor, command.request.conversationId)
- open(state, command.request.conversationId)
+ requireWorkerDecisions(state, actor, open(state, command.request.conversationId))
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
// The Lead's account has machines the Swarm never prepared (no clone of the project), so a Lead may start only where the
// Swarm already lists a machine: a contributed one, or one an agent of the Swarm runs on. A person's start may name any
@@ -452,7 +458,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
controls(state, actor, start.request.conversationId)
if (command.type === 'agent.startDispatch') {
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
- open(state, start.request.conversationId)
+ requireWorkerDecisions(state, actor, open(state, start.request.conversationId))
const grant = context.contribution ?? fail('HOST_REQUIRED', 'The original machine grant is unavailable.', 403)
if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {
fail('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.', 403)
@@ -484,10 +490,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const group = open(state, start.request.conversationId)
const agentId = stableId(start.request.machineId, command.harnessId)
if (state.agents.some(a => a.id === agentId)) fail('ALREADY_SHARED', 'This native harness is already in the tab.')
+ reserveHarnessSlot(state, start.request.machineId, command.harnessId, operationId)
state.agents.push({ id: agentId, machineId: start.request.machineId, harnessId: command.harnessId,
...(state.projects ? { projectId: groupProject(state, group).id } : {}),
machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
- hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId })
+ hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,
+ ...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })
group.agentIds.push(agentId)
start.harnessId = command.harnessId
result.agentId = agentId
@@ -508,18 +516,71 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
break
}
+ case 'agent.release': {
+ const target = agent(state, command.agentId)
+ const project = projectOf(state, agentProjectId(state, target))
+ const isLead = actor.kind === 'agent' && conversation(state, project.leadConversationId).leadId === actor.agentId
+ const isOwner = actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId)
+ if (!isLead && !isOwner) fail('FORBIDDEN', 'Only this project’s Lead, the contributor or tab owner can release a worker.', 403)
+ if (state.conversations.some(c => c.leadId === target.id)) fail('LEAD_REQUIRED', 'Release workers only; keep the Lead running.')
+ if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before releasing this worker.')
+ if (!target.workDecision && !state.conversations.some(c => c.assignment?.agentId === target.id)) fail('WORK_REQUIRED', 'This worker has no finished assignment to release.')
+ if (target.workDecision === 'stop' && command.decision !== 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
+ if (command.decision === 'stop' && target.workDecision !== 'stop') target.releaseId = operationId
+ target.workDecision = command.decision
+ break
+ }
+ case 'agent.stopLease': {
+ const target = agent(state, command.agentId)
+ if (actor.kind !== 'agent' || actor.agentId !== target.id || target.workDecision !== 'stop' || command.releaseId !== target.releaseId) {
+ fail('STALE_RELEASE', 'Only the execution host can claim the current worker stop.', 403)
+ }
+ result.leaseId = operationId
+ result.durationMs = 120_000
+ result.expiresAt = context.now + 120_000
+ break
+ }
case 'agent.remove': {
const target = agent(state, command.agentId)
- if (actor.kind !== 'person' || (actor.userId !== state.ownerId && actor.userId !== target.contributorId)) {
+ const hostStop = actor.kind === 'agent' && actor.agentId === target.id && target.workDecision === 'stop'
+ const forceStop = actor.kind === 'person' && target.workDecision === 'stop' &&
+ [state.ownerId, target.contributorId].includes(actor.userId)
+ if (hostStop || forceStop) {
+ if (hostStop && (command.releaseId !== target.releaseId || !target.releaseId)) fail('STALE_RELEASE', 'Read the current stop request before confirming removal.')
+ if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before stopping this worker.')
+ // Administrative withdrawal never attests physical stopping or releases native capacity.
+ if (hostStop) {
+ state.releasedHarnesses ??= []
+ if (!state.releasedHarnesses.some(r => r.machineId === target.machineId && r.harnessId === target.harnessId)) {
+ state.releasedHarnesses.push({ machineId: target.machineId, harnessId: target.harnessId })
+ }
+ state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== target.machineId || r.harnessId !== target.harnessId)
+ const observation = state.machines?.find(m => m.machineId === target.machineId)?.observation
+ if (observation) {
+ observation.runningHarnessIds = observation.runningHarnessIds.filter(id => id !== target.harnessId)
+ if (!observation.stoppedHarnessIds.includes(target.harnessId)) observation.stoppedHarnessIds.push(target.harnessId)
+ }
+ }
+ if (actor.kind === 'agent') result.releasedBy = actor.machineOwnerId
+ if (forceStop) result.forceReleased = target.id
+ } else if (target.workDecision === 'stop') {
+ fail('FORBIDDEN', 'Only its contributor or tab owner can force-withdraw a stopping worker.', 403)
+ } else if (actor.kind !== 'person' || (actor.userId !== state.ownerId && actor.userId !== target.contributorId)) {
fail('FORBIDDEN', 'Only the contributor or tab owner can withdraw this agent.', 403)
}
+ if (actor.kind === 'person' && !state.harnessReservations?.some(r => r.machineId === target.machineId && r.harnessId === target.harnessId)
+ && !state.releasedHarnesses?.some(r => r.machineId === target.machineId && r.harnessId === target.harnessId)) {
+ reserveHarnessSlot(state, target.machineId, target.harnessId, operationId)
+ }
removeAgent(target)
break
}
case 'conversation.agent': {
controls(state, actor, command.conversationId)
const group = open(state, command.conversationId)
- sameProject(state, group, agent(state, command.agentId))
+ const member = agent(state, command.agentId)
+ sameProject(state, group, member)
+ if (member.workDecision === 'stop' && command.lead) fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
if (!command.present) {
if (activeWork(group) && (group.assignment?.agentId === command.agentId || group.leadId === command.agentId)) {
fail('WORK_ACTIVE', 'Reconcile this agent’s assignment before removing it from the conversation.')
@@ -608,7 +669,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
case 'route.record': {
controls(state, actor, command.conversationId)
- open(state, command.conversationId)
+ const chosen = command.decision.candidates.find(c => c.id === command.decision.pick)!
+ requireWorkerDecisions(state, actor, open(state, command.conversationId), chosen.kind === 'member' ? chosen.agentId : undefined)
if ((context.recentRoutes ?? 0) >= 30) fail('RATE_LIMITED', 'This Super Tab routed 30 tasks in the last hour. Wait before routing again.', 429)
const decision = command.decision
const pick = decision.candidates.find(c => c.id === decision.pick)!
@@ -656,6 +718,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
controls(state, actor, command.conversationId)
const group = open(state, command.conversationId)
if (activeWork(group)) fail('WORK_ACTIVE', 'Finish or stop the current assignment before changing its acceptance checks.')
+ if (group.assignment) {
+ const worker = state.agents.find(a => a.id === group.assignment!.agentId)
+ if (worker && !worker.workDecision) finishWorker(state, worker.id)
+ }
rememberAttempt(group)
group.assignment = null
group.brief = command.task ? renderWorkTask(command.task) : command.brief!
@@ -677,7 +743,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!group.brief || !group.checks.length) fail('BRIEF_REQUIRED', 'Record the brief and acceptance checks before assigning work.', 400)
const worker = agent(state, command.agentId)
sameProject(state, group, worker)
+ requireWorkerDecisions(state, actor, group, worker.id)
+ if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
+ delete worker.workDecision
+ delete worker.releaseId
if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
rememberAttempt(group)
group.assignment = { id: operationId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
@@ -714,6 +784,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const changed = assignment.status !== command.status || assignment.result !== command.result
assignment.status = command.status
assignment.result = command.result
+ if (['done', 'stopped'].includes(command.status)) finishWorker(state, assignment.agentId)
if (changed) {
const label = { working: 'Working', needs_human: 'Needs a human', blocked: 'Stuck', review: 'Ready for review', done: 'Done', stopped: 'Stopped' }[command.status]
const lead = group.leadId
@@ -737,8 +808,26 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
}
}
+ for (const target of original.agents.filter(a => a.workDecision === 'stop')) {
+ const acknowledged = command.type === 'agent.remove' && command.agentId === target.id &&
+ (actor.kind === 'agent' && actor.agentId === target.id || actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId))
+ if (!acknowledged && !state.agents.some(a => a.id === target.id)) fail('STOP_REQUESTED', 'Wait for the execution host to finish stopping its workers before withdrawing them.')
+ }
// MongoDB limits a document to 16 MiB. Leave room for indexes and metadata, and refuse before losing state.
assignAgentDisplayNames(state.agents)
if (Buffer.byteLength(JSON.stringify(state)) > 8 * 1024 * 1024) fail('TAB_TOO_LARGE', 'This Super Tab has reached its metadata limit.', 413)
return effects
}
+
+/** A contribution owns capacity independently of membership. Reuse invalidates every prior stop proof. */
+function reserveHarnessSlot(state: SuperTabState, machineId: string, harnessId: string, generation: string) {
+ const observation = state.machines?.find(m => m.machineId === machineId)?.observation
+ const renewed = !!(state.harnessReservations?.some(r => r.machineId === machineId && r.harnessId === harnessId)
+ || state.releasedHarnesses?.some(r => r.machineId === machineId && r.harnessId === harnessId)
+ || observation?.stoppedHarnessIds.includes(harnessId))
+ if (observation) observation.stoppedHarnessIds = observation.stoppedHarnessIds.filter(id => id !== harnessId)
+ state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== machineId || r.harnessId !== harnessId)
+ state.harnessReservations ??= []
+ state.harnessReservations = state.harnessReservations.filter(r => r.machineId !== machineId || r.harnessId !== harnessId)
+ state.harnessReservations.push({ machineId, harnessId, generation, renewed })
+}
diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.ts
index 91facdca3..a0ea081cb 100644
--- a/backend/src/superTabs/machines.test.ts
+++ b/backend/src/superTabs/machines.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { createSuperTab, SuperTabError, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
-import { admitMachineStart, type ContributedMachine } from './machines.js'
+import { admitMachineStart, machineSlots, type ContributedMachine } from './machines.js'
const NOW = 1_000_000
const requirements = { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 50, tools: ['git'], devices: [], quotaRequired: false }
@@ -112,3 +112,16 @@ describe('a start on a contributed machine', () => {
expect(refusal(f.state, f.request(), start)).toBeNull()
})
})
+
+
+it('keeps durable release receipts authoritative over stale observations and retained starts', () => {
+ const f = setup(), pool = f.state.machines![0]!
+ pool.observation = { ...observation, runningHarnessIds: ['finished'] }
+ f.state.starts = [{ request: { machineId: 'host' }, harnessId: 'finished' } as AgentStart]
+ f.state.releasedHarnesses = [{ machineId: 'host', harnessId: 'finished' }]
+ expect(machineSlots(f.state, pool)).toBe(0)
+ f.state.agents.push({ machineId: 'host', harnessId: 'finished' } as never)
+ expect(machineSlots(f.state, pool)).toBe(0)
+ f.state.harnessReservations = [{ machineId: 'host', harnessId: 'finished', generation: 'new-runtime', renewed: true }]
+ expect(machineSlots(f.state, pool)).toBe(1)
+})
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index d0aac212b..c4bc2a9dd 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -34,6 +34,7 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16
tools: z.record(z.string().max(80), z.boolean()).refine(v => Object.keys(v).length <= 20),
quotas: z.array(quota).max(32), runningHarnessIds: z.array(z.string().max(160)).max(1000),
stoppedHarnessIds: z.array(z.string().max(160)).max(1000),
+ stoppedReservations: z.array(z.object({ harnessId: z.string().min(1).max(160), generation: z.string().min(1).max(160) }).strict()).max(1000).optional(),
}).strict()
export type MachineObservation = z.infer<typeof machineObservationSchema>
@@ -49,9 +50,18 @@ export function machineContribution(state: SuperTabState, machineId: string) {
/** Pending intents reserve slots too. Only an explicit host stop frees a launched slot. */
export function machineSlots(state: SuperTabState, pool: ContributedMachine) {
- const stopped = new Set(pool.observation?.stoppedHarnessIds ?? [])
- const running = new Set(pool.observation?.runningHarnessIds ?? [])
+ const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === pool.machineId)
+ const live = new Set(reservations.map(r => r.harnessId))
+ const released = (state.releasedHarnesses ?? []).filter(r => r.machineId === pool.machineId && !live.has(r.harnessId)).map(r => r.harnessId)
+ const observed = pool.observation?.stoppedHarnessIds ?? []
+ const stopped = new Set([...observed.filter(id => {
+ const reservation = reservations.find(r => r.harnessId === id)
+ // Older hosts can prove a first launch stopped, but cannot distinguish a resumed runtime from its predecessor.
+ return !reservation || !reservation.renewed || pool.observation?.stoppedReservations?.some(r => r.harnessId === id && r.generation === reservation.generation)
+ }), ...released])
+ const running = new Set((pool.observation?.runningHarnessIds ?? []).filter(id => !stopped.has(id)))
for (const a of state.agents) if (a.machineId === pool.machineId && !stopped.has(a.harnessId)) running.add(a.harnessId)
+ for (const r of reservations) if (!stopped.has(r.harnessId)) running.add(r.harnessId)
let pending = 0
for (const start of state.starts ?? []) {
if (start.request.machineId !== pool.machineId || start.error) continue
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index f121f6cff..6b1f7b90d 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -24,6 +24,11 @@ export interface Agent {
name: string
/** A stable member name; native session and routing names remain in `name`. */
displayName?: string
+ /** A finished worker stays undecided even when its group receives a new brief. */
+ workDecision?: 'awaiting' | 'keep' | 'stop'
+ releaseId?: string
+ /** Captured from the original Swarm launch, never inferred from a later live session with the same id. */
+ startedSession?: { creationId: string; sessionId: string; createdAt: string }
configuration: AgentConfiguration
/** The last configuration operation fences delayed observations, including re-contribution. */
configurationVersion?: string
@@ -132,6 +137,10 @@ export interface SuperTabState {
invitations: Invitation[]
starts?: AgentStart[]
machines?: import('./machines.js').ContributedMachine[]
+ /** Slot claims survive person withdrawal; only host proof for this generation releases them. */
+ harnessReservations?: Array<{ machineId: string; harnessId: string; generation: string; renewed: boolean }>
+ /** Native stop receipts survive late replaceable machine observations. */
+ releasedHarnesses?: Array<{ machineId: string; harnessId: string }>
}
export type Actor =
| { kind: 'person'; userId: string; email: string }
@@ -168,6 +177,25 @@ export const actorKey = (actor: Actor): string => actor.kind === 'person' ? `per
export const activeWork = (group: Conversation): boolean => !!group.assignment &&
!['done', 'stopped'].includes(group.assignment.status)
+/** Old states derive pending decisions from their closed assignments; new states persist them on the worker. */
+export function awaitingWorkers(state: SuperTabState, projectId: string): Agent[] {
+ return state.agents.filter(a => {
+ if (state.conversations.some(c => c.leadId === a.id) || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)) return false
+ const groups = state.conversations.filter(c => c.assignment?.agentId === a.id)
+ return (a.projectId ?? groups.map(c => groupProject(state, c).id)[0] ?? 'lead') === projectId &&
+ (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !activeWork(c))))
+ })
+}
+export function requireWorkerDecisions(state: SuperTabState, actor: Actor, group: Conversation, reuseId?: string): void {
+ if (actor.kind !== 'agent') return
+ const waiting = awaitingWorkers(state, groupProject(state, group).id).filter(a => a.id !== reuseId)
+ if (waiting.length) fail('WORKER_DECISION_REQUIRED', `Decide what to do with ${waiting.map(a => a.displayName ?? a.name).join(', ')}: reuse, keep or stop. Prefer stop unless more work is coming soon.`)
+}
+export function finishWorker(state: SuperTabState, workerId: string): void {
+ const target = state.agents.find(a => a.id === workerId)
+ if (target && !state.conversations.some(c => c.leadId === workerId)) target.workDecision = 'awaiting'
+}
+
export function person(state: SuperTabState, id: string): Person {
return state.people.find(p => p.id === id) ?? fail('FORBIDDEN', 'You no longer have access to this Super Tab.', 403)
}
@@ -223,6 +251,8 @@ export function visibleState(state: SuperTabState, actor: Actor): SuperTabState
const visible = structuredClone(state)
assignAgentDisplayNames(visible.agents)
delete visible.sharing
+ delete visible.harnessReservations
+ delete visible.releasedHarnesses
numberConversations(visible)
delete visible.retiredConversationNumber
if (visible.projects) {
@@ -239,9 +269,11 @@ export function visibleState(state: SuperTabState, actor: Actor): SuperTabState
if (!pool.observation) continue
pool.observation.runningHarnessIds = pool.observation.runningHarnessIds.filter(id => harnesses.has(id))
pool.observation.stoppedHarnessIds = pool.observation.stoppedHarnessIds.filter(id => harnesses.has(id))
+ if (pool.observation.stoppedReservations) pool.observation.stoppedReservations = pool.observation.stoppedReservations.filter(r => harnesses.has(r.harnessId))
}
visible.invitations = visible.invitations.filter(i => visible.conversations.some(c => c.id === i.conversationId))
}
+ for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id)) target.workDecision = 'awaiting'
if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []
return visible
}
diff --git a/backend/src/superTabs/sessionScope.ts b/backend/src/superTabs/sessionScope.ts
index 1c59e08ed..bf7166622 100644
--- a/backend/src/superTabs/sessionScope.ts
+++ b/backend/src/superTabs/sessionScope.ts
@@ -4,11 +4,16 @@ import { agentProjectId, projectOf } from './projects.js'
const scopeId = (state: SuperTabState, projectId: string) => stableId(state.id, projectId)
-export async function bindSession(tx: Prisma.TransactionClient, state: SuperTabState, target: Agent) {
+export async function bindSession(tx: Prisma.TransactionClient, state: SuperTabState, target: Agent, now = Date.now()) {
const project = projectOf(state, agentProjectId(state, target))
const scope = scopeId(state, project.id)
const id = stableId('swarm-session', state.environment, target.machineOwnerId, target.id)
const prior = await tx.superTabSessionScope.findUnique({ where: { id } })
+ if (prior?.releasedTabIds.includes(state.id)) fail('SESSION_RELEASED', 'This session was withdrawn while stopping in this Swarm. Start a new Harness here or use it in another Swarm.')
+ if (prior?.closeLeaseUntil && prior.closeLeaseUntil.getTime() > now) fail('CLOSE_PENDING', 'Another Swarm is stopping this session. Wait up to two minutes, then try again.')
+ if (prior?.stopReleaseId) fail('STOP_REQUESTED', 'This session is stopping. Wait for its host or withdraw it before contributing another session.')
+ const running = await tx.superTabRun.findUnique({ where: { id: target.id } })
+ if (running?.assignmentId.startsWith('release-')) fail('STOP_REQUESTED', 'This session is stopping. Wait for its host or force-withdraw it before contributing another session.')
let scopes = prior?.scopeIds ?? []
if (!prior) {
// Sessions contributed before project privacy existed may already appear
@@ -32,7 +37,7 @@ export async function bindSession(tx: Prisma.TransactionClient, state: SuperTabS
export async function makeProjectPrivate(tx: Prisma.TransactionClient, state: SuperTabState, projectId: string) {
const scope = scopeId(state, projectId)
- for (const target of state.agents.filter(a => agentProjectId(state, a) === projectId)) await bindSession(tx, state, target)
+ for (const target of state.agents.filter(a => agentProjectId(state, a) === projectId && a.workDecision !== 'stop')) await bindSession(tx, state, target)
const bindings = await tx.superTabSessionScope.findMany({ where: { scopeIds: { has: scope } } })
if (bindings.some(b => b.scopeIds.some(id => id !== scope))) {
fail('PROJECT_SESSION', 'An agent terminal from this project was shared elsewhere. Create a new private project for private work.')
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 97b20cebe..6f1ad67fb 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -10,12 +10,12 @@ import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_AT
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
-import { canReadAgent, canReadProject, groupProject, projectsOf, readConversation, type ProjectVisibility } from './projects.js'
+import { canReadAgent, canReadProject, groupProject, projectsOf, agentProjectId, readConversation, type ProjectVisibility } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
import {
- activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,
+ activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
SuperTabError, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,
} from './model.js'
import { holdNoticeText, type HoldReason } from './holdNotice.js'
@@ -301,6 +301,14 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
const row = await this.row(tx, user, tabId)
const original = stateOf(row)
+ // Removal retries can arrive after the actor itself left. Return only this host's exact prior receipt.
+ if (command.type === 'agent.remove' && asAgentId === command.agentId && !original.agents.some(a => a.id === asAgentId)) {
+ const prior = await tx.superTabOperation.findUnique({ where: { id: stableId(tabId, `agent:${asAgentId}`, operationId) } })
+ if (prior && prior.requestHash === hash(command) && (prior.result as Record<string, unknown>).releasedBy === user.sub) {
+ return { revision: prior.revision, result: prior.result }
+ }
+ fail('FORBIDDEN', 'Only the execution host can confirm this removal.', 403)
+ }
if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)
const actor = hostMachineId && 'startId' in command
? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
@@ -388,7 +396,7 @@ export class SuperTabStore {
const effects = applyCommand(original, actor, command, context)
if (command.type === 'agent.add' || command.type === 'agent.started') {
const target = agent(effects.state, effects.result.agentId as string)
- await bindSession(tx, effects.state, target)
+ await bindSession(tx, effects.state, target, context.now)
}
if (command.type === 'project.sharing' && command.visibility === 'private') {
await makeProjectPrivate(tx, effects.state, command.projectId)
@@ -417,6 +425,41 @@ export class SuperTabStore {
}
for (const message of effects.messages) conversation(effects.state, message.conversationId).lastMessageSequence = revision
noteProjectReports(effects.state, effects.messages, revision, context.now)
+ if (command.type === 'agent.release' && command.decision === 'stop') {
+ const target = agent(effects.state, command.agentId)
+ const assignmentId = `release-${target.releaseId}`
+ const running = await tx.superTabRun.findUnique({ where: { id: target.id } })
+ if (running && (running.tabId !== tabId || running.assignmentId !== assignmentId)) fail('AGENT_BUSY', 'This agent already owns active work in a Swarm or is stopping elsewhere.')
+ const registrations = await tx.superTab.findMany({ where: { autonomousEnv: original.environment, machineIds: { has: target.machineId }, id: { not: tabId } } })
+ if (registrations.some(row => stateOf(row).agents.some(a => a.id === target.id && a.machineOwnerId === target.machineOwnerId))) {
+ fail('SESSION_SHARED', 'This session is still shared with another Swarm. Withdraw it there before stopping it here.')
+ }
+ // Serialize new contributions with stop intent; bindSession writes this same native-session record.
+ const scopeId = stableId('swarm-session', original.environment, target.machineOwnerId, target.id)
+ const scope = await tx.superTabSessionScope.findUnique({ where: { id: scopeId } })
+ await tx.superTabSessionScope.upsert({ where: { id: scopeId },
+ create: { id: scopeId, scopeIds: [stableId(tabId, agentProjectId(original, target))], stopReleaseId: target.releaseId },
+ update: { scopeIds: scope?.scopeIds ?? [], stopReleaseId: target.releaseId } })
+ // The same global uniqueness fence as work.assign: another public Swarm cannot assign this native session during close.
+ if (!running) await tx.superTabRun.create({ data: { id: target.id, tabId, assignmentId, machineId: target.machineId, harnessId: target.harnessId } })
+ }
+ if (command.type === 'agent.stopLease') {
+ const target = agent(effects.state, command.agentId)
+ const id = stableId('swarm-session', original.environment, target.machineOwnerId, target.id)
+ const reservation = effects.state.harnessReservations?.find(r => r.machineId === target.machineId && r.harnessId === target.harnessId)
+ await tx.superTabSessionScope.update({ where: { id }, data: {
+ closeLeaseId: effects.result.leaseId as string, closeLeaseUntil: new Date(effects.result.expiresAt as number),
+ closeLeaseGeneration: reservation?.generation ?? null,
+ } })
+ }
+ if (command.type === 'agent.remove' && (actor.kind === 'agent' || effects.result.forceReleased)) {
+ const target = agent(original, command.agentId)
+ await tx.superTabRun.deleteMany({ where: { id: target.id, tabId, assignmentId: `release-${target.releaseId}` } })
+ const id = stableId('swarm-session', original.environment, target.machineOwnerId, target.id)
+ await tx.superTabSessionScope.upsert({ where: { id },
+ create: { id, scopeIds: [], ...(effects.result.forceReleased ? { releasedTabIds: [tabId] } : {}) },
+ update: { stopReleaseId: null, ...(effects.result.forceReleased ? { releasedTabIds: { push: tabId } } : { closeLeaseId: null, closeLeaseUntil: null, closeLeaseGeneration: null }) } })
+ }
if (command.type === 'work.assign') {
const assigned = conversation(effects.state, command.conversationId).assignment!
const running = await tx.superTabRun.findUnique({ where: { id: assigned.agentId } })
@@ -651,7 +694,8 @@ export class SuperTabStore {
groupProject(state, conversation(state, s.request.conversationId)).id === p.id))
.map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,
conversationIds: state.conversations.filter(c => groupProject(state, c).id === p.id).map(c => c.id) })) } : {}),
- harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]
+ reservations: (state.harnessReservations ?? []).filter(r => r.machineId === machineId).map(({ harnessId, generation }) => ({ harnessId, generation })),
+ harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.harnessReservations ?? []).filter(r => r.machineId === machineId).map(r => r.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]
})
})
}
@@ -665,6 +709,18 @@ export class SuperTabStore {
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
pool.observation = { ...observation, quotas: observation.quotas.filter(q => pool.engines.includes(q.engine)), receivedAt: this.now() }
+ // Current-generation physical stop proof also finishes a close whose membership was already withdrawn.
+ for (const proof of observation.stoppedReservations ?? []) {
+ if (!observation.stoppedHarnessIds.includes(proof.harnessId)) continue
+ const reservation = state.harnessReservations?.find(r => r.machineId === machineId && r.harnessId === proof.harnessId && r.generation === proof.generation)
+ if (!reservation) continue
+ state.harnessReservations = state.harnessReservations?.filter(r => r !== reservation)
+ state.releasedHarnesses ??= []
+ if (!state.releasedHarnesses.some(r => r.machineId === machineId && r.harnessId === proof.harnessId)) state.releasedHarnesses.push({ machineId, harnessId: proof.harnessId })
+ const id = stableId('swarm-session', state.environment, user.sub, stableId(machineId, proof.harnessId))
+ await tx.superTabSessionScope.updateMany({ where: { id, closeLeaseGeneration: proof.generation },
+ data: { closeLeaseId: null, closeLeaseUntil: null, closeLeaseGeneration: null } })
+ }
await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { state: json(state), revision: row.revision + 1 } })
return { revision: row.revision + 1 }
})
@@ -690,6 +746,7 @@ export class SuperTabStore {
c.assignment!.execution.machineId === machineId && ['needs_human', 'blocked'].includes(c.assignment!.status))?.assignment
const attention = waiting ? { assignmentId: waiting.id, status: waiting.status, result: waiting.result?.slice(0, 500) ?? null } : null
result.push({ tabId: row.id, tabName: state.name, revision: row.revision, paused: state.paused, active, attention, agent: target,
+ stopRequested: target.workDecision === 'stop' && !state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id),
observers: people.filter(p => p.id !== user.sub &&
canReadAgent(state, { kind: 'person', userId: p.id, email: p.email }, target))
.map(p => ({ email: p.email, userId: p.id })) })
@@ -865,6 +922,7 @@ export class SuperTabStore {
const notices: MessageDraft[] = []
if (group && activeWork(group)) {
assignment.status = 'stopped'
+ finishWorker(state, assignment.agentId)
assignment.result = 'The execution host confirmed that this harness stopped.'
await tx.superTabRun.deleteMany({ where: { tabId, assignmentId } })
await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId,
diff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.ts
index 2462c23e5..691f942e4 100644
--- a/cli/e2e/superTabs.e2e.ts
+++ b/cli/e2e/superTabs.e2e.ts
@@ -51,9 +51,10 @@ it('starts either engine once, posts to its captured group and delivers shared i
const idFor = (harnessId: string) => createHash('sha256').update(JSON.stringify([ME.machineId, harnessId])).digest('hex').slice(0, 24)
relay.superTabs = async (method, raw, body) => {
const url = new URL(raw, relay.httpUrl), path = url.pathname
+ if (path === `/api/super-tabs/hosts/${ME.machineId}/pools`) return { data: [] }
if (path === `/api/super-tabs/hosts/${ME.machineId}/assignments`) return { data: assignments }
if (path.endsWith('/stopped')) { stopReceipts.push(body); assignments.length = 0; return { data: { confirmed: true } } }
- if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: allowed ? agents.map(agent => ({ tabId: TAB, agent, observers: [] })) : [] }
+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: allowed ? agents.map(agent => ({ tabId: TAB, agent, stopRequested: agent.workDecision === 'stop', observers: [] })) : [] }
if (!allowed) return { status: 403, error: { code: 'FORBIDDEN', message: 'The contribution was withdrawn.' } }
if (path === `/api/super-tabs/${TAB}/native` && method === 'POST') {
const agent = agents.find(a => a.id === body.agentId)!
@@ -75,7 +76,7 @@ it('starts either engine once, posts to its captured group and delivers shared i
if (loseNativeReply) { loseNativeReply = false; return { status: 503, error: { code: 'BACKEND_UNAVAILABLE', message: 'Lost fixture reply' } } }
return { data: { eventId } }
}
- if (path === `/api/super-tabs/${TAB}`) return { data: { revision, state: { id: TAB, agents } } }
+ if (path === `/api/super-tabs/${TAB}`) return { data: { revision, state: { id: TAB, agents, conversations: [] } } }
if (path === `/api/super-tabs/${TAB}/conversations/feature/messages`) {
expect(agents.some(agent => agent.id === url.searchParams.get('asAgentId'))).toBe(true)
return { data: { messages: [{ id: url.searchParams.get('messageId'), text: 'Should the offline queue survive restart?' }] } }
@@ -88,6 +89,7 @@ it('starts either engine once, posts to its captured group and delivers shared i
if (!starts.has(startId)) starts.set(startId, { id: startId, creationId: `super-${startId}`, request: command.request, dispatched: false, harnessId: null })
return { data: { result: { startId } } }
}
+ if (command.type === 'agent.stopLease') return { data: { result: { expiresAt: Date.now() + 120_000, durationMs: 120_000 } } }
const start = starts.get(String(command.startId))
if (command.type === 'agent.startDispatch') {
if (start!.dispatched) throw new Error('Duplicate dispatch')
@@ -95,7 +97,8 @@ it('starts either engine once, posts to its captured group and delivers shared i
} else if (command.type === 'agent.started') {
start!.harnessId = command.harnessId
const id = idFor(String(command.harnessId))
- if (!agents.some(a => a.id === id)) agents.push({ id, harnessId: command.harnessId, machineId: ME.machineId, configuration: command.configuration })
+ if (!agents.some(a => a.id === id)) agents.push({ id, harnessId: command.harnessId, machineId: ME.machineId, configuration: command.configuration,
+ ...(command.startedSession ? { startedSession: { ...object(command.startedSession), creationId: start!.creationId } } : {}) })
return { data: { result: { agentId: id } } }
} else if (command.type === 'conversation.create') {
tasks.push(body)
@@ -107,6 +110,12 @@ it('starts either engine once, posts to its captured group and delivers shared i
agent.configuration = command.configuration
agent.configurationVersion = body.operationId
}
+ else if (command.type === 'agent.remove') {
+ const index = agents.findIndex(a => a.id === command.agentId)
+ expect(index).toBeGreaterThanOrEqual(0)
+ expect(agents[index]).toMatchObject({ workDecision: 'stop', releaseId: command.releaseId })
+ agents.splice(index, 1)
+ }
else if (command.type === 'agent.startFailed') start!.error = command.error
else throw new Error(`Unexpected command ${command.type}`)
revision++
@@ -281,19 +290,19 @@ it('starts either engine once, posts to its captured group and delivers shared i
const reads = deliveryReads
await until('further host polls without replay', () => deliveryReads > reads + 3 || null, 10_000, 250)
expect(readFileSync(join(d.root, 'submitted-prompts'), 'utf8')).not.toContain('do-not-replay-without-journal')
- const refused = await run(['start', 'refused-mode', JSON.stringify({
+ const refused = await run(['start', 'refused-config', JSON.stringify({
conversationId: 'feature', machineId: ME.machineId, engine: 'claude', name: 'Refused builder',
- cwd, worktree: false, permissionMode: 'not-a-mode', requirements: { memoryBytes: 0, diskBytes: 1,
+ cwd, worktree: false, codexHome: join(d.root, 'unused-codex-home'), requirements: { memoryBytes: 0, diskBytes: 1,
maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false },
})])
expect(refused.code, JSON.stringify(refused.answer)).toBe(1)
- expect(refused.answer).toMatchObject({ error: 'START_FAILED', detail: expect.stringContaining('permission mode') })
- expect(starts.get('start-refused-mode')!.error).toContain('before starting an agent')
- const creationId = starts.get('start-refused-mode')!.creationId
+ expect(refused.answer).toMatchObject({ error: 'START_FAILED', detail: expect.stringContaining('codexHome') })
+ expect(starts.get('start-refused-config')!.error).toContain('before starting an agent')
+ const creationId = starts.get('start-refused-config')!.creationId
expect(await client.request('agent_create_status', { creationId })).toMatchObject({ creationId, state: 'cancelled' })
// Even a delayed valid create cannot revive the cancelled request.
expect(await client.request('agent_create', { engine: 'claude', cwd, creationId }, 30_000)).toMatchObject({ creationId, state: 'cancelled' })
- expect((await run(['resume', 'start-refused-mode'])).answer).toMatchObject({ error: 'START_FAILED' })
+ expect((await run(['resume', 'start-refused-config'])).answer).toMatchObject({ error: 'START_FAILED' })
const listed = await client.request('agents_list')
expect(listed.agents).toHaveLength(3)
const worker = listed.agents.find((a: Record<string, any>) => a.id === starts.get('start-claude')!.harnessId)
@@ -337,6 +346,26 @@ it('starts either engine once, posts to its captured group and delivers shared i
const reserved = reservations.find(r => r.ok)!.reservationId
expect(await client.request('agent_create_cancel', { creationId: reserved })).toMatchObject({ state: 'cancelled' })
expect(await client.request('super_tabs', { action: 'observeCapacity', creationId: reserved })).toMatchObject({ released: true })
+ // A person-created session stays open even if a stale backend asks the Swarm host to stop it.
+ const contributed = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true, prompt: 'Report that this personal session is ready.' }, 90_000)
+ expect(contributed.error, JSON.stringify(contributed)).toBeUndefined()
+ const contributedId = idFor(contributed.agent.id)
+ agents.push({ id: contributedId, harnessId: contributed.agent.id, machineId: ME.machineId, workDecision: 'stop', releaseId: 'personal-session-stop' })
+ await until('the core to refuse closing a personal session', () => d.log().includes('not the original Swarm launch') || null, 15_000, 100)
+ expect((await client.request('agents_list')).agents.some((a: Record<string, any>) => a.id === contributed.agent.id)).toBe(true)
+ agents.splice(agents.findIndex(a => a.id === contributedId), 1)
+ // Only the recorded original Swarm launch may be closed through the service process.
+ const launchedId = String(starts.get('start-codex')!.harnessId)
+ const launched = agents.find(a => a.harnessId === launchedId)!
+ expect(launched.startedSession).toMatchObject({ creationId: starts.get('start-codex')!.creationId })
+ launched.workDecision = 'stop'; launched.releaseId = 'finished-worker-release'
+ await until('the host process to close and remove the original Swarm worker', () => !agents.some(a => a.id === launched.id) || null, 60_000, 250)
+ expect((await client.request('agents_list')).agents.some((a: Record<string, any>) => a.id === launchedId)).toBe(false)
+ await until('removed worker retention to be released', () => !retainedHarnesses(d.dataDir).has(launchedId) || null, 10_000, 100)
+ const goneId = idFor('deleted-native-worker')
+ agents.push({ id: goneId, harnessId: 'deleted-native-worker', machineId: ME.machineId, workDecision: 'stop', releaseId: 'deleted-worker-release' })
+ await until('a deleted session without a stopped record to be withdrawn', () => !agents.some(a => a.id === goneId) || null, 15_000, 100)
+ expect((await client.request('agents_list')).agents.some((a: Record<string, any>) => a.id === lead.agent.id)).toBe(true)
allowed = false
const denied = await run(['post', 'feature', 'not allowed', 'after-removal'])
expect(denied.code).toBe(1)
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index e230a879f..0270030de 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -6,6 +6,68 @@ import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
describe('the core API services stand on', () => {
+ it('closes only the original Swarm-started native session and treats an absent session as gone', async () => {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
+ const deps = coreDeps(), byAgent = vi.fn(() => session as RegisteredSession | undefined)
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))
+ const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], closeAgent, creationStatus })
+ expect(await core.agents.closeSwarm!(request)).toEqual({ closed: true })
+ expect(closeAgent).toHaveBeenCalledWith({ agentId: 'worker', sessionId: 'native', createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt })
+ closeAgent.mockClear()
+ byAgent.mockReturnValue({ ...session, startedBy: undefined })
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
+ byAgent.mockReturnValue({ ...session, registeredAt: 2000 })
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'AGENT_CHANGED' })
+ byAgent.mockReturnValue({ ...session, sessionId: 'replacement' })
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'AGENT_CHANGED' })
+ byAgent.mockReturnValue(session)
+ creationStatus.mockResolvedValueOnce({ creationId: request.creationId, state: 'created', agentId: 'other' })
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
+ expect(closeAgent).not.toHaveBeenCalled()
+ const withoutCreation = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], closeAgent })
+ expect(await withoutCreation.agents.closeSwarm!(request)).toEqual({ error: 'NOT_SWARM_STARTED' })
+ const noLifecycle = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], creationStatus })
+ expect(await noLifecycle.agents.closeSwarm!(request)).toEqual({ error: 'UNSUPPORTED' })
+ for (const partial of [{ agentId: 'worker' }, { ...request, creationId: '' }, { ...request, sessionId: undefined }, { ...request, createdAt: undefined }]) {
+ expect(await core.agents.closeSwarm!(partial)).toEqual({ error: 'NOT_SWARM_STARTED' })
+ }
+ byAgent.mockReturnValue(undefined)
+ expect(await core.agents.closeSwarm!({ agentId: 'worker' })).toEqual({ closed: true })
+ })
+
+ it('refuses a personal resume before or during the original creation lookup', async () => {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const, resumeOnly: true }
+ const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const creationStatus = vi.fn(async () => {
+ session.resumeOnly = true
+ return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' }
+ })
+ const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent: () => session } as CoreApiDeps['registry'], closeAgent, creationStatus })
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: expect.any(String) })
+ expect(creationStatus).not.toHaveBeenCalled()
+ session.resumeOnly = false
+ expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: expect.any(String) })
+ expect(closeAgent).not.toHaveBeenCalled()
+ })
+
+ it('refuses missing or expired close leases, including expiry during the creation lookup', async () => {
+ let now = 1000
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
+ try {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(1000).toISOString(), expiresAt: 1100 }
+ const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
+ const creationStatus = vi.fn(async () => { now = 1200; return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' } })
+ const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent: () => session } as CoreApiDeps['registry'], closeAgent, creationStatus })
+ for (const expiresAt of [undefined, NaN, 999]) expect(await core.agents.closeSwarm!({ ...request, expiresAt })).toEqual({ error: 'STOP_LEASE_EXPIRED' })
+ expect(await core.agents.closeSwarm!(request)).toEqual({ error: 'STOP_LEASE_EXPIRED' })
+ expect(closeAgent).not.toHaveBeenCalled()
+ } finally { clock.mockRestore() }
+ })
+
it('exposes an optional native-turn observer without importing feature state', () => {
const nativeTurns = vi.fn(async () => null)
expect(createCoreApi({ ...coreDeps(), nativeTurns }).transcripts.nativeTurns).toBe(nativeTurns)
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 0deea23ce..e0028f25c 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -200,6 +200,8 @@ export interface CoreApi {
* (`SESSION_NOT_IDLE`); `now` does not. Any other harness is refused (`NOT_AGENT_STARTED`): the agent cleanup
* (services/agentCleanup.ts) closes those, and nothing else. Absent where the core does not let a service close. */
closeStarted?(agentId: string, mode: 'idle' | 'now'): Promise<AgentCloseResult>
+ /** Close only the recorded native identity started for a Swarm. Missing live sessions are already gone. */
+ closeSwarm?(request: { agentId: string; creationId?: string; sessionId?: string; createdAt?: string; expiresAt?: number }): Promise<AgentCloseResult>
/** When a live agent's conversation last moved, epoch ms: the latest dated work in its transcript
* (lib/transcriptActivity.ts), what the apps' `updatedAt` is when there is one. Null for none live, and for an
* engine that keeps no dated transcript: a hook's time or the bind's is not when it last answered. Absent where
@@ -1837,6 +1839,21 @@ export function createCoreApi({
summaries: summaries ?? (async () => ({})),
// Decided here, not in the service: whatever the cleanup asks, from its process or this one, the core closes only
// a harness another agent started, the conversation it reviewed (`agent_close`'s identity), and keeps it.
+ closeSwarm: async request => {
+ const session = registry.byAgent(request.agentId)
+ // This is the authoritative live registry, not a service's possibly old snapshot or a failed read.
+ if (!session) return { closed: true }
+ if (session.startedBy !== 'agent' || session.resumeOnly || !request.creationId || typeof request.sessionId !== 'string' || !request.createdAt) return { error: 'NOT_SWARM_STARTED' }
+ if (session.sessionId !== request.sessionId || session.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
+ if (!Number.isFinite(request.expiresAt) || request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
+ const creation = await creationStatus?.(request.creationId)
+ if (creation?.state !== 'created' || creation.agentId !== request.agentId) return { error: 'NOT_SWARM_STARTED' }
+ if (request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
+ const latest = registry.byAgent(request.agentId)
+ if (!latest || latest.startedBy !== 'agent' || latest.resumeOnly || latest.sessionId !== request.sessionId
+ || latest.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
+ return closeAgent ? closeAgent({ agentId: request.agentId, sessionId: request.sessionId, createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt }) : { error: 'UNSUPPORTED' }
+ },
closeStarted: async (agentId, mode) => {
const session = registry.byAgent(agentId)
if (!session) return { error: 'AGENT_CHANGED' }
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 5e112258d..a3836f6cd 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -202,3 +202,18 @@ describe('what an experiment in its own process may ask of the core', () => {
expect(await createForExperiment(null, request)).toEqual({ ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot create agents.' })
})
})
+
+it('exposes identity-bound close only to the Swarm service and validates its native identity', async () => {
+ const closeSwarm = vi.fn(async () => ({ closed: true as const })), core = fakeCore({ agents: { closeSwarm } })
+ const allowed = new Set(['superTabs', 'orchestrator'])
+ const payload = { expiresAt: Date.now() + 120_000, agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: '2026-10-22T00:00:00.000Z' }
+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_swarm', payload)).toEqual({ closed: true })
+ expect(closeSwarm).toHaveBeenCalledWith(payload)
+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_swarm', { agentId: 'gone' })).toEqual({ closed: true })
+ expect(closeSwarm).toHaveBeenLastCalledWith({ agentId: 'gone' })
+ expect(await answerExperimentQuery(core, allowed, 'orchestrator', 'close_swarm', payload)).toEqual({ error: 'NOT_SUPER_TABS' })
+ for (const invalid of [{ ...payload, agentId: '' }, { ...payload, sessionId: 1 }, { ...payload, createdAt: 'bad' }, { ...payload, creationId: 'bad' }, { ...payload, creationId: 4 }, { ...payload, createdAt: 4 }, { ...payload, expiresAt: 'later' }, { ...payload, expiresAt: Infinity }]) {
+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_swarm', invalid)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ expect(await answerExperimentQuery(fakeCore(), allowed, 'superTabs', 'close_swarm', payload)).toEqual({ error: 'UNSUPPORTED' })
+})
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index c1d183d56..302851a14 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -34,7 +34,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'stopped', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -68,6 +68,18 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
switch (query) {
case 'shown':
return shownAgents(core)
+ case 'close_swarm': {
+ if (service !== 'superTabs') return { error: 'NOT_SUPER_TABS' }
+ const { agentId, creationId, sessionId, createdAt, expiresAt } = payload
+ if (!/^[A-Za-z0-9_-]{1,160}$/.test(text(agentId)) ||
+ creationId !== undefined && (typeof creationId !== 'string' || !/^[A-Za-z0-9_-]{16,96}$/.test(creationId)) ||
+ sessionId !== undefined && typeof sessionId !== 'string' ||
+ createdAt !== undefined && (typeof createdAt !== 'string' || !Number.isFinite(Date.parse(createdAt))) ||
+ expiresAt !== undefined && (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt))) return { error: 'INVALID_REQUEST' }
+ return { ...await (core.agents.closeSwarm?.({ agentId: agentId as string,
+ ...(typeof creationId === 'string' ? { creationId } : {}), ...(typeof sessionId === 'string' ? { sessionId } : {}),
+ ...(typeof createdAt === 'string' ? { createdAt } : {}), ...(typeof expiresAt === 'number' ? { expiresAt } : {}) }) ?? { error: 'UNSUPPORTED' }) }
+ }
case 'stopped':
return { stopped: !!text(payload.agentId) && await core.agents.stopped?.(text(payload.agentId)) === true }
case 'creation_status':
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index e2d599b00..ac80714e0 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -35,6 +35,25 @@ beforeEach(() => {
})
afterEach(() => { service.dispose(); vi.useRealTimers(); vi.restoreAllMocks(); for (const s of registry.list()) registry.removeAgent(s.agentId) })
+it.each(['before', 'activity', 'checkpoint'] as const)('a Swarm close preserves a personally resumed worker at %s', async phase => {
+ row.startedBy = 'agent'
+ if (phase === 'before') row.resumeOnly = true
+ if (phase === 'activity') vi.mocked(deps.activity).mockImplementation(async () => { row.resumeOnly = true; return 'idle' })
+ if (phase === 'checkpoint') vi.mocked(deps.checkpoint).mockImplementation(async () => { row.resumeOnly = true })
+ const guarded = { ...request('now'), onlyIfOriginalLaunch: true }
+ expect(await service.request(guarded)).toMatchObject({ error: expect.any(String) })
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+
+it.each(['before', 'activity', 'checkpoint'] as const)('an expired native close lease preserves the worker at %s', async phase => {
+ const guarded = { ...request('now'), expiresAt: time + 1 }
+ if (phase === 'before') time += 2
+ if (phase === 'activity') vi.mocked(deps.activity).mockImplementation(async () => { time += 2; return 'idle' })
+ if (phase === 'checkpoint') vi.mocked(deps.checkpoint).mockImplementation(async () => { time += 2 })
+ expect(await service.request(guarded)).toMatchObject({ error: expect.any(String) })
+ expect(registry.byAgent(row.agentId)).toBe(row)
+})
+
it('backs up an idle session before stopping, without treating a tab switch as Close', async () => {
service.start()
expect(deps.activity).not.toHaveBeenCalled()
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index 4221ffa72..219ed0083 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -16,7 +16,7 @@ export type AgentClosePlan = {
state: 'waiting' | 'failed'
detail?: string
}
-export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean }
+export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number }
/** `withoutConversation`: closed while still starting, before Harness could read its conversation, so none is kept. */
export type AgentCloseResult = { closed?: true; withoutConversation?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }
@@ -90,10 +90,10 @@ function stillStarting(s: RegisteredSession, at: number): boolean {
/** What makes two requests the same one: the agent, the mode, and whether it holds only while no tab
* shows the agent. A cleanup that finds the agent on screen again must not answer the person's own close. */
function jobKey(request: AgentCloseRequest): string {
- return JSON.stringify([request.agentId, request.mode, request.onlyIfHidden === true])
+ return JSON.stringify([request.agentId, request.mode, request.onlyIfHidden === true, request.onlyIfOriginalLaunch === true, request.expiresAt])
}
function matches(s: RegisteredSession | undefined, request: AgentCloseRequest, at: number): s is RegisteredSession {
- if (!s || new Date(s.registeredAt).toISOString() !== request.createdAt) return false
+ if (!s || (request.expiresAt !== undefined && request.expiresAt <= at) || (request.onlyIfOriginalLaunch && (s.startedBy !== 'agent' || s.resumeOnly)) || new Date(s.registeredAt).toISOString() !== request.createdAt) return false
// Asked of a harness still starting, which has bound its first conversation since the list the request was made
// from: the same harness, and the close keeps that conversation. Refused as changed, a close sent in the seconds a
// Codex binds was answered "changed while closing".
@@ -211,7 +211,9 @@ export class CloseAgentService {
first: AgentCloseResult): Promise<AgentCloseResult> {
const same = () => {
const s = this.deps.registry.byAgent(request.agentId)
- return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision && s && harnessIdentity(s) === harness ? s : undefined
+ return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision && s && harnessIdentity(s) === harness
+ && (request.expiresAt === undefined || request.expiresAt > this.now())
+ && (!request.onlyIfOriginalLaunch || (s.startedBy === 'agent' && !s.resumeOnly)) ? s : undefined
}
let tried = target, result = first, waiting = false
for (;;) {
@@ -245,6 +247,8 @@ export class CloseAgentService {
const s = this.deps.registry.byAgent(request.agentId)
return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision
&& s && identity(s) === target
+ && (request.expiresAt === undefined || request.expiresAt > this.now())
+ && (!request.onlyIfOriginalLaunch || (s.startedBy === 'agent' && !s.resumeOnly))
&& (!request.onlyIfHidden || this.deps.openTabs?.isHidden(s)) ? s : undefined
}
try {
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index 1002fe535..931510246 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -342,3 +342,13 @@ it('asks for native stop evidence and treats an absent or failed link as unknown
expect(await api.agents.stopped!('a')).toBe(false)
expect(await processCoreApi('/data', 'superTabs').agents.stopped!('a')).toBe(false)
})
+
+it('carries the exact native close identity through the service process and fails closed without the core', async () => {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: '2026-10-22T00:00:00.000Z' }
+ const ask = vi.fn(async () => ({ closed: true as const }))
+ expect(await processCoreApi('/data', 'superTabs', { ask }).agents.closeSwarm!(request)).toEqual({ closed: true })
+ expect(ask).toHaveBeenCalledWith('close_swarm', request)
+ ask.mockRejectedValueOnce(new Error('Gone'))
+ expect(await processCoreApi('/data', 'superTabs', { ask }).agents.closeSwarm!(request)).toEqual({ error: 'SERVICE_UNAVAILABLE' })
+ expect(await processCoreApi('/data', 'superTabs').agents.closeSwarm!(request)).toEqual({ error: 'SERVICE_UNAVAILABLE' })
+})
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index fd1161401..f719da9f1 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -120,6 +120,8 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
live,
displayName: (session) => (session as ShownAgent).displayName ?? '',
byAgent: (agentId) => live().find((session) => session.agentId === agentId),
+ closeSwarm: async request => await (ask?.('close_swarm', { ...request }) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }))
+ .catch(() => ({ error: 'SERVICE_UNAVAILABLE' })),
stopped: async agentId => (await ask?.('stopped', { agentId }).catch(() => null))?.stopped === true,
creationStatus: async creationId => creationObservation(creationId,
(await ask?.('creation_status', { creationId }).catch(() => null))?.observation),
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 5ad6d5dc5..bbe164692 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -34,7 +34,7 @@ function setup(messageFields: Record<string, unknown> = {}) {
return { status: 200, body: { success: true, data } }
})
const core = fakeCore({ dataDir: dir,
- agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) },
+ agents: { creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'harness' })), byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) },
account: { backend: call },
turns: { onDelivery: vi.fn(fn => { listeners.add(fn); return () => { listeners.delete(fn) } }) },
})
@@ -436,7 +436,7 @@ describe('Super Tab waits for the Harness Pro', () => {
})
const superTabs = { attention: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
- agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
+ agents: { creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'harness' })), byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
const open = () => { const host = new SuperTabHost(core, 'machine-1', { log: vi.fn() }); hosts.push(host); return host }
const first = open()
await first.tick()
@@ -496,3 +496,162 @@ describe('Super Tab waits for the Harness Pro', () => {
expect(superTabs.attention).toHaveBeenCalledTimes(2)
})
})
+
+it('stops a requested worker once, confirms removal, and releases retention on the next roster', async () => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', sessionId: 'native', registeredAt: 0, startedBy: 'agent' } as never)
+ let closed = false, removed = false, acknowledgements = 0
+ const target = { id: 'agent', harnessId: 'harness', machineId: 'machine-1', workDecision: 'stop', startedSession: { creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(0).toISOString() } }
+ t.core.agents.stopped = async () => closed
+ t.core.agents.closeSwarm = async request => { expect(request.agentId).toBe('harness'); expect(request.expiresAt).toBeLessThanOrEqual(Date.now() + 120_000); closed = true; return { closed: true } }
+ t.core.account.backend = async (method, path, body) => {
+ if ((body as any)?.command?.type === 'agent.stopLease') return { status: 200, body: { data: { result: { expiresAt: Date.now() + 3_600_000, durationMs: 120_000 } } } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: removed ? [] : [{ tabId: 'tab', agent: target, stopRequested: true }] } }
+ if (method === 'GET') return { status: 200, body: { data: { state: { agents: [target], conversations: [] } } } }
+ acknowledgements++; removed = true
+ return { status: 200, body: { data: {} } }
+ }
+ await host.tick()
+ await vi.waitFor(() => expect(acknowledgements).toBe(1))
+ expect(closed).toBe(true)
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ await host.tick()
+ expect(retainedHarnesses(t.dir).size).toBe(0)
+ expect(acknowledgements).toBe(1)
+})
+
+it.each(['active', 'foreign', 'changed', 'missing', 'refused', 'unconfirmed', 'unsupported'])('withholds closure or acknowledgement when stop safety is %s', async kind => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', sessionId: 'native', registeredAt: 0, startedBy: 'agent' } as never)
+ const target = { id: 'agent', harnessId: 'harness', machineId: 'machine-1', workDecision: 'stop', releaseId: 'release-1', startedSession: { creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(0).toISOString() } }
+ const close = vi.fn(async () => kind === 'refused' ? { error: 'NOT_SWARM_STARTED' } : kind === 'unconfirmed' ? { deferred: true as const } : { closed: true as const })
+ const acknowledge = vi.fn()
+ t.core.agents.closeSwarm = kind === 'unsupported' ? undefined : close
+ t.core.agents.stopped = async () => false
+ t.core.account.backend = async (method, path, body) => {
+ if ((body as any)?.command?.type === 'agent.stopLease') return { status: 200, body: { data: { result: { expiresAt: Date.now() + 3_600_000, durationMs: 120_000 } } } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: [{ tabId: 'tab', agent: target, stopRequested: true }] } }
+ if (method === 'GET') return { status: 200, body: { data: { state: {
+ agents: kind === 'missing' ? [] : [{ ...target, machineId: kind === 'foreign' ? 'foreign' : target.machineId, releaseId: kind === 'changed' ? 'release-2' : 'release-1' }],
+ conversations: [{ assignment: { agentId: 'agent', status: kind === 'active' ? 'working' : 'done' } }],
+ } } } }
+ acknowledge(); return { status: 200, body: { data: {} } }
+ }
+ await host.tick()
+ // Finish the asynchronous lifecycle pickup without relying on the delivery poll to wait on it.
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(acknowledge).not.toHaveBeenCalled()
+ if (['active', 'foreign', 'changed', 'missing', 'unsupported'].includes(kind)) expect(close).not.toHaveBeenCalled()
+ else expect(close).toHaveBeenCalledOnce()
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+})
+
+it('retries a lost removal acknowledgement from native stopped evidence without closing twice', async () => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', sessionId: 'native', registeredAt: 0, startedBy: 'agent' } as never)
+ const target = { id: 'agent', harnessId: 'harness', machineId: 'machine-1', workDecision: 'stop', startedSession: { creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(0).toISOString() } }
+ let stopped = false, attempts = 0
+ const close = vi.fn()
+ t.core.agents.closeSwarm = async () => { if (!stopped) { close(); stopped = true }; return { closed: true } }
+ t.core.agents.stopped = async () => stopped
+ t.core.account.backend = async (method, path, body) => {
+ if ((body as any)?.command?.type === 'agent.stopLease') return { status: 200, body: { data: { result: { expiresAt: Date.now() + 3_600_000, durationMs: 120_000 } } } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: [{ tabId: 'tab', agent: target, stopRequested: true }] } }
+ if (method === 'GET') return { status: 200, body: { data: { state: { agents: [target], conversations: [] } } } }
+ attempts++
+ if (attempts === 1) throw new Error('Lost acknowledgement')
+ return { status: 200, body: { data: {} } }
+ }
+ await host.tick(); await vi.waitFor(() => expect(attempts).toBe(1))
+ t.wait(5_000); await host.tick(); await vi.waitFor(() => expect(attempts).toBe(2))
+ expect(close).toHaveBeenCalledOnce()
+})
+
+
+function releaseFixture(nativeKind = 'swarm', result: Record<string, unknown> = { error: 'NOT_SWARM_STARTED' }) {
+ const t = setup(), host = t.open()
+ const identity = { creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(0).toISOString() }
+ const target = { id: 'agent', harnessId: 'harness', machineId: 'machine-1', workDecision: 'stop', releaseId: 'release-1',
+ ...(nativeKind === 'missing-record' ? {} : { startedSession: identity }) }
+ const native = { agentId: 'harness', sessionId: nativeKind === 'changed' ? 'replacement' : 'native', registeredAt: 0,
+ startedBy: nativeKind === 'personal' ? undefined : 'agent', processIdentity: { pid: 1, startMarker: 'first', executable: 'codex' } }
+ const lookup = vi.fn(async () => ({ creationId: identity.creationId, state: 'created' as const, agentId: 'harness' }))
+ const close = vi.fn(async () => result), lease = vi.fn(), remove = vi.fn()
+ t.core.agents.byAgent = vi.fn(() => native as never)
+ t.core.agents.creationStatus = lookup
+ t.core.agents.closeSwarm = close as NonNullable<CoreApi['agents']['closeSwarm']>
+ t.core.account.backend = async (method, path, body) => {
+ const command = (body as any)?.command
+ if (command?.type === 'agent.stopLease') { lease(); return { status: 200, body: { data: { result: { durationMs: 120_000 } } } } }
+ if (command?.type === 'agent.remove') { remove(); return { status: 200, body: { data: {} } } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: [{ tabId: 'tab', agent: target, stopRequested: true }] } }
+ return { status: 200, body: { data: { state: { agents: [target], conversations: [] } } } }
+ }
+ const poll = async (advance = 0) => { t.wait(advance); await host.tick(); await new Promise(resolve => setImmediate(resolve)) }
+ return { ...t, host, target, native, lookup, close, lease, remove, poll }
+}
+
+it.each(['personal', 'missing-record', 'changed'])('requests no close lease for an ineligible %s runtime', async kind => {
+ const t = releaseFixture(kind)
+ for (let i = 0; i < 10; i++) await t.poll(1_000)
+ expect(t.lease).not.toHaveBeenCalled()
+ expect(t.close).not.toHaveBeenCalled()
+})
+
+it('never acquires a lease for a creation receipt naming a different native harness', async () => {
+ const t = releaseFixture()
+ t.lookup.mockResolvedValue({ creationId: 'super-original-creation', state: 'created', agentId: 'another-harness' })
+ for (let i = 0; i < 10; i++) await t.poll(130_000)
+ expect(t.lease).not.toHaveBeenCalled()
+})
+
+it.each(['NOT_SWARM_STARTED', 'AGENT_CHANGED'])('does not keep leasing a runtime refused as %s; still clears it once gone', async error => {
+ const t = releaseFixture('swarm', { error })
+ for (let i = 0; i < 10; i++) await t.poll(130_000)
+ expect(t.lease).toHaveBeenCalledTimes(1)
+ expect(t.close).toHaveBeenCalledTimes(1)
+ vi.mocked(t.core.agents.byAgent).mockReturnValue(undefined)
+ t.close.mockResolvedValue({ closed: true })
+ await t.poll()
+ expect(t.remove).toHaveBeenCalledOnce()
+ expect(t.lease).toHaveBeenCalledTimes(1)
+})
+
+it('backs off transient close failures and caps retries for the same runtime', async () => {
+ const t = releaseFixture('swarm', { error: 'SERVICE_UNAVAILABLE' })
+ await t.poll()
+ for (let i = 0; i < 4; i++) await t.poll(1_000)
+ expect(t.lease).toHaveBeenCalledTimes(1)
+ await t.poll(1_000)
+ expect(t.lease).toHaveBeenCalledTimes(2)
+ await t.poll(14_000)
+ expect(t.lease).toHaveBeenCalledTimes(2)
+ await t.poll(1_000)
+ expect(t.lease).toHaveBeenCalledTimes(3)
+ for (let i = 0; i < 10; i++) await t.poll(130_000)
+ expect(t.lease).toHaveBeenCalledTimes(5)
+ t.native.processIdentity.startMarker = 'new-runtime'
+ await t.poll()
+ expect(t.lease).toHaveBeenCalledTimes(6)
+})
+
+
+it('backs off unavailable launch-receipt reads without writing any close leases', async () => {
+ const t = releaseFixture()
+ t.lookup.mockRejectedValue(new Error('Core temporarily unavailable'))
+ for (let i = 0; i < 10; i++) await t.poll(130_000)
+ expect(t.lookup).toHaveBeenCalledTimes(5)
+ expect(t.lease).not.toHaveBeenCalled()
+})
+
+it('rechecks authoritative native absence before retrying a lost acknowledgement', async () => {
+ const t = releaseFixture('swarm', { closed: true })
+ t.remove.mockImplementationOnce(() => { throw new Error('Lost acknowledgement') })
+ await t.poll()
+ t.close.mockResolvedValue({ error: 'NOT_SWARM_STARTED' })
+ await t.poll(5_000)
+ await t.poll(130_000)
+ expect(t.lease).toHaveBeenCalledOnce()
+ expect(t.remove).toHaveBeenCalledOnce()
+ expect(t.close).toHaveBeenLastCalledWith({ agentId: 'harness' })
+})
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index ca935aadf..b2c1e6f96 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -40,7 +40,7 @@ interface Entry {
receipt?: string
}
interface Journal { version: 1; machineId: string; entries: Record<string, Entry> }
-interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string } }
+interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string } }
export interface SuperTabHostOptions {
now?: () => number
write?: (file: string, journal: Journal) => void
@@ -65,7 +65,8 @@ const SUPER_TAB_REPLY_STYLE = 'Write to the people in this tab like a helpful co
+ 'Do not show commands, message or sequence ids, field names or error codes. '
+ 'Do not describe your own tools or permission prompts unless that blocks what they asked. '
+ 'Answer each message once: post with --reply-to MESSAGE_ID. If you have already answered a message, do not post again. '
- + 'When you hand over finished work, give the result with the revision and links they need.'
+ + 'When you hand over finished work, give the result with the revision and links they need. '
+ + 'Lead: when a worker finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon.'
/** Owns only the handoff between a durable backend claim and the core's native input.
* A process restart never interprets a lost acknowledgement as permission to type twice. */
@@ -88,6 +89,9 @@ export class SuperTabHost {
private stopped = false
private running: Promise<void> | null = null
private stopsRunning: Promise<void> | null = null
+ private readonly releases = new Set<string>()
+ /** Eligibility and failures belong to this stop and native runtime; a new runtime or stop gets a fresh decision. */
+ private readonly releaseAttempts = new Map<string, { signature: string; failures: number; retryAt: number; closed?: true }>()
private nextStopsAt = 0
private receiptsRunning: Promise<void> | null = null
private nextReceiptsAt = 0
@@ -216,6 +220,87 @@ export class SuperTabHost {
}
}
+ /** Re-read stop intent and native launch authority; require core evidence before confirming removal. */
+ private async releaseWorker(target: HostAgent): Promise<void> {
+ const { tabId, agent } = target
+ const key = `${tabId}:${agent.id}`
+ if (this.releases.has(key) || !this.core.agents.closeSwarm) return
+ const native = this.core.agents.byAgent(agent.harnessId)
+ const signature = JSON.stringify([agent.releaseId, object(agent).startedSession, native
+ ? [native.sessionId, native.registeredAt, native.startedBy, native.resumeOnly, native.processIdentity] : null])
+ const previous = this.releaseAttempts.get(key)
+ const attempt = previous?.signature === signature ? previous : { signature, failures: 0, retryAt: 0, closed: undefined }
+ if (this.now() < attempt.retryAt) return
+ this.releaseAttempts.set(key, attempt)
+ this.releases.add(key)
+ try {
+ const current = object(object(await backend(this.core, 'GET', `/api/super-tabs/${tabId}?asAgentId=${agent.id}`)).state)
+ const member = Array.isArray(current.agents) ? current.agents.map(object).find(a => a.id === agent.id) : undefined
+ if (this.stopped || member?.workDecision !== 'stop' || member.harnessId !== agent.harnessId || member.machineId !== this.machineId || member.releaseId !== agent.releaseId) return
+ if (!Array.isArray(current.conversations) || current.conversations.map(object).some(c => {
+ if (c.leadId === agent.id) return true
+ const work = object(c.assignment)
+ return work.agentId === agent.id && !['done', 'stopped'].includes(String(work.status))
+ })) return
+ if (attempt.closed) {
+ // A failed acknowledgement can outlive the native stop; a fresh core read must still rule out personal resume.
+ const confirmed = await this.core.agents.closeSwarm({ agentId: agent.harnessId })
+ if (!confirmed.closed) {
+ if (['NOT_SWARM_STARTED', 'AGENT_CHANGED'].includes(String(confirmed.error))) attempt.retryAt = Infinity
+ throw new Error(confirmed.detail ?? confirmed.error ?? 'The stopped session could not be confirmed.')
+ }
+ } else {
+ const identity = object(member.startedSession)
+ let result
+ if (!native) {
+ // The process snapshot can lag. Only the authoritative core may confirm absence; no lease can close a live row.
+ result = await this.core.agents.closeSwarm({ agentId: agent.harnessId })
+ } else {
+ if (native.startedBy !== 'agent' || native.resumeOnly || !identifier(identity.creationId)
+ || typeof identity.sessionId !== 'string' || !identity.sessionId || typeof identity.createdAt !== 'string'
+ || native.sessionId !== identity.sessionId || native.registeredAt !== Date.parse(identity.createdAt)) {
+ attempt.retryAt = Infinity
+ this.log('This session is not the original Swarm launch. Remove its stuck contribution.')
+ return
+ }
+ const creation = await this.core.agents.creationStatus?.(identity.creationId)
+ if (creation?.state === 'created' && creation.agentId !== agent.harnessId) {
+ attempt.retryAt = Infinity
+ this.log('This session is not the original Swarm launch. Remove its stuck contribution.')
+ return
+ }
+ if (creation?.state !== 'created') throw new Error('The original Swarm launch could not be confirmed. Stop will retry with backoff.')
+ if (this.stopped) return
+ // Start locally before asking: server clock skew cannot extend authority, and network delay consumes it.
+ const leaseRequestedAt = Date.now()
+ const leased = object(object(await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, {
+ operationId: `close-lease-${randomUUID()}`, asAgentId: agent.id,
+ command: { type: 'agent.stopLease', agentId: agent.id, releaseId: agent.releaseId },
+ })).result)
+ if (typeof leased.durationMs !== 'number' || !Number.isFinite(leased.durationMs) || leased.durationMs <= 0 || leased.durationMs > 120_000) throw new Error('The host could not reserve this native close. Remove a stuck contribution or update its backend.')
+ result = await this.core.agents.closeSwarm({ agentId: agent.harnessId, expiresAt: leaseRequestedAt + leased.durationMs,
+ creationId: identity.creationId, sessionId: identity.sessionId, createdAt: identity.createdAt })
+ }
+ if (!result.closed) {
+ if (['NOT_SWARM_STARTED', 'AGENT_CHANGED'].includes(String(result.error))) attempt.retryAt = Infinity
+ throw new Error(result.detail ?? result.error ?? 'Could not stop this Swarm worker.')
+ }
+ attempt.closed = true
+ }
+ if (this.stopped) return
+ await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, {
+ operationId: `release-${agent.releaseId ?? agent.id}`, asAgentId: agent.id, command: { type: 'agent.remove', agentId: agent.id, releaseId: agent.releaseId },
+ })
+ attempt.retryAt = Infinity
+ } catch (error) {
+ attempt.failures++
+ // Five attempts total; permanent ownership/identity refusals never acquire another lease for this runtime.
+ if (attempt.retryAt !== Infinity) attempt.retryAt = attempt.failures >= 5 ? Infinity
+ : this.now() + [5_000, 15_000, 60_000, 120_000][attempt.failures - 1]!
+ this.log(error instanceof Error ? error.message : String(error))
+ } finally { this.releases.delete(key) }
+ }
+
/** Retire local intent only after an authoritative terminal delivery state.
* This runs independently so a slow receipt lookup cannot stall live leases. */
reconcileReceipts(): Promise<void> {
@@ -274,11 +359,18 @@ export class SuperTabHost {
this.nextConfigurationsAt = this.now() + 5_000
})
}
+ const stopKeys = new Set(data.filter(item => object(item).stopRequested === true).map(item => { const row = object(item); return `${row.tabId}:${object(row.agent).id}` }))
+ for (const key of this.releaseAttempts.keys()) if (!stopKeys.has(key)) this.releaseAttempts.delete(key)
const seen = new Set<string>()
for (const item of data) {
const row = object(item), agent = object(row.agent)
if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continue
const target = row as unknown as HostAgent
+ if (row.stopRequested === true) {
+ // Native close may wait on disk or the engine; it must not delay other workers' input leases.
+ void this.releaseWorker(target)
+ continue
+ }
// Never adopt another live session as a replacement for the recorded harness.
if (!this.core.agents.byAgent(target.agent.harnessId) || !this.core.agents.terminalAvailable(target.agent.harnessId)) continue
const path = `/api/super-tabs/${target.tabId}/agents/${target.agent.id}/deliveries`
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index bb8e9236f..3fde72c38 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -60,6 +60,14 @@ describe('contributed machine executor', () => {
expect(f.open).toHaveBeenCalledOnce()
})
+ it('binds stopped native proof to the current slot reservation generation', async () => {
+ const f = fixture()
+ Object.assign(f.pool, { reservations: [{ harnessId: 'stopped', generation: 'new-contribution' }] })
+ await f.machine.tick()
+ const body = f.backend.mock.calls.find(c => c[1] === 'POST')![3]
+ expect(body).toMatchObject({ stoppedReservations: [{ harnessId: 'stopped', generation: 'new-contribution' }] })
+ })
+
it('does not connect to a daemon without an explicit contribution', async () => {
const f = fixture()
f.backend.mockResolvedValue([{ tabId: 'tab', agent: { id: 'existing-agent' } }])
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index d0eedcece..6abeea4b0 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -65,7 +65,7 @@ export class ContributedMachines {
for (const id of ids) if (await this.core.agents.stopped?.(id)) stopped.push(id)
const running = ids.filter(id => !!this.core.agents.byAgent(id) && !stopped.includes(id))
const pending = list(row.starts)
- const signature = JSON.stringify([pool.generation, [...running].sort(), [...stopped].sort(), row.paused === true || pool.paused === true,
+ const signature = JSON.stringify([row.reservations, pool.generation, [...running].sort(), [...stopped].sort(), row.paused === true || pool.paused === true,
pending.map(start => start.id).sort()])
const last = this.published.get(String(row.tabId))
if (!last || last.signature !== signature || began - last.at >= MACHINE_HEARTBEAT_MS) {
@@ -86,7 +86,9 @@ export class ContributedMachines {
quotas: (Array.isArray(pool.engines) ? pool.engines : []).filter((e): e is string => typeof e === 'string').map(engine => {
const q = quotaOf(readings, engine, false)
return { engine, known: q.known, windows: q.windows }
- }), runningHarnessIds: running, stoppedHarnessIds: stopped }
+ }), runningHarnessIds: running, stoppedHarnessIds: stopped,
+ ...(Array.isArray(row.reservations) ? { stoppedReservations: list(row.reservations).filter(r => stopped.includes(String(r.harnessId))
+ && identifier(r.harnessId) && identifier(r.generation)).map(r => ({ harnessId: r.harnessId, generation: r.generation })) } : {}) }
try {
await this.deps.backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/machines/${this.machineId}`, observation)
this.published.set(String(row.tabId), { at: began, signature })
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 393fe98fa..a51e1d2b8 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -497,3 +497,15 @@ it('teaches agents to say when their work needs a person or is stuck', async ()
expect(help.help.commands.filter(c => c.type === 'work.status').map(c => c.status)).toEqual(['working', 'needs_human', 'blocked', 'done'])
expect(help.help.command).toContain('needs_human')
})
+
+it('documents finished worker decisions and explains an older backend without release support', async () => {
+ const t = setup()
+ const help = (await t.ask({ action: 'help' }, owner)).help as { commands: unknown[]; release: string }
+ expect(help.commands).toContainEqual({ type: 'agent.release', agentId: 'AGENT', decision: 'keep|stop' })
+ expect(help.release).toContain('prefer stop')
+ t.call.mockImplementation(async (...args: unknown[]) => args[0] === 'POST'
+ ? { status: 400, body: { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid request' } } } as never
+ : { status: 200, body: { success: true, data: { state: { agents: [t.agent] } } } })
+ const reply = await t.ask({ action: 'command', tabId: 'tab', agentId: t.agentId, operationId: 'release', command: { type: 'agent.release', agentId: 'worker', decision: 'stop' } }, owner)
+ expect(reply).toMatchObject({ detail: 'This backend does not support releasing workers yet. Update the backend and try again.' })
+})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 53d6559f2..c63f5aaeb 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -17,6 +17,7 @@ const HELP = {
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.',
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on.',
+ release: 'When a worker finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',
capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
@@ -30,6 +31,7 @@ const HELP = {
{ type: 'conversation.create', title: 'Outcome', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },
{ type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },
{ type: 'work.define', conversationId: 'GROUP', task: { goal: 'What to deliver', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },
+ { type: 'agent.release', agentId: 'AGENT', decision: 'keep|stop' },
{ type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },
{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },
// Both reach the Lead and alert the Harness Pro on the machine running the agent until the status moves on.
@@ -240,6 +242,9 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
{ operationId: payload.operationId, command, asAgentId: agentId })
let value: unknown
try { value = await send(command) } catch (error) {
+ if (command.type === 'agent.release' && error instanceof SuperTabHostError && error.status === 400 && ['VALIDATION_ERROR', 'INVALID_REQUEST'].includes(error.code)) {
+ return { error: 'RELEASE_UNSUPPORTED', detail: 'This backend does not support releasing workers yet. Update the backend and try again.' }
+ }
if (!['conversation.create', 'work.define'].includes(String(command.type)) || !command.task || !(error instanceof SuperTabHostError)) throw error
const oldSchema = error.status === 400 && error.code === 'VALIDATION_ERROR'
&& /^(?:command: )?Unrecognized (?:key: "task"|key\(s\) in object: 'task')$/.test(error.message)
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 749744a6b..f0f5e45ca 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -9,7 +9,7 @@ import type { RegisteredSession } from '../lib/registry.js'
import type { AgentFrame } from '../lib/agentFrame.js'
import { buildEngineCommandArgv } from '../lib/engineLaunch.js'
const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
-function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string; guest?: boolean } = {}) {
+function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }
let nativeState = 'missing', lostJoin = false
@@ -25,7 +25,7 @@ function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?:
return { ok: true, value: { result: cmd.type === 'agent.start' ? { startId: 'start' } : { agentId: 'worker' } } }
})
const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}, _ms?: number): Promise<Record<string, unknown>> => {
- if (type === 'agent_create_status') return { creationId: start.creationId, state: nativeState, ...(nativeState === 'created' ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } } : {}) }
+ if (type === 'agent_create_status') return { creationId: start.creationId, state: nativeState, ...(nativeState === 'created' ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high', ...options.identity } } : {}) }
if (type === 'agents_list' && options.frame) return { agents: [{ id: 'native', engine: 'claude', selectedModel: options.frame }] }
if (type === 'engines_probe') return { engines: [{ engine: (payload.engines as string[])[0], installed: true }] }
if (type === 'usage_read') return { providers: [] }
@@ -39,7 +39,7 @@ function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?:
if (type === 'agent_create') {
if (options.refuseModel && payload.model !== undefined) return { error: options.refuseModel, detail: 'This daemon cannot launch with a model.' }
if (options.refuse) return { error: options.refuse, detail: 'This agent does not support that permission mode.' }
- nativeState = 'created'; return { creationId: start.creationId, state: 'created', agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } }
+ nativeState = 'created'; return { creationId: start.creationId, state: 'created', agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high', ...options.identity } }
}
if (type === 'agent_create_cancel') {
nativeState = 'cancelled'
@@ -714,3 +714,26 @@ describe('a routed Claude start launches with the model instead of switching it
})
})
})
+
+
+it('records the original launch identity and retries without it only for an older backend', async () => {
+ const identity = { sessionId: 'original-session', createdAt: '2026-10-22T00:00:00.000Z' }
+ const f = fixture({ identity })
+ const input = { action: 'start', tabId: 'tab', operationId: 'identity-start', request: f.start.request }
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ const joined = f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).find(c => c?.type === 'agent.started')!
+ expect(joined).toMatchObject({ startedSession: identity })
+ const old = fixture({ identity })
+ const scoped = async (payload: Record<string, unknown>) => {
+ const command = payload.command as Record<string, unknown> | undefined
+ return command?.startedSession ? { error: 'VALIDATION_ERROR' } : old.scoped(payload)
+ }
+ expect(await startAgent({ ...input, request: old.start.request }, scoped, where, old.open)).toMatchObject({ ok: true })
+ expect(old.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).find(c => c?.type === 'agent.started')).not.toHaveProperty('startedSession')
+})
+
+it('waits for the initial engine binding before recording a timed launch identity', async () => {
+ const f = fixture({ identity: { sessionId: '', createdAt: '2026-10-22T00:00:00.000Z' } })
+ expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'binding-start', request: f.start.request }, f.scoped, where, f.open)).toMatchObject({ error: 'START_PENDING' })
+ expect(f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).some(c => c?.type === 'agent.started')).toBe(false)
+})
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index bc5c2ac92..1d731a9cf 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -208,8 +208,21 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
const matched = profile && profile.sessionId === nativeId && profile.engine === frame.engine ? profile : null
const configuration = { engine: text(frame.engine) ?? String(request.engine), model: matched?.model ?? null, effort: matched?.effort ?? null,
contextWindow: number(frame.contextWindow), engineVersion: text(frame.engineVersion) }
- const joined = start.harnessId ? { result: {} } : requireSuccess(await scoped({ action: 'command', operationId: `joined-${startId}`,
- command: { type: 'agent.started', startId, harnessId: nativeId, configuration } }))
+ const startedSession = typeof frame.sessionId === 'string' && frame.sessionId && typeof frame.createdAt === 'string' && Number.isFinite(Date.parse(frame.createdAt))
+ ? { sessionId: frame.sessionId, createdAt: frame.createdAt } : undefined
+ // New native frames have their creation time before the engine binds. Wait for its original session identity.
+ if (typeof frame.createdAt === 'string' && !startedSession) return { error: 'START_PENDING', startId, creationId,
+ detail: 'Waiting for the launched engine to record its session identity. Resume this same start request.' }
+ const join = { type: 'agent.started', startId, harnessId: nativeId, configuration }
+ let joined: Json = { result: {} }
+ if (!start.harnessId) {
+ let reply = await scoped({ action: 'command', operationId: `joined-${startId}`, command: { ...join, ...(startedSession ? { startedSession } : {}) } })
+ if (startedSession && ['VALIDATION_ERROR', 'INVALID_REQUEST'].includes(String(reply.error))) {
+ // Older backends retain the launch, but cannot attest its native identity for automatic stopping.
+ reply = await scoped({ action: 'command', operationId: `joined-legacy-${startId}`, command: join })
+ }
+ joined = requireSuccess(reply)
+ }
await target.request('super_tabs', { action: 'wake' }).catch(() => {})
await target.request('harness_share_rosters', {}).catch(() => {})
// A launched agent already runs the routed model. Any other (Codex, a grid model, a machine that does not list the
diff --git a/desktop/lib/super_tabs/launch_prompt.dart b/desktop/lib/super_tabs/launch_prompt.dart
index 8adfbd466..6959e5031 100644
--- a/desktop/lib/super_tabs/launch_prompt.dart
+++ b/desktop/lib/super_tabs/launch_prompt.dart
@@ -7,15 +7,16 @@ String superTabLaunchPrompt({
required bool lead,
}) =>
'Harness Swarm agent. '
- '${lead ? 'You are the project lead. Discuss first; build when authorized. ' : ''}'
- 'Use `harness super-tab --tab $tabId` with the subcommands below. '
+ '${lead ? 'You lead the project. Discuss first; build when authorized. ' : ''}'
+ 'Use `harness super-tab --tab $tabId` subcommands. '
'First: `status`. Retry AGENT_UNAVAILABLE briefly; do not work or post before registration. '
- 'Read `messages $conversationId` for the full human request; if empty, ask what they want to work on. '
- 'Reply there using `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
- 'Use --reply-to for existing messages; answer each message once, do not post again. Retry a lost reply with the exact same operation ID and text. '
- 'Terminal output is not shared chat. If sandbox restrictions block this command, request permission. Use `help` for syntax. '
- '${lead ? 'Before starting or assigning work, use `route GROUP JSON` with difficulty, risk and size (small, medium or large); use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'
- '${lead ? 'Coordinate: put multi-part or 15+ minute work in groups for Swarm agents. Do only answers, lookups and small fixes yourself; your subagents only read and look up. ' : ''}'
+ 'Read `messages $conversationId` for the full request; if empty, ask what to work on. '
+ 'Reply there: `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
+ 'Use --reply-to for existing messages; answer each message once, do not post again. Retry lost replies with the same operation ID and text. '
+ 'Terminal output is not shared chat. If the sandbox blocks this command, request permission. Use `help` for syntax. '
+ '${lead ? 'Before work or assignment, use `route GROUP JSON` with difficulty, risk and size (small, medium or large); use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'
+ '${lead ? 'Put multi-part or 15+ minute work in Swarm agent groups. Do only answers, lookups and small fixes yourself; your subagents only read and look up. ' : ''}'
'Reuse agents and groups. Each task needs goal, changes, constraints, owned paths, checks. '
+ "${lead ? 'When a worker finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. ' : ''}"
'Write like a helpful colleague: answer first, in their language, under about 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. '
- '${lead ? 'Keep the Lead chat informed: plan, progress, blockers, next steps. Consolidate workgroup reports at the project cadence. Answer questions, serious blockers and completion immediately. On scheduled requests read new reports; use project.report for one update or text:null if nothing new. No per-turn summarizer. Keep workgroups and sessions scoped to this project.' : ''}';
+ '${lead ? 'Update Lead chat: plan, progress, blockers, next steps. At the project cadence, read new reports and consolidate them. No per-turn summarizer. Answer questions, serious blockers and completion immediately. On scheduled requests use project.report for updates or text:null when nothing changed. Scope workgroups and sessions to this project.' : ''}';
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index c7fa59aed..957465a60 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -853,6 +853,9 @@ void main() {
expect(prompt, contains('routeDecisionId'));
expect(prompt, contains('overrideReason'));
expect(prompt, contains('NO_CANDIDATE'));
+ expect(prompt, contains('reuse, keep or stop'));
+ expect(prompt, contains('prefer stop'));
+ expect(prompt.length, lessThanOrEqualTo(2000));
});
test('a new Lead starts Claude Code or Codex; other agents stay open to the rest', () async {
diff --git a/desktop/test/super_tab_startup_recovery_test.dart b/desktop/test/super_tab_startup_recovery_test.dart
index 9ad79e9fb..99ffdebde 100644
--- a/desktop/test/super_tab_startup_recovery_test.dart
+++ b/desktop/test/super_tab_startup_recovery_test.dart
@@ -46,10 +46,28 @@ void main() {
conversationId: 'b' * 160,
lead: lead,
);
- expect(prompt.length, lessThanOrEqualTo(kFirstTaskMaxLength));
+ expect(
+ prompt.length,
+ lessThanOrEqualTo(kFirstTaskMaxLength),
+ reason: '${lead ? 'Lead' : 'Worker'} bootstrap must fit native creation',
+ );
}
});
+ test('lead bootstrap retains report reading and worker release guidance', () {
+ final prompt = superTabLaunchPrompt(
+ tabId: 'a' * 160,
+ conversationId: 'b' * 160,
+ lead: true,
+ );
+ expect(prompt, contains('read new reports'));
+ expect(prompt, contains('No per-turn summarizer'));
+ expect(prompt, contains('When a worker finishes, decide reuse, keep or stop'));
+ expect(prompt, contains('prefer stop unless more work is coming soon'));
+ expect(prompt, contains('On scheduled requests use project.report'));
+ expect(prompt, contains('text:null when nothing changed'));
+ });
+
for (final engine in ['codex', 'claude']) {
for (final newProject in [false, true]) {
for (final task in ['', 'hi', '文🙂\n' * 500]) {
diff --git a/docs/plans/2026-10-22-worker-release.md b/docs/plans/2026-10-22-worker-release.md
new file mode 100644
index 000000000..91175674c
--- /dev/null
+++ b/docs/plans/2026-10-22-worker-release.md
@@ -0,0 +1,144 @@
+# Finished-worker decisions implementation plan
+
+> **For agentic workers:** Use superpowers:executing-plans to implement this plan task by task.
+
+**Goal:** Require the Lead to reuse, keep or stop each finished worker; stopping closes its native session and returns its machine slot.
+
+**Architecture:** Persist the decision on the Swarm agent, independently of the group's replaceable assignment. The backend gates new routing, starting and assignment. The execution host consumes stop requests through the existing identity-bound core lifecycle, including its service-process bridge, and confirms removal through the command transaction, which also cancels deliveries. A global SuperTabRun reservation prevents another public Swarm from assigning the same native session during close. A pending stop cannot be reassigned. An owner or contributor can withdraw a stuck stop with normal Remove; this clears its work reservation and retires that native ID only in this Swarm. Native capacity remains reserved until host stop proof. A separate two-minute close lease protects other Swarms from an already-running close; completion or expiry permits reuse elsewhere. Native core closure accepts only the original recorded Swarm launch and refuses personally resumed sessions throughout saving/stopping.
+
+**Tech stack:** Existing TypeScript, Zod, Prisma/MongoDB, Vitest and Flutter. No new dependencies.
+
+**Spec:** The Lead's brief in this group's assignment: finished work requires reuse, keep or stop; only the project's Lead or the tab owner/contributor decides; active work is never stopped; host-confirmed removal frees slots. Deliver a draft PR only.
+
+## Global constraints
+
+- Work from current origin/main; keep changes within worker release ownership and its necessary model/tests.
+- Product = Swarm; coordinating role = Lead; visible copy in plain English.
+- CLI tests use Node 24 and disposable data; never touch port 18473, the real tmux or personal agent homes.
+- Keep older clients compatible through optional fields; explain unsupported commands from older backends plainly.
+- No new dependencies. Do not mark the PR ready, merge or release.
+- Preserve the 2,000 UTF-16-unit launch prompt limit and adjacent groups' changes.
+
+## Review focus
+
+- Stop requests remain irreversible until removal; reuse cannot race host closure.
+- Decisions survive replacing a brief or archiving the finished group.
+- Only the execution host can acknowledge physical stopping. A person may administratively withdraw a stuck stop; an agent cannot impersonate that withdrawal.
+- Repeated host polls and lost acknowledgements never close a replacement session or close the same session twice.
+- Removing the agent cancels outstanding deliveries. Capacity is released only by host stop evidence; person withdrawal retains its native reservation.
+
+### Task 1: Backend policy and state
+
+**Files:** backend/src/superTabs/model.ts, commands.ts, machines.ts; commands.test.ts, machines.test.ts.
+
+**Interfaces:** Optional agent decision tied to the finished assignment; helpers compute pending decisions by project and reject new work; agent.release accepts keep/stop. A host acknowledgement uses the existing agent.remove command and exact release token. The owner or contributor can use ordinary agent.remove to withdraw a stuck stop without falsely confirming physical closure.
+
+- [x] Add tests for Lead/owner/contributor permissions, active-work refusal, pending guards, keep/reuse/stop, brief replacement and host acknowledgement.
+- [x] Run affected tests and observe failures caused by the missing behavior.
+- [x] Implement persistence on completion, project guards and irreversible stop requests; expose pending decisions in status.
+- [x] Verify affected backend tests pass.
+
+### Task 2: Host lifecycle and integration
+
+**Files:** backend/src/superTabs/store.ts, backend/integration/superTabs.test.ts; cli/src/superTabs/host.ts, host.spec.ts; cli/src/core/api.ts, experimentQueries.ts and their tests; cli/src/services/processCoreApi.ts and its tests. Core API additions are kept in a separate commit.
+
+**Interfaces:** Host roster exposes stop requests only without active work. The CLI passes the creation receipt, native session ID and creation time recorded by agent.started to core.agents.closeSwarm. Core checks agent ownership, the original creation receipt and conversation identity, and refuses personal resume before/after asynchronous lookup and throughout the lifecycle. An authoritatively absent native session counts as stopped even without a stopped-history record. Only a positive close result permits host acknowledgement as that agent. The close request carries the exact native session identity and is exposed only to the Swarm service process. Backend host removal requires the current release token, shares cancellation semantics with ordinary withdrawal, and stores a durable stopped-harness receipt independent of replaceable observations. Stop intent refuses any other Swarm membership, including an idle Lead. Session-scope writes serialize contribution and stop transactions. Optional session-scope stopReleaseId and close-lease fields plus default-empty releasedTabIds preserve compatibility with existing Mongo records. A re-contribution reserves a new generation: unversioned late observations cannot prove that its new runtime stopped, even after membership removal. Host polling includes withdrawn reservations; matching generation-stamped stop observations retire them and persist durable physical-stop proof.
+
+- [x] Add failing tests for host stop pickup, safe retry, refusal/unavailable lifecycle, foreign sessions and slot release through real Mongo transactions.
+- [x] Implement stop pickup outside native delivery; withhold new input for stop-requested agents.
+- [x] Verify host tests and backend integration pass, including cancelled deliveries and slot counts.
+
+### Task 3: Guidance, validation and delivery
+
+**Files:** cli/src/superTabs/service.ts (release HELP and compatibility only), desktop/lib/super_tabs/launch_prompt.dart, affected tests.
+
+**Interfaces:** HELP lists keep/stop and recommends stopping unless more work is imminent; launch/delivery guidance tells the Lead to decide after completion.
+
+- [x] Add failing tests for release HELP, older-backend error and launch prompt wording/length.
+- [x] Implement guidance and plain unsupported-command error.
+- [x] Run CLI npm run test:super-tabs (100% coverage), npm run typecheck and affected host/service tests; backend npx tsc --noEmit, vitest run src/superTabs and npm run test:super-tabs; desktop flutter analyze and affected launch tests. Run required full component suites once with bounded workers, recording unavailable or baseline failures explicitly.
+- [x] Review the final diff independently; fix material findings and verify affected checks.
+- [x] Fetch/rebase current main, inspect new interactions and repeat only invalidated checks. Commit/push the reviewed changes and open a draft PR with exact evidence and timing. Report its URL and head revision.
+
+
+## Earlier review validation (superseded by final review below)
+
+Earlier validated source: `5f5595e53`, rebased cleanly on current main `f1a67cd22`. The final evidence-only commit does not change component inputs. Node 24.3.0, locked npm dependencies, disposable MongoDB 7.0.24 replica set; Flutter 3.47.5 / Dart 3.13.4 on macOS arm64. Tested component trees: CLI `ef737f3b94e7ff1f67b55f2f2920267f1e0c9d3e`, backend `0ab259684dc680db212ece9e595d4a3d0bffd817`, Desktop `b50fcb14523b4af8c98a7f3c7fe8907536ce737e`.
+
+Every requested review correction had a failing regression before its implementation:
+
+1. Maximum-length 160-character IDs made the Lead prompt 2,054 units and exposed dropped reporting instructions. It is now 1,991, restores “read new reports” and “No per-turn summarizer”, and preserves the worker-release instruction.
+2. An offline/old host or deleted native session could leave a permanent stop reservation. Ordinary person Remove now withdraws the stuck contribution, releases its global reservation, and retires its old native ID against future Swarm work. An agent Lead cannot force-withdraw it. Core treats an absent native row as already gone.
+3. A worker that also leads another Swarm could be closed. Stop now refuses any other membership; serialized session-scope writes fence concurrent recontribution.
+4. A generic core close could stop a personal or replacement session. The Swarm-specific bridge verifies the recorded original creation/session identity, preserves personally contributed and resumed sessions, and carries its original-launch guard through save/stop boundaries and job deduplication. Old backends accept a fallback join without identity; those live sessions require person withdrawal.
+5. Route selection of the awaiting worker itself now gets the direct-reuse exemption.
+
+Follow-up independent review found personal-resume and late stopped-observation gaps. Regressions reproduced both; durable recontribution history also covers repeated removal/re-addition. Final read-only review at `5f5595e53` found no remaining material findings.
+
+| Scope | Command | Observed result |
+| --- | --- | --- |
+| CLI routing coverage | `npm run test:super-tabs` | 111 pass; all four measures 100% |
+| CLI types | `npm run typecheck` | Pass after rebase |
+| CLI affected Swarm/core/process/native close tests | `vitest run src/core/api.spec.ts src/lib/closeAgentService.spec.ts src/superTabs src/services/processCoreApi.spec.ts src/core/experimentQueries.spec.ts` | 490 pass |
+| CLI core/services | `npm run test:core -- --maxWorkers=3 --testTimeout=15000` | 2,945 pass; changed core/service files 100% in all measures. Gate nonzero only on unchanged osDevice.ts:181 (99.16% lines, 99.31% branches, 97.22% functions, 99.37% statements) |
+| CLI native E2E | `E2E_BUNDLE=1 vitest run --config vitest.e2e.config.ts e2e/superTabs.e2e.ts` | Pass on rebased source in 74.48s (49.91s test); real private daemon/service process/tmux with fake Claude/Codex; original Swarm launch removed, personal session and Lead preserved, deleted session without stopped record removed |
+| Backend types | `npx tsc --noEmit` | Pass after rebase |
+| Backend Swarm unit tests | `NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=<fixture> vitest run src/superTabs` | 114 pass before rebase; complete suite below covers integrated source |
+| Backend integration | `npm run test:super-tabs` | 64 pass on final rebased source |
+| Backend complete unit suite | `npm test -- --maxWorkers=3` | 1,697 pass, 11 skipped on final rebased source |
+| Desktop bootstrap/launch | `flutter test --no-pub --concurrency=2 --timeout=60s test/super_tab_startup_recovery_test.dart test/super_tab_launch_test.dart` | 49 pass, including maximum IDs and reporting wording |
+| Desktop affected analyzer | `flutter analyze --no-pub lib/super_tabs/launch_prompt.dart test/super_tab_startup_recovery_test.dart` | No issues |
+| Desktop complete analyzer | `flutter analyze` | Prior receipt: 44 diagnostics in unchanged files (5 unused-import warnings, 39 infos), no errors; nonzero |
+
+The first review-fix core attempt collided with coverage cleanup from a parallel coverage run; it produced no valid receipt. A sandboxed attempt could not open disposable loopback listeners. An unsandboxed attempt hit an unchanged held-launch test's 5-second timeout; its isolated 25 tests passed. The recorded retry allows 15 seconds for that fake-timer loop and preserves all coverage thresholds.
+
+The original full CLI `npm test -- --maxWorkers=4` run was stopped at its ten-minute budget. It encountered failures in unchanged `sessionRepair.spec.ts`, `stoppedAgents.spec.ts`, `storePool.spec.ts`, `exactTranscript.spec.ts`, `nativeDescriptors.golden.spec.ts`, `messages/rpc.spec.ts` and `publishedGridConfig.spec.ts`. New regressions were added during that broad run, so it is incomplete and is not a final-source pass. Stable affected tests, core results, types, routing coverage and native E2E are separate receipts. No required gate was lowered or silently skipped.
+
+Timing (UTC): initial explicit Go 03:48; draft publication 04:14, first handover 04:17 (29 minutes total, including overlapping implementation/review/validation). Review-fix implementation, follow-up review and validation continued in the same request; final publication timing is recorded in the shared handover. No merge or release occurred. PR #1527 remains draft.
+
+
+## Second review corrections and final validation
+
+Final source is rebased on `9313c4429`, preserving main's five-part delegation and change-driven Machines publisher. The merged maximum-ID Lead prompt is 1,994 units and its 49 bootstrap/launch tests pass. A conflict-resolution syntax error was caught and corrected before final validation.
+
+All three requested regressions failed before implementation:
+
+- A person withdrawing a stuck stop no longer creates physical-stop receipts or frees capacity. Every new contribution records a native slot reservation independently of membership. Person removal retains it; the host continues polling withdrawn IDs, including contributed sessions without start receipts. Re-contribution invalidates old receipts and uses a new generation. Matching host stop proof persists durably, so older running observations cannot resurrect a confirmed released slot, even while old membership remains. Older unversioned hosts may prove a first contribution stopped; renewed reservations conservatively need generation-stamped host proof or the exact host removal acknowledgement.
+- Administrative retirement records only the originating tab. Other Swarms can use the contributor's session after any in-flight close finishes or its bounded lease expires. The Lead explicitly approved a two-minute native-close lease. Its completion and expiration paths have transactional regressions. Core enforces the deadline before/after asynchronous receipt lookup and through save/stop callbacks. The host derives its local deadline from request-start time plus the returned duration, so clock skew and network delay cannot extend server authority; a server-clock-skew regression failed first.
+- Making a project private skips rebinding stopping agents while preserving historical audience checks and private-scope updates.
+
+| Scope | Final observed result |
+| --- | --- |
+| CLI `npm run test:super-tabs` | 111 pass; all four coverage measures 100% |
+| CLI `npm run typecheck` | Pass |
+| CLI affected tests (same command above) | 517 pass |
+| CLI `npm run test:core -- --maxWorkers=3 --testTimeout=15000` | 2,946 pass; changed core/service files 100%; unchanged osDevice.ts:181 keeps gate nonzero |
+| CLI isolated native E2E (same command above) | 1 pass, 57.27s; real private daemon/service process/backend/tmux, leased original-launch stop, personal session/Lead preserved |
+| Backend `npx tsc --noEmit` | Pass |
+| Backend `npm test -- --maxWorkers=3` | 1,702 pass, 11 skipped |
+| Backend `npm run test:super-tabs` | 68 pass |
+| Desktop bootstrap/launch (same two files above) | 49 pass |
+| Desktop affected analyzer | No issues |
+
+The earlier full Desktop analyzer diagnostics and incomplete broad CLI baseline remain explicit validation gaps. Component CI is intentionally deferred while this remains a draft. No coverage threshold was lowered. Final source revision, exact component trees, review result and publication time are recorded at delivery.
+
+Final independent read-only review: no remaining material findings.
+
+Final validated source: `d8ef49df645f131bcfc200f3b6e6eea617e3d015`; CLI tree `e0b9dd89a159cd5732cee605a2025acfccb71148`, backend tree `a5318553728bbc76da167b173b2c93f7821a9022`, Desktop tree `eae4b0e36e8cdcb904215870ec4d24a526fbccec`. The evidence-only commit changes none of those inputs.
+
+
+## Third review: stop retry bounds
+
+The host used to acquire a fresh close lease every second for a stop that could never close. Seven new regressions failed before the fix. The host now checks recorded original-launch identity, current native ownership/resume state and the native creation receipt before any lease write. A definitive ownership/identity refusal disables retries for that exact stop/runtime. Unknown/transient failures back off for 5, 15, 60 and 120 seconds, at most five attempts. The memo key includes native process identity; a changed runtime or disappeared session gets a fresh check. Removed stop requests discard the memo.
+
+An absent process snapshot is not stop proof: the authoritative core confirms absence without a lease. A failed removal acknowledgement similarly rechecks core absence before retrying, without acquiring another lease. This preserves deleted-session cleanup and refuses a personal resume hidden by a stale process snapshot. Tests cover repeated personal/missing-record/replacement sessions, wrong creation receipts, permanent close refusals, unknown receipt reads, timed retry bounds, changed runtimes, absence recovery and lost acknowledgements.
+
+Rebased cleanly on `9142773b0`; main's full-permission starts changed an old E2E refusal expectation. The fixture now uses an invalid Claude codexHome combination to preserve the same pre-dispatch cancellation/replay assertions. No application permission logic changed in this review fix.
+
+Final checks for this review: CLI `vitest run src/superTabs` 383 pass; `npm run test:super-tabs` 111 pass at 100% in all four coverage measures; CLI typecheck pass. After integrating main, backend `vitest run src/superTabs` 125 pass, backend integration 68 pass and backend types pass; Desktop bootstrap/launch/Machines 79 pass. Native E2E and full Desktop analyzer results are recorded below once complete. Prior core coverage/full backend evidence is reused only for its unchanged scope; the unchanged coverage/broad CLI baseline gaps remain explicit.
+
+Independent read-only review of `5a4d9caeb`: no material findings. Two additional regressions for transient receipt reads and lost-ack authoritative absence also pass in the final 383-test run.
+
+Third-review final native E2E: 1 pass in58.45s (42.02s test), real disposable daemon/service process/backend/tmux. Full Desktop analyzer refreshed:44 diagnostics (5 warnings,39infos), no errors; same unchanged baseline. No core/service implementation changed in this review; its earlier2,946-test coverage receipt remains scoped to unchanged core/services. No coverage threshold was lowered.
+
+Third-review validated source: `c04a8a880b6308c33849e32277e9b72037c96ed2`; CLI tree `65954bc5471951345e651a30d47980f3549be866`, backend tree `472bd37bd0cbd699a23fff815fc436d568c40f99`, Desktop tree `73fc6a9b30e128234fea74789797eec7efc2aee1`. Final evidence-only commit changes none of these inputs.