The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Lead always alive: CLI keep-alive, close guards, Swarm link after restart (#1635)
0xken1566d4a00926f5
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.tsindex 9ac1031ac..28665a90a 100644--- a/cli/src/core/agents/close.ts+++ b/cli/src/core/agents/close.ts@@ -35,6 +35,8 @@ export interface ClosingDeps {engineReady: (engine: string, ms: number) => Promise<void>/** The agents stopped and kept: a close of one already closed is answered closed. */stoppedAgents?: Pick<StoppedAgentStore, 'get' | 'resumeReservedAt'>+ /** Whether the agent may be the Lead of an active Swarm project: never closed (superTabs/retention.ts `mayBeLead`). */+ leadProtected?: (agentId: string) => boolean}/** How long a close waits for an engine worker that restarted under its read, before reading once more. */@@ -42,7 +44,7 @@ export const CLOSE_READ_RECONNECT_MS = 10_000export function createAgentClosing({readScreen, registry, cleanupTabs, watcher, captureTerminal, sessionTurnState, openQuestions, terminals, sessionCheckpoints,- stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true,+ stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true, leadProtected,}: ClosingDeps) {const ready = (s: RegisteredSession): boolean =>!s.identityHold && !s.admissionHold && !s.interpretationHold && nativeRecoveryReady(s)@@ -96,6 +98,7 @@ export function createAgentClosing({},stop: stopAgent,changed: announceSession,+ leadProtected,// Not live, not being resumed, and kept as stopped with the conversation the close names: it was closed. A record// that cannot be read says nothing, and the close is answered as changed, as before.closedAlready: request => {diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.tsindex b94d17743..7eb4ac8d1 100644--- a/cli/src/core/agents/lifecycle.spec.ts+++ b/cli/src/core/agents/lifecycle.spec.ts@@ -3,7 +3,7 @@ import type { PurgeDeps } from '../../lib/purgeAgentService.js'import type { RegisteredSession } from '../../lib/registry.js'import { createResumeAgentService } from '../../lib/resumeAgentService.js'import { AgentStopError, createStopAgentService } from '../../lib/stopAgentService.js'-import { createAgentLifecycle, createPurgeRequest, createStopRequest, type LifecycleDeps } from './lifecycle.js'+import { createAgentLifecycle, createPurgeRequest, createStopRequest, LeadProtectedError, type LifecycleDeps } from './lifecycle.js'import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'@@ -99,6 +99,23 @@ describe('stopping, purging and resuming an agent', () => {await expect(setup().lifecycle.stopAgent('a1')).resolves.toBeUndefined()})+ // The owner, 2026-10-23: the Lead of an active project is never stopped, in any case. Every stop goes through here (a+ // window's close and Stop Harness, `harness close`, a purge, the cleanup), so one guard refuses them all.+ it('refuses to stop a Swarm Lead, by agent or session id, and stops nothing', async () => {+ const stopped = vi.fn(), leadProtected = vi.fn((agentId: string) => agentId === 'a1')+ const { lifecycle } = setup({ stopped, leadProtected })+ const stop = vi.mocked(createStopAgentService).mock.results[0].value as ReturnType<typeof vi.fn>+ for (const target of ['a1', 's1']) {+ const refusal = await lifecycle.stopAgent(target).catch((error: unknown) => error)+ expect(refusal).toBeInstanceOf(LeadProtectedError)+ expect(refusal).toMatchObject({ code: 'LEAD_PROTECTED', message: expect.stringContaining('Delete its project first') })+ }+ expect(stop).not.toHaveBeenCalled()+ expect(stopped).not.toHaveBeenCalled()+ await lifecycle.stopAgent('gone')+ expect(stop).toHaveBeenCalledWith('gone', undefined)+ })+describe('purge', () => {it('sees live and stopped agents, stops through the stop service, and checkpoints where stop does', () => {const { deps, lifecycle, purge } = setup()@@ -228,6 +245,11 @@ describe('agent_delete', () => {await expect(request(async () => { throw new Error('tmux gone') })({ agentId: 'a1' })).rejects.toThrow('tmux gone')})+ it('says why a Swarm Lead is not stopped', async () => {+ const refused = await request(async () => { throw new LeadProtectedError() })({ agentId: 'a1' })+ expect(refused).toStrictEqual({ error: 'LEAD_PROTECTED', detail: new LeadProtectedError().message })+ })+it('returns an unavailable native identity as a retryable hold and permits the same Stop after recovery', async () => {const error = new IdentityReadUnavailable('the native record is incomplete')const stop = vi.fn().mockRejectedValueOnce(error).mockResolvedValueOnce(undefined)diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex 926e9dc3d..32b6b2289 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -5,6 +5,7 @@* Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).*/import type { clearDeleted as clearDeletedFn, markDeleted as markDeletedFn } from '../../lib/deletedSessions.js'+import { LEAD_PROTECTED_DETAIL } from '../../lib/closeAgentService.js'import { PurgeAgentService } from '../../lib/purgeAgentService.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import { createResumeAgentService, type ResumeAgentServiceDeps } from '../../lib/resumeAgentService.js'@@ -60,12 +61,21 @@ export interface LifecycleDeps {stopped?: (agentId: string) => void/** An agent a move a dead daemon left may still run beside (main.ts `moveHeld`): no engine of it starts this start. */moveHeld?: (agentId: string) => boolean+ /** Whether the agent is the Lead of an active Swarm project here (superTabs/retention.ts `retainedLeads`). */+ leadProtected?: (agentId: string) => boolean+}++/** The owner, 2026-10-23: the Lead of an active project is never stopped, in any case; deleting its project closes it. */+export class LeadProtectedError extends Error {+ readonly code = 'LEAD_PROTECTED'+ constructor() { super(LEAD_PROTECTED_DETAIL) }}export function createAgentLifecycle({registry, stoppedAgents, restartJobs, createBackend, noBackendCode, backendFor, agentReconciler, forgetSession, markDeleted, clearDeleted, stopNative, settlePane, cancelExternal,sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,relaunchOverrides, prepareSessionResume, refreshGridWebSearch, adoptSwarmSkill, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer, moveHeld,+ leadProtected,}: LifecycleDeps) {/*** Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live@@ -84,6 +94,7 @@ export function createAgentLifecycle({*/const stopAgent: typeof stop = (target, options) => {const agentId = registry.resolve(target)?.agentId ?? target+ if (leadProtected?.(agentId)) return Promise.reject(new LeadProtectedError())return stop(target, options).then(() => { stopped?.(agentId) })}const purgeAgentService = new PurgeAgentService({@@ -147,7 +158,7 @@ export function createStopRequest({ byAgent, stop }: {try { await stop(target) }catch (error) {if (error instanceof IdentityReadUnavailable) return { error: error.code, detail: error.message, held: true, retryable: true }- if (!(error instanceof AgentStopError)) throw error+ if (!(error instanceof AgentStopError) && !(error instanceof LeadProtectedError)) throw errorreturn { error: error.code, detail: error.message }}return { deleted: true }diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex dbe22db12..e367c79d9 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -40,22 +40,83 @@ describe('the core API services stand on', () => {expect(await core.agents.closeSwarm!({ agentId: 'worker' })).toEqual({ closed: true })})- it('refuses a personal resume before or during the original creation lookup', async () => {+ // A machine restart stops Swarm sessions; reopened, each keeps its harness, conversation and registeredAt but is marked+ // resume-only. On 2026-10-23 such a worker could no longer be stopped by the Swarm ("not started by the Swarm").+ it('closes a Swarm session reopened on its own conversation, and refuses one whose conversation changed during the 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 session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const, resumeOnly: true as const }const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))- const creationStatus = vi.fn(async () => {- session.resumeOnly = true+ const creationStatus = vi.fn(async () => ({ 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)).toEqual({ closed: true })+ expect(closeAgent).toHaveBeenCalledOnce()+ closeAgent.mockClear()+ creationStatus.mockImplementationOnce(async () => {+ session.sessionId = 'personal-resume'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(await core.agents.closeSwarm!(request)).toEqual({ error: 'AGENT_CHANGED' })expect(closeAgent).not.toHaveBeenCalled()})+ // The Super Tab host keeps a Swarm Lead alive and closes the sessions its backend ends (owner, 2026-10-23). The core+ // decides what a service may do: reopen only a stopped Lead the host's retention names, close only a member it names.+ it('reopens only a stopped Swarm Lead, and says a live one is up', async () => {+ const deps = coreDeps(), resumeAgent = vi.fn(async () => ({ ok: true as const, session: row('stopped'), resumed: true }))+ const leads = vi.fn(() => new Set(['stopped', 'live']))+ const core = createCoreApi({ ...deps, resumeAgent, swarmMembers: { leads, harnesses: () => new Set() } })+ expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: true })+ expect(resumeAgent).toHaveBeenCalledWith('stopped')+ expect(await core.agents.keepLeadAlive!('live')).toEqual({ ok: true })+ leads.mockReturnValue(new Set(['live']))+ expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' })+ leads.mockReturnValue(new Set(['gone']))+ expect(await core.agents.keepLeadAlive!('gone')).toMatchObject({ ok: false, error: 'NOT_A_LEAD' })+ expect(resumeAgent).toHaveBeenCalledTimes(1)+ leads.mockReturnValue(new Set(['stopped']))+ resumeAgent.mockResolvedValueOnce({ ok: false, error: 'AGENT_BUSY', detail: 'busy' } as never)+ expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'AGENT_BUSY', detail: 'busy' })+ resumeAgent.mockResolvedValueOnce({ ok: false, error: 'RESUME_FAILED' } as never)+ expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'RESUME_FAILED' })+ expect(await createCoreApi(deps).agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'UNSUPPORTED' })+ })++ it('closes now only a Super Tab member the host retains, and treats an absent one as closed', async () => {+ const base = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))+ const deps = { ...base, registry: { ...base.registry, byAgent: (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined } as CoreApiDeps['registry'] }+ const harnesses = vi.fn(() => new Set(['live']))+ const core = createCoreApi({ ...deps, closeAgent, swarmMembers: { leads: () => new Set(), harnesses } })+ expect(await core.agents.closeMember!('live')).toEqual({ closed: true })+ expect(closeAgent).toHaveBeenCalledWith({ agentId: 'live', sessionId: 's-live', createdAt: new Date(1000).toISOString(), mode: 'now' })+ expect(await core.agents.closeMember!('absent')).toEqual({ closed: true })+ harnesses.mockReturnValue(new Set())+ expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })+ harnesses.mockImplementation(() => { throw new Error('Super Tab retention is unreadable.') })+ expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })+ expect(closeAgent).toHaveBeenCalledTimes(1)+ expect(await createCoreApi({ ...deps, closeAgent }).agents.closeMember!('live')).toEqual({ error: 'UNSUPPORTED' })+ expect(await createCoreApi({ ...deps, swarmMembers: { leads: () => new Set(), harnesses: () => new Set(['live']) } }).agents.closeMember!('live')).toEqual({ error: 'UNSUPPORTED' })+ })++ // The review of #1635: an agent removed before its host wrote a roster naming it is no member there; the exact receipt of+ // the Swarm's start proves it is the Swarm's own to close, and a receipt naming another harness proves nothing.+ it('closes a member the retention does not name only when its start receipt names it', async () => {+ const base = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))+ const creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'created' as const, agentId: 'live' }))+ const deps = { ...base, closeAgent, creationStatus, swarmMembers: { leads: () => new Set<string>(), harnesses: () => new Set<string>() },+ registry: { ...base.registry, byAgent: (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined } as CoreApiDeps['registry'] }+ const core = createCoreApi(deps)+ expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })+ expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ closed: true })+ expect(creationStatus).toHaveBeenCalledWith('super-start')+ creationStatus.mockResolvedValueOnce({ creationId: 'super-start', state: 'created', agentId: 'another' })+ expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })+ creationStatus.mockResolvedValueOnce(null as never)+ expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })+ expect(await createCoreApi({ ...deps, creationStatus: undefined }).agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })+ expect(closeAgent).toHaveBeenCalledTimes(1)+ })+it('refuses missing or expired close leases, including expiry during the creation lookup', async () => {let now = 1000const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 4075d8f29..53e54f555 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -207,6 +207,14 @@ export interface CoreApi {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>+ /** Reopen a Swarm Lead whose session is gone, on its own conversation, as a resume does: nothing is typed into it+ * (superTabs/host.ts keeps Leads alive). Only an agent stopped here that this machine's Super Tab host keeps as the+ * Lead of an active project (superTabs/retention.ts); a live one is answered ok. */+ keepLeadAlive?(agentId: string): Promise<{ ok: true } | { ok: false; error: string; detail?: string }>+ /** Close, now and keeping its conversation, a Super Tab member whose session the backend ends (its project deleted,+ * the agent removed). Only a harness this machine's Super Tab host retains as a member, or one whose exact native+ * creation receipt [creationId] (the Swarm's start) names it; a gone one is closed. */+ closeMember?(agentId: string, creationId?: string): 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@@ -1800,6 +1808,11 @@ export interface CoreApiDeps {closeAgent?: (request: AgentCloseRequest) => Promise<AgentCloseResult>/** When an agent's conversation last moved (lib/transcriptActivity.ts), for `lastActivity`. */activityAt?: (session: RegisteredSession) => Promise<number | null>+ /** A resume of a stopped agent (core/agents/lifecycle.ts `resumeAgent`), for `keepLeadAlive`. */+ resumeAgent?: (agentId: string) => Promise<{ ok: true } | { ok: false; error: string; detail?: string }>+ /** The Swarm Leads and members this machine's Super Tab host keeps (superTabs/retention.ts), for `keepLeadAlive` and+ * `closeMember`; absent, neither does anything. */+ swarmMembers?: { leads(): Set<string>; harnesses(): Set<string> }signedIn: CoreApi['account']['signedIn']environment: CoreApi['account']['environment']machines: CoreApi['account']['machines']@@ -1832,7 +1845,7 @@ export function createCoreApi({dataDir, registry, stoppedAgents, databaseHistory, syncSession, runtimeModels, viewerChanged,gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, tabKey, tabRelay, connectorVault, observer, privateGridName, machineName, backend, onNotice,runtimeProfile, setRuntime, fork, create, creationStatus, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText, activitySnapshot, activity, summaries,- closeAgent, activityAt,+ closeAgent, activityAt, resumeAgent, swarmMembers,signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, cloud, superTabs, superTabRequest, cloudRows, lastTurn, nativeTurns, turnCard, turnSummary,log = (line) => console.warn(line),}: CoreApiDeps): CoreApi {@@ -1877,17 +1890,42 @@ export function createCoreApi({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' }+ // A reopen (resume-only) of the same conversation is still the Swarm's session: the identity below proves it.+ if (session.startedBy !== 'agent' || !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+ if (!latest || latest.startedBy !== 'agent' || 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' }},+ keepLeadAlive: async agentId => {+ if (!resumeAgent || !swarmMembers) return { ok: false, error: 'UNSUPPORTED' }+ if (registry.byAgent(agentId)) return { ok: true }+ if (!swarmMembers.leads().has(agentId) || !stoppedAgents.ids().includes(agentId)) {+ return { ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' }+ }+ const reply = await resumeAgent(agentId)+ return reply.ok ? { ok: true } : { ok: false, error: reply.error, ...(reply.detail ? { detail: reply.detail } : {}) }+ },+ closeMember: async (agentId, creationId) => {+ if (!closeAgent || !swarmMembers) return { error: 'UNSUPPORTED' }+ const session = registry.byAgent(agentId)+ if (!session) return { closed: true }+ let member = false+ try { member = swarmMembers.harnesses().has(agentId) } catch { /* An unreadable retention names no member. */ }+ // An agent removed before its host wrote a roster naming it: the Swarm's own start receipt proves it (the review of #1635).+ if (!member && creationId) {+ const creation = await creationStatus?.(creationId)+ member = creation?.state === 'created' && creation.agentId === agentId+ }+ if (!member) return { error: 'NOT_A_MEMBER' }+ // The close itself refuses a session that changed during the receipt read.+ return closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'now' })+ },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.tsindex 0f193da7a..0811b2246 100644--- a/cli/src/core/experimentQueries.spec.ts+++ b/cli/src/core/experimentQueries.spec.ts@@ -269,3 +269,24 @@ it('exposes identity-bound close only to the Swarm service and validates its nat}expect(await answerExperimentQuery(fakeCore(), allowed, 'superTabs', 'close_swarm', payload)).toEqual({ error: 'UNSUPPORTED' })})++it('lets only the Swarm service reopen a Lead or close a member, by a valid agent id', async () => {+ const keepLeadAlive = vi.fn(async () => ({ ok: true as const })), closeMember = vi.fn(async () => ({ closed: true as const }))+ const core = fakeCore({ agents: { keepLeadAlive, closeMember } })+ const allowed = new Set(['superTabs', 'orchestrator'])+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'keep_lead_alive', { agentId: 'lead' })).toEqual({ ok: true })+ expect(keepLeadAlive).toHaveBeenCalledWith('lead')+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_member', { agentId: 'worker' })).toEqual({ closed: true })+ expect(closeMember).toHaveBeenCalledWith('worker', undefined)+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_member', { agentId: 'worker', creationId: 'super-0123456789abcdef' })).toEqual({ closed: true })+ expect(closeMember).toHaveBeenLastCalledWith('worker', 'super-0123456789abcdef')+ for (const creationId of ['short', 4]) expect(await answerExperimentQuery(core, allowed, 'superTabs', 'close_member', { agentId: 'worker', creationId })).toEqual({ error: 'INVALID_REQUEST' })+ for (const query of ['keep_lead_alive', 'close_member']) {+ expect(await answerExperimentQuery(core, allowed, 'orchestrator', query, { agentId: 'lead' })).toEqual({ error: 'NOT_SUPER_TABS' })+ for (const agentId of ['', '../x', 4]) expect(await answerExperimentQuery(core, allowed, 'superTabs', query, { agentId })).toEqual({ error: 'INVALID_REQUEST' })+ }+ expect(await answerExperimentQuery(fakeCore(), allowed, 'superTabs', 'keep_lead_alive', { agentId: 'lead' })).toEqual({ ok: false, error: 'UNSUPPORTED' })+ expect(await answerExperimentQuery(fakeCore(), allowed, 'superTabs', 'close_member', { agentId: 'worker' })).toEqual({ error: 'UNSUPPORTED' })+ expect(keepLeadAlive).toHaveBeenCalledTimes(1)+ expect(closeMember).toHaveBeenCalledTimes(2)+})diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.tsindex a38a19560..fc86f68fa 100644--- a/cli/src/core/experimentQueries.ts+++ b/cli/src/core/experimentQueries.ts@@ -7,6 +7,8 @@* and what its frame says about its harness (its viewer);* - `create`: create an agent, as the window's `agent_create` does;* - `creation_status`: read the exact native receipt without exposing its launch request;+ * - `keep_lead_alive`, `close_member`: for the Super Tab service alone, reopen a stopped Swarm Lead and close a member+ * whose session its backend ended, each only as core/api.ts allows;* - `stop_turn`: stop an agent's turn;* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);* - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;@@ -40,7 +42,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', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input'])+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'keep_lead_alive', 'close_member', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input'])const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])const text = (value: unknown): string => (typeof value === 'string' ? value : '')@@ -86,6 +88,17 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet...(typeof creationId === 'string' ? { creationId } : {}), ...(typeof sessionId === 'string' ? { sessionId } : {}),...(typeof createdAt === 'string' ? { createdAt } : {}), ...(typeof expiresAt === 'number' ? { expiresAt } : {}) }) ?? { error: 'UNSUPPORTED' }) }}+ // The Super Tab host keeps its Leads alive and closes the sessions its backend ends; the core decides which (core/api.ts).+ case 'keep_lead_alive':+ case 'close_member': {+ if (service !== 'superTabs') return { error: 'NOT_SUPER_TABS' }+ const { agentId, creationId } = payload+ if (typeof agentId !== 'string' || !/^[A-Za-z0-9_-]{1,160}$/.test(agentId)+ || creationId !== undefined && (typeof creationId !== 'string' || !/^[A-Za-z0-9_-]{16,96}$/.test(creationId))) return { error: 'INVALID_REQUEST' }+ return query === 'keep_lead_alive'+ ? { ...await (core.agents.keepLeadAlive?.(agentId) ?? { ok: false, error: 'UNSUPPORTED' }) }+ : { ...await (core.agents.closeMember?.(agentId, creationId as string | undefined) ?? { error: 'UNSUPPORTED' }) }+ }case 'stopped':return { stopped: !!text(payload.agentId) && await core.agents.stopped?.(text(payload.agentId)) === true }case 'gone':diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 56772e1f2..2fde7cc3d 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1,6 +1,6 @@import { createSwarmSkillAdoption } from './agents/swarmSkills.js'import { swarmRoleThrough } from './superTabSkills.js'-import { retainedHarnesses } from '../superTabs/retention.js'+import { mayBeLead, retainedHarnesses, retainedLeads } from '../superTabs/retention.js'import { createGridAssignments } from './agents/gridAssignments.js'import { createQuestionControls } from './engines/questionControls.js'import { masterRunsEngineQuestionControl } from '../harnessd/services.js'@@ -995,6 +995,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {// a harness another agent started. Read when it closes one, never now: the close service is built further down.closeAgent: (request) => backendRef?.closeAgentService?.request(request) ?? Promise.resolve({ error: 'UNSUPPORTED' }),activityAt: (session) => transcriptActivityAt(session.transcriptPath, session.engine),+ // The Super Tab host keeps its Leads alive and closes the sessions its backend ends (superTabs/host.ts). Read when it+ // asks, never now: the lifecycle is built further down, and one asked before then is refused, and asked again later.+ resumeAgent: async (agentId) => lifecycle.resumeAgent(agentId),+ swarmMembers: { leads: () => retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => retainedHarnesses(env.ADAPTER_DATA_DIR) },dsh: (session) => backendRef?.dshFrameProvider?.(session) ?? null,windows: (frame) => backendRef?.sendLocal(frame),daemon: { command: daemonCommand(), port: env.PORT, machineId: () => backendRef?.machineId ?? '', autonomousEnv: session?.autonomousEnv ?? env.AUTONOMOUS_ENV },@@ -2803,6 +2807,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A harness closed or stopped: the harnesses it started close with it (services/agentCleanup.ts).stopped: (agentId) => ports.agentCleanup?.closed(agentId),moveHeld: (agentId) => moveHeld.has(agentId),+ // The Lead of an active Swarm project is never stopped (owner, 2026-10-23); its host keeps the list (superTabs/retention.ts).+ leadProtected: (agentId) => mayBeLead(env.ADAPTER_DATA_DIR, agentId),})const stopJobs = lifecycle.stopJobslaunchCancelled = id => stopJobs.has(id)@@ -2828,6 +2834,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {announceSession,engineReady: (engine, ms) => engineLinks.ready(engine, ms),stoppedAgents,+ leadProtected: (agentId) => mayBeLead(env.ADAPTER_DATA_DIR, agentId),})backend.closeAgentService = closing.closeAgentServicebackend.closeAgentService.start()diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex ac80714e0..a29ea74be 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -1,6 +1,6 @@import { screenFor } from '../engines/screens.js'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { CloseAgentService, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'+import { CloseAgentService, LEAD_PROTECTED_DETAIL, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'import { registry, type RegisteredSession } from './registry.js'import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'@@ -35,16 +35,36 @@ 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 => {+it.each(['before', 'activity', 'checkpoint'] as const)('a Swarm close preserves a worker that stopped being Swarm-started 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 })+ if (phase === 'before') row.startedBy = undefined+ if (phase === 'activity') vi.mocked(deps.activity).mockImplementation(async () => { row.startedBy = undefined; return 'idle' })+ if (phase === 'checkpoint') vi.mocked(deps.checkpoint).mockImplementation(async () => { row.startedBy = undefined })const guarded = { ...request('now'), onlyIfOriginalLaunch: true }expect(await service.request(guarded)).toMatchObject({ error: expect.any(String) })expect(registry.byAgent(row.agentId)).toBe(row)})+// A machine restart stops a Swarm worker; reopened on its own conversation it is resume-only, and is still the Swarm's+// (2026-10-23: such a worker could no longer be stopped by the Swarm).+it('a Swarm close closes a worker reopened on the conversation it was started with', async () => {+ row.startedBy = 'agent'+ row.resumeOnly = true+ expect(await service.request({ ...request('now'), onlyIfOriginalLaunch: true })).toEqual({ closed: true })+})++// The review of #1635: Close after task answered a Swarm Lead "deferred", saved its plan, and said LEAD_PROTECTED only once+// the task ended. A Lead is refused at once, for every kind of close, before anything is read, saved or stopped.+it.each(['now', 'idle', 'after_task'] as const)('refuses to close a Swarm Lead (%s) at once, saving no plan', async mode => {+ const svc = new CloseAgentService({ ...deps, leadProtected: id => id === row.agentId })+ expect(await svc.request(request(mode))).toEqual({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })+ expect(registry.byAgent(row.agentId)?.closePlan).toBeUndefined()+ expect(deps.activity).not.toHaveBeenCalled()+ expect(deps.stop).not.toHaveBeenCalled()+ expect(await svc.request(request('inspect'))).toEqual({ activity: expect.any(String) })+ svc.dispose()+})+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 += 2diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex 219ed0083..e7db2e250 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -16,6 +16,8 @@ export type AgentClosePlan = {state: 'waiting' | 'failed'detail?: string}+/** Why the Lead of an active Swarm project is not closed (owner, 2026-10-23: it is never stopped, in any case). */+export const LEAD_PROTECTED_DETAIL = 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.'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 }@@ -93,7 +95,7 @@ function jobKey(request: AgentCloseRequest): string {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 || (request.expiresAt !== undefined && request.expiresAt <= at) || (request.onlyIfOriginalLaunch && (s.startedBy !== 'agent' || s.resumeOnly)) || new Date(s.registeredAt).toISOString() !== request.createdAt) return false+ if (!s || (request.expiresAt !== undefined && request.expiresAt <= at) || (request.onlyIfOriginalLaunch && s.startedBy !== 'agent') || 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".@@ -111,6 +113,8 @@ export interface CloseAgentServiceDeps {openTabs?: { assertHidden(s: RegisteredSession): Promise<void>; isHidden(s: RegisteredSession): boolean }/** Whether the conversation [request] names is closed already: no longer live, and kept as stopped. */closedAlready?(request: AgentCloseRequest): boolean+ /** Whether the agent may be the Lead of an active Swarm project (superTabs/retention.ts `mayBeLead`): never closed. */+ leadProtected?(agentId: string): booleannow?: () => numbersleep?: (ms: number) => Promise<void>}@@ -156,6 +160,10 @@ export class CloseAgentService {const current = this.deps.registry.byAgent(request.agentId)if (!matches(current, request, this.now())) return Promise.resolve(this.changed(request))if (request.mode === 'cancel') { this.cancel(request.agentId); return Promise.resolve({ cancelled: true }) }+ // Refused before anything is read or saved: a Close after task once answered a Lead "deferred" (the review of #1635).+ if (request.mode !== 'inspect' && this.deps.leadProtected?.(request.agentId)) {+ return Promise.resolve({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })+ }// A job answers only a request of its own kind. When any job running for the agent answered every// request, a close asked for while another window (or the cleanup preview) was inspecting the agent// was answered with that inspect's `{ activity }` and never carried out, and an inspect beside a@@ -213,7 +221,7 @@ export class CloseAgentService {const s = this.deps.registry.byAgent(request.agentId)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+ && (!request.onlyIfOriginalLaunch || s.startedBy === 'agent') ? s : undefined}let tried = target, result = first, waiting = falsefor (;;) {@@ -248,7 +256,7 @@ export class CloseAgentService {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.onlyIfOriginalLaunch || s.startedBy === 'agent')&& (!request.onlyIfHidden || this.deps.openTabs?.isHidden(s)) ? s : undefined}try {diff --git a/cli/src/services/agentCleanup.spec.ts b/cli/src/services/agentCleanup.spec.tsindex 1eb904c30..95ebb487e 100644--- a/cli/src/services/agentCleanup.spec.ts+++ b/cli/src/services/agentCleanup.spec.ts@@ -1,4 +1,4 @@-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -6,7 +6,7 @@ import { emptyPorts } from '../core/api.js'import type { AgentCloseResult } from '../lib/closeAgentService.js'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'-import { retainContributions } from '../superTabs/retention.js'+import { RETENTION_LAPSE_MS, retainContributions, retentionFile } from '../superTabs/retention.js'import { ASK_AGAIN_MS, CASCADE_RETRY_MS, CASCADE_TRIES, createAgentCleanup, IDLE_CLOSE_MS, JOINED_MAX, joinedPath, LOOK_EVERY_MS, startAgentCleanup, type AgentCleanupDeps } from './agentCleanup.js'const NOW = Date.parse('2026-10-12T12:00:00Z')@@ -75,6 +75,24 @@ it('keeps idle Super Tab members through host restarts and starter closure, untirestarted.cleanup.port.stop()})+// The owner, 2026-10-23: the Lead of an active project is never stopped in any case, nor when no roster has confirmed it+// for a week (a machine signed out), which lapses every other member to cleanup.+it('never closes a Swarm Lead, idle or orphaned, even once its roster has lapsed', async () => {+ const sessions = [kid('pm'), kid('member')]+ const t = setup(sessions, { pm: 2 * IDLE_CLOSE_MS, member: 2 * IDLE_CLOSE_MS })+ retainContributions(dir, 'machine-1', [{ tabId: 'tab', lead: true, agent: { harnessId: 'pm', machineId: 'machine-1' } },+ { tabId: 'tab', agent: { harnessId: 'member', machineId: 'machine-1' } }])+ const lapsed = new Date(Date.now() - RETENTION_LAPSE_MS - MIN)+ utimesSync(retentionFile(dir), lapsed, lapsed)+ await t.cleanup.look()+ t.advance(IDLE_CLOSE_MS)+ await t.cleanup.look()+ await t.cleanup.closeStartedBy('lead')+ expect(t.closeStarted.mock.calls).toEqual([['member', 'idle']])+ expect(sessions.map(s => s.agentId)).toEqual(['pm'])+ t.cleanup.port.stop()+})+it('rechecks retention after waiting on activity or another orphan close', async () => {const t = setup([kid('member')], { member: 2 * IDLE_CLOSE_MS })await t.cleanup.look()diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex 81610c0a0..e254b3b4a 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -392,3 +392,29 @@ it('carries the exact native close identity through the service process and failexpect(await processCoreApi('/data', 'superTabs', { ask }).agents.closeSwarm!(request)).toEqual({ error: 'SERVICE_UNAVAILABLE' })expect(await processCoreApi('/data', 'superTabs').agents.closeSwarm!(request)).toEqual({ error: 'SERVICE_UNAVAILABLE' })})++it('asks the core to reopen a Lead or close a member, and fails closed without it', async () => {+ const ask = vi.fn(async (query: string): Promise<Record<string, unknown>> => query === 'keep_lead_alive' ? { ok: true } : { closed: true })+ const api = processCoreApi('/data', 'superTabs', { ask })+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: true })+ expect(ask).toHaveBeenLastCalledWith('keep_lead_alive', { agentId: 'lead' })+ expect(await api.agents.closeMember!('worker')).toEqual({ closed: true })+ expect(ask).toHaveBeenLastCalledWith('close_member', { agentId: 'worker' })+ expect(await api.agents.closeMember!('worker', 'super-0123456789abcdef')).toEqual({ closed: true })+ expect(ask).toHaveBeenLastCalledWith('close_member', { agentId: 'worker', creationId: 'super-0123456789abcdef' })+ ask.mockResolvedValueOnce({ ok: false, error: 'AGENT_BUSY', detail: 'busy' })+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'AGENT_BUSY', detail: 'busy' })+ ask.mockResolvedValueOnce({ ok: false, error: 'NOT_A_LEAD' })+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'NOT_A_LEAD' })+ ask.mockResolvedValueOnce({ ok: false })+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })+ ask.mockResolvedValueOnce({ ok: 'yes' })+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })+ ask.mockRejectedValueOnce(new Error('offline'))+ expect(await api.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })+ ask.mockRejectedValueOnce(new Error('offline'))+ expect(await api.agents.closeMember!('worker')).toEqual({ error: 'SERVICE_UNAVAILABLE' })+ const alone = processCoreApi('/data', 'superTabs')+ expect(await alone.agents.keepLeadAlive!('lead')).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })+ expect(await alone.agents.closeMember!('worker')).toEqual({ error: 'SERVICE_UNAVAILABLE' })+})diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 456a3cb38..64f0287ad 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -127,6 +127,15 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViebyAgent: (agentId) => live().find((session) => session.agentId === agentId),closeSwarm: async request => await (ask?.('close_swarm', { ...request }) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' })).catch(() => ({ error: 'SERVICE_UNAVAILABLE' })),+ keepLeadAlive: async agentId => {+ const answer = await ask?.('keep_lead_alive', { agentId }).catch(() => null)+ if (answer?.ok === true) return { ok: true }+ return answer?.ok === false && typeof answer.error === 'string'+ ? { ok: false, error: answer.error, ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }+ : { ok: false, error: 'SERVICE_UNAVAILABLE' }+ },+ closeMember: async (agentId, creationId) => await (ask?.('close_member', { agentId, ...(creationId ? { creationId } : {}) }) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }))+ .catch(() => ({ error: 'SERVICE_UNAVAILABLE' })),stopped: async agentId => (await ask?.('stopped', { agentId }).catch(() => null))?.stopped === true,gone: async agentId => (await ask?.('gone', { agentId }).catch(() => null))?.gone === true,creationStatus: async creationId => creationObservation(creationId,diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex b8e1c1bf9..599f549fc 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -5,7 +5,7 @@ import { prepareSwarmSkill } from '../lib/swarmSkills.js'import { afterEach, describe, expect, it, vi } from 'vitest'import type { CoreApi, TurnDelivery } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'-import { backend, swarmRoleFor, hostJournalFile, SuperTabHost } from './host.js'+import { backend, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'import { retainedHarnesses, retentionFile } from './retention.js'import { observerSource } from './observers.js'@@ -41,7 +41,7 @@ function setup(messageFields: Record<string, unknown> = {}) {turns: { onDelivery: vi.fn(fn => { listeners.add(fn); return () => { listeners.delete(fn) } }) },})const log = vi.fn()- const open = () => { const host = new SuperTabHost(core, 'machine-1', { log, now: () => clock }); hosts.push(host); return host }+ const open = (options: SuperTabHostOptions = {}) => { const host = new SuperTabHost(core, 'machine-1', { log, now: () => clock, ...options }); hosts.push(host); return host }const event = (state: TurnDelivery['state'], reason?: string) => {for (const fn of listeners) fn({ deliveryId: 'team:service:superTabs:delivery', sessionId: 'harness', state, reason })}@@ -733,6 +733,24 @@ function releaseFixture(nativeKind = 'swarm', result: Record<string, unknown> =return { ...t, host, target, native, lookup, close, lease, remove, sent, poll }}+// On 2026-10-23 a worker its machine's restart had stopped, reopened on the same conversation, could no longer be stopped by+// the Swarm ("not started by the Swarm"): the reopen marks the row resume-only, though it is still the Swarm's session.+it('stops a Swarm worker reopened after a restart on the conversation the Swarm started', async () => {+ const t = releaseFixture('swarm', { closed: true })+ Object.assign(t.native, { resumeOnly: true })+ await t.poll()+ await vi.waitFor(() => expect(t.remove).toHaveBeenCalledOnce())+ expect(t.close).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'harness', creationId: 'super-original-creation', sessionId: 'native' }))+})++it('still refuses, as changed, a reopened worker that now runs another conversation', async () => {+ const t = releaseFixture('changed', { closed: true })+ Object.assign(t.native, { resumeOnly: true })+ for (let i = 0; i < 3; i++) await t.poll(130_000)+ expect(t.close).not.toHaveBeenCalled()+ expect(t.remove).not.toHaveBeenCalled()+})+// A Swarm start before #1527 left only its start record and the native creation receipt (super-<startId>).const group = { id: 'group', leadId: 'lead', agentIds: ['lead', 'agent'], assignment: { agentId: 'agent', status: 'done' } }const legacyStarts = { starts: [{ id: 'start-1', creationId: 'super-start-1', harnessId: 'harness', request: { machineId: 'machine-1', name: 'Permission builder' }, error: null }] }@@ -1183,3 +1201,179 @@ describe('built-in skill text after a CLI update', () => {expect(f.sent).toHaveLength(3)})})++/** A host on this machine whose roster is [rows] (changeable), with the core's keep-alive and member close mocked. */+function lifeFixture(rows: Record<string, unknown>[], options: SuperTabHostOptions = {}) {+ const t = setup(), host = t.open(options)+ const commands: Record<string, unknown>[] = []+ let live = false+ const keepLeadAlive = vi.fn(async () => ({ ok: false as const, error: 'AGENT_BUSY' } as { ok: true } | { ok: false; error: string }))+ const closeMember = vi.fn(async () => ({ closed: true as const } as { closed?: true; error?: string }))+ t.core.agents.byAgent = vi.fn(() => (live ? { agentId: 'harness' } : undefined) as never)+ t.core.agents.keepLeadAlive = keepLeadAlive+ t.core.agents.closeMember = closeMember+ t.core.account.backend = async (_method, path, body) => {+ if ((body as any)?.command) { commands.push(body as Record<string, unknown>); return { status: 200, body: { data: {} } } }+ if (path.includes('/hosts/')) return { status: 200, body: { data: rows } }+ return { status: 200, body: { data: [] } }+ }+ const poll = async (advance = 0) => { t.wait(advance); await host.tick(); for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve)) }+ return { ...t, host, rows, commands, keepLeadAlive, closeMember, poll, live: (value: boolean) => { live = value } }+}+const leadRow = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', lead: true, active: true, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }, ...extra })++describe('keeping a Swarm Lead alive', () => {+ // The owner, 2026-10-23: a Lead whose session died (a machine restart, a kill) stalls its whole project until someone+ // reopens it by hand. Its host reopens it on its own conversation; a crash loop must not spin.+ it('reopens a Lead whose session is gone, backing off while it cannot, and leaves a live one alone', async () => {+ const t = lifeFixture([leadRow()])+ await t.poll()+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')+ await t.poll(4_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ await t.poll(1_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(2)+ await t.poll(9_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(2)+ await t.poll(1_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(3)+ // The wait doubles, up to half an hour.+ for (let i = 0; i < 20; i++) await t.poll(30 * 60_000)+ const calls = t.keepLeadAlive.mock.calls.length+ await t.poll(30 * 60_000 - 1)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(calls)+ await t.poll(1)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(calls + 1)+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('Could not reopen the Product Manager'))+ t.keepLeadAlive.mockResolvedValue({ ok: true })+ await t.poll(30 * 60_000)+ t.live(true)+ for (let i = 0; i < 3; i++) await t.poll(60 * 60_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(calls + 2)+ // Gone again later: reopened at once, its backoff started over.+ t.live(false)+ await t.poll()+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(calls + 3)+ })++ it('waits a minute after a reopen it asked for before asking again', async () => {+ const t = lifeFixture([leadRow()])+ t.keepLeadAlive.mockResolvedValue({ ok: true })+ await t.poll()+ await t.poll(59_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ await t.poll(1_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(2)+ })++ it('reopens no agent the roster does not mark Lead: once its project is deleted, or while it is being stopped', async () => {+ const t = lifeFixture([leadRow()])+ await t.poll()+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ t.rows.splice(0, 1, leadRow({ lead: false }))+ for (let i = 0; i < 3; i++) await t.poll(30 * 60_000)+ t.rows.splice(0, 1, leadRow({ stopRequested: true }), leadRow({ closeSession: true, agent: { id: 'other', harnessId: 'other', machineId: 'machine-1' } }))+ for (let i = 0; i < 3; i++) await t.poll(30 * 60_000)+ t.rows.splice(0, 2)+ for (let i = 0; i < 3; i++) await t.poll(30 * 60_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ })++ it('reopens nothing on a core that cannot', async () => {+ const t = lifeFixture([leadRow()])+ t.core.agents.keepLeadAlive = undefined+ await t.poll()+ expect(t.keepLeadAlive).not.toHaveBeenCalled()+ })+})++describe('closing the sessions the backend ends', () => {+ const ended = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', closeSession: true, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }, ...extra })++ // Deleting a project left its Lead's session running, and removing an ordinary agent left its session behind (owner,+ // 2026-10-23: no zombie agents). The backend marks the session; this host closes it and says so.+ it('closes a member it knew, says it closed once, and never closes it again', async () => {+ const t = lifeFixture([leadRow({ lead: false })])+ await t.poll()+ t.rows.splice(0, 1, ended())+ await t.poll()+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(t.closeMember).toHaveBeenCalledWith('harness', undefined)+ expect(t.commands[0]).toEqual({ operationId: 'session-closed-agent-harness', command: { type: 'agent.sessionClosed', agentId: 'agent', harnessId: 'harness' } })+ for (let i = 0; i < 3; i++) await t.poll(60_000)+ expect(t.closeMember).toHaveBeenCalledTimes(1)+ expect(t.commands).toHaveLength(1)+ })++ it('closes after a host restart a member the last roster named, and retries a lost acknowledgement without closing twice', async () => {+ const t = lifeFixture([leadRow({ lead: false })])+ await t.poll()+ t.host.stop()+ t.rows.splice(0, 1, ended())+ let refused = 1+ const backend = t.core.account.backend+ t.core.account.backend = async (method, path, body) => (body as any)?.command?.type === 'agent.sessionClosed' && refused-- > 0+ ? { status: 503, body: { success: false, error: { code: 'BACKEND_UNAVAILABLE', message: 'down' } } } : backend(method, path, body)+ const restarted = t.open()+ const poll = async (advance = 0) => { t.wait(advance); await restarted.tick(); for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve)) }+ await poll()+ expect(t.log).toHaveBeenCalledWith('down')+ await poll(5_000)+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(t.closeMember).toHaveBeenCalledTimes(1)+ })++ it('never asks to close a Lead, and acknowledges nothing the core refuses as not its member', async () => {+ const t = lifeFixture([ended({ lead: true })])+ for (let i = 0; i < 3; i++) await t.poll(60_000)+ expect(t.closeMember).not.toHaveBeenCalled()+ t.rows.splice(0, 1, ended())+ t.closeMember.mockResolvedValue({ error: 'NOT_A_MEMBER' })+ for (let i = 0; i < 3; i++) await t.poll(60_000)+ expect(t.closeMember).toHaveBeenCalledWith('harness', undefined)+ expect(t.commands).toHaveLength(0)+ })++ // The review of #1635: an agent removed before this host wrote its first roster was never a member here, so it was never+ // closed nor acknowledged, and its row stayed for good. The released backend's row names only the harness; this host's+ // own record of the Swarm start that created it is the proof, which the core checks against its receipt.+ it('closes an agent removed before any roster named it, proven by this host\'s start of it', async () => {+ const t = lifeFixture([ended()], { startReceipt: harnessId => harnessId === 'harness' ? 'super-0123456789abcdef' : null })+ await t.poll()+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(t.closeMember).toHaveBeenCalledWith('harness', 'super-0123456789abcdef')+ })++ it('still closes a known member when this host\'s start record cannot be read', async () => {+ const t = lifeFixture([ended()], { startReceipt: () => { throw new Error('The capacity ledger is unreadable.') } })+ await t.poll()+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(t.closeMember).toHaveBeenCalledWith('harness', undefined)+ })++ it('backs off a close the core refuses, and acknowledges nothing until it closes', async () => {+ const t = lifeFixture([leadRow({ lead: false })])+ await t.poll()+ t.rows.splice(0, 1, ended())+ t.closeMember.mockResolvedValue({ error: 'LEAD_PROTECTED' })+ await t.poll()+ await t.poll(4_000)+ expect(t.closeMember).toHaveBeenCalledTimes(1)+ await t.poll(1_000)+ expect(t.closeMember).toHaveBeenCalledTimes(2)+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('LEAD_PROTECTED'))+ t.closeMember.mockResolvedValue({ closed: true })+ await t.poll(10_000)+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ })++ it('closes nothing on a core that cannot', async () => {+ const t = lifeFixture([leadRow({ lead: false })])+ await t.poll()+ t.core.agents.closeMember = undefined+ t.rows.splice(0, 1, ended())+ await t.poll()+ expect(t.commands).toHaveLength(0)+ })+})diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 0e437a16b..291dc5eb8 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -93,6 +93,8 @@ export interface SuperTabHostOptions {prepareContribution?: typeof prepareContribution/** The `… super-tab` prefix agents are told to run (superTabs/shortCommand.ts), for a spec. */agentCommand?: (core: CoreApi, machineId: string) => Promise<string>+ /** The Swarm start this machine made of a harness (superTabs/reservations.ts), or null. */+ startReceipt?: (harnessId: string) => string | null}const defaultAgentCommand = (core: CoreApi, machineId: string) => agentCommandPrefix(core.daemon, machineId,@@ -107,9 +109,18 @@ const SKILL_RETRY_MS = 60_000const JOIN_RETRY_MAX_MS = 30 * 60_000/** Refusals no retry can change while this host runs: the Swarm has all its machines, or this account does not own it. */const JOIN_FINAL = new Set(['MACHINES_FULL', 'OWNER_REQUIRED'])+/** A Lead's reopen that failed (an engine that cannot start, a busy pane) waits this long, doubling up to half an hour, so a+ * crash loop never spins; one the core took waits a minute for its session to show before it is asked again. */+const LEAD_RETRY_MS = 5_000+const LEAD_RETRY_MAX_MS = 30 * 60_000+const LEAD_REOPEN_WAIT_MS = 60_000+/** The first wait after a session the backend ended could not be closed or acknowledged, doubling up to ten minutes. */+const END_RETRY_MS = 5_000+const END_RETRY_MAX_MS = 10 * 60_000/** How long after a pre-#1527 Swarm launch its engine may first bind a session and still be the Swarm's own. */const LEGACY_FIRST_BIND_MS = 120_000const typedId = (entry: Entry) => `team:service:superTabs:${entry.deliveryId}`+const endingKey = (target: HostAgent) => `${target.tabId}:${target.agent.id}:${target.agent.harnessId}`const writeJournal = (file: string, journal: Journal) => {mkdirSync(dirname(file), { recursive: true, mode: 0o700 })const temporary = `${file}.next`@@ -161,6 +172,7 @@ export class SuperTabHost {private nextReceiptsAt = 0private receiptCursor = 0private readonly agentCommand: (core: CoreApi, machineId: string) => Promise<string>+ private readonly startReceipt: (harnessId: string) => string | null/** Asked once, on the first delivery: the answer cannot change while this daemon runs (superTabs/shortCommand.ts). */private prefix: Promise<string> | null = nullprivate configurationsRunning: Promise<void> | null = null@@ -182,6 +194,10 @@ export class SuperTabHost {private readonly skillModes = new Map<string, SwarmSkillMode>()private skillsRunning: Promise<void> | null = nullprivate missing = new Map<string, number>()+ /** Per Lead harness here: a reopen in progress, its failures, when the next may run, and the reason last logged. */+ private readonly keepAlives = new Map<string, { running: boolean; failures: number; retryAt: number; reason?: string }>()+ /** Per session the backend ends: a close or acknowledgement in progress, how far it got, and when the next try may run. */+ private readonly endings = new Map<string, { running: boolean; closed: boolean; acked: boolean; failures: number; retryAt: number }>()/** A Lead's reads of and typing into this machine's agents' terminals, and the stuck and usage-limit alerts. */private readonly terminal: TerminalHost@@ -192,6 +208,7 @@ export class SuperTabHost {this.attachedFiles = options.attachedFiles ?? attachedFilesthis.prepareContribution = options.prepareContribution ?? prepareContributionthis.agentCommand = options.agentCommand ?? defaultAgentCommand+ this.startReceipt = options.startReceipt ?? (() => null)this.now = options.now ?? Date.nowthis.write = options.write ?? writeJournalthis.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))@@ -369,10 +386,12 @@ export class SuperTabHost {// 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)+ // A reopen keeps the row's harness, conversation and registeredAt but marks it resume-only: still the Swarm's+ // session (2026-10-23, a worker reopened after its machine restarted was refused as "not started by the Swarm").+ if (native.startedBy !== 'agent' || !identifier(identity.creationId)|| typeof identity.sessionId !== 'string' || !identity.sessionId || typeof identity.createdAt !== 'string'|| native.sessionId !== identity.sessionId || native.registeredAt !== Date.parse(identity.createdAt)) {- refuse(native.startedBy === 'agent' && !native.resumeOnly && identifier(identity.creationId) ? 'AGENT_CHANGED' : 'NOT_SWARM_STARTED')+ refuse(native.startedBy === 'agent' && identifier(identity.creationId) ? 'AGENT_CHANGED' : 'NOT_SWARM_STARTED')return}const creation = await this.core.agents.creationStatus?.(identity.creationId)@@ -486,15 +505,26 @@ export class SuperTabHost {for (const key of this.releaseAttempts.keys()) if (!stopKeys.has(key)) this.releaseAttempts.delete(key)const seen = new Set<string>()const running: HostAgent[] = []+ const leads = new Set<string>(), ended = 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) continueconst target = row as unknown as HostAgent+ // A row still marked Lead is never closed (owner, 2026-10-23); one marked both is neither closed nor reopened.+ if (row.closeSession === true) {+ ended.add(endingKey(target))+ if (row.lead !== true) this.endSession(target)+ continue+ }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}+ if (row.lead === true) {+ leads.add(target.agent.harnessId)+ this.keepAlive(target.agent.harnessId)+ }// 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)) continuerunning.push(target)@@ -520,6 +550,9 @@ export class SuperTabHost {}}if (this.stopped) return+ // A Lead the roster no longer marks (its project deleted) is never reopened again.+ for (const [harnessId, state] of this.keepAlives) if (!leads.has(harnessId) && !state.running) this.keepAlives.delete(harnessId)+ for (const [key, state] of this.endings) if (!ended.has(key) && !state.running) this.endings.delete(key)for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)for (const entry of Object.values(this.journal.entries)) {const id = typedId(entry)@@ -539,6 +572,63 @@ export class SuperTabHost {.finally(() => { this.skillsRunning = null })}+ /** The owner, 2026-10-23: the Lead of an active project stays alive. One whose session is gone (a machine restart, a+ * kill) is reopened on its own conversation; nothing is typed into it, so no old input is replayed. A failure backs+ * off, so an engine that cannot start never spins. */+ private keepAlive(harnessId: string): void {+ const reopen = this.core.agents.keepLeadAlive+ if (!reopen) return+ const state = this.keepAlives.get(harnessId) ?? { running: false, failures: 0, retryAt: 0 }+ this.keepAlives.set(harnessId, state)+ if (state.running) return+ if (this.core.agents.byAgent(harnessId)) { state.failures = 0; state.retryAt = 0; delete state.reason; return }+ if (this.now() < state.retryAt) return+ state.running = true+ const failed = (reason: string) => {+ state.retryAt = this.now() + Math.min(LEAD_RETRY_MAX_MS, LEAD_RETRY_MS * 2 ** state.failures++)+ if (reason !== state.reason) this.log(`Could not reopen the Product Manager ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)+ state.reason = reason+ }+ void reopen(harnessId).then(result => {+ if (!result.ok) return failed(result.detail ?? result.error)+ state.failures = 0+ state.retryAt = this.now() + LEAD_REOPEN_WAIT_MS+ delete state.reason+ }, error => failed(error instanceof Error ? error.message : String(error))).finally(() => { state.running = false })+ }++ /** Deleting a project left its Lead's session running, and removing an agent left its session behind (owner, 2026-10-23:+ * no zombie agents). The backend marks the session; this closes it, keeping its conversation, and says so once. */+ private endSession(target: HostAgent): void {+ const close = this.core.agents.closeMember+ if (!close || this.stopped) return+ const { tabId, agent } = target+ const key = endingKey(target)+ const state = this.endings.get(key) ?? { running: false, closed: false, acked: false, failures: 0, retryAt: 0 }+ this.endings.set(key, state)+ if (state.running || state.acked || this.now() < state.retryAt) return+ state.running = true+ void (async () => {+ if (!state.closed) {+ // The core closes only a member the retention names, or one this machine's Swarm start proves its own: an agent+ // removed before this host wrote its first roster was never a member here, and the backend's row names only the+ // harness (the review of #1635). An unreadable start record still lets the retention decide.+ let started: string | null = null+ try { started = this.startReceipt(agent.harnessId) } catch (error) { this.log(error instanceof Error ? error.message : String(error)) }+ const result = await close(agent.harnessId, started ?? undefined)+ if (!result.closed) throw new Error(`Could not close a session the Swarm ended (${result.error ?? 'unknown'}${result.detail ? `: ${result.detail}` : ''}).`)+ state.closed = true+ }+ if (this.stopped) return+ await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `session-closed-${agent.id}-${agent.harnessId}`,+ command: { type: 'agent.sessionClosed', agentId: agent.id, harnessId: agent.harnessId } })+ state.acked = true+ })().catch(error => {+ state.retryAt = this.now() + Math.min(END_RETRY_MAX_MS, END_RETRY_MS * 2 ** state.failures++)+ this.log(error instanceof Error ? error.message : String(error))+ }).finally(() => { state.running = false })+ }+/** A CLI update can ship new built-in skill text while Swarm sessions run; until now a running agent kept the text it* read at start, so a skill release reached nobody until each agent restarted (owner, 2026-10-22). Rewrite a role* session's file at once; tell its agent through the Swarm, as any delivery, once it is in an open group. Thediff --git a/cli/src/superTabs/reservations.spec.ts b/cli/src/superTabs/reservations.spec.tsindex d0c4f1f90..f0c33c8e5 100644--- a/cli/src/superTabs/reservations.spec.ts+++ b/cli/src/superTabs/reservations.spec.ts@@ -82,6 +82,19 @@ it('retains a learned harness identity after its native window disappears and reexpect(await restarted.observe(id(1))).toMatchObject({ harnessId: 'native', released: true })})+// The review of #1635: the backend's closeSession row names only the harness, so the host finds the Swarm's own start of+// it here, the receipt every start confirmed against the core before it reported success.+it('names the start that created a harness, even after it stopped, and none for a harness it never started', async () => {+ const f = setup(), book = f.open()+ await book.reserve(input())+ expect(book.creationOf('native')).toBeNull()+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'native' })+ f.stopped.add('native')+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'native', released: true })+ expect(book.creationOf('native')).toBe(id(1))+ expect(book.creationOf('another')).toBeNull()+})+it('recovers a harness that started and stopped before the service observed its creation', async () => {const f = setup(), book = f.open()await book.reserve(input())diff --git a/cli/src/superTabs/reservations.ts b/cli/src/superTabs/reservations.tsindex 8b759f668..db8a92b15 100644--- a/cli/src/superTabs/reservations.ts+++ b/cli/src/superTabs/reservations.ts@@ -24,6 +24,7 @@ interface Reservation {export interface ReservationBook {reserve(input: Json, closed?: AbortSignal): Promise<Json>observe(creationId: unknown, closed?: AbortSignal): Promise<Json>+ creationOf(harnessId: string): string | nullstop(): void}interface Dependencies {@@ -160,6 +161,14 @@ export class CapacityReservations implements ReservationBook {: { error: 'CAPACITY_RECEIPT_MISSING', detail: 'This start has no capacity receipt. Inspect the machine before starting another agent.' }}+ /** The Swarm start that created this harness: every start confirms the harness its native receipt names before it+ * reports success, and a stopped one keeps its row. The core still checks the receipt itself. */+ creationOf(harnessId: string): string | null {+ this.check()+ const row = this.db.prepare('SELECT creation_id FROM reservations WHERE harness_id = ? ORDER BY created_at DESC LIMIT 1').get(harnessId)+ return typeof row?.creation_id === 'string' ? row.creation_id : null+ }+async reserve(input: Json, closed?: AbortSignal): Promise<Json> {const { creationId, cwd } = input, request = object(input.requirements)const memory = request.memoryBytes ?? 0, disk = request.diskBytes ?? 0, cpu = request.maxCpuPercent ?? 100diff --git a/cli/src/superTabs/retention.spec.ts b/cli/src/superTabs/retention.spec.tsindex 2571ed06d..9b419b062 100644--- a/cli/src/superTabs/retention.spec.ts+++ b/cli/src/superTabs/retention.spec.ts@@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, wrimport { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, expect, it } from 'vitest'-import { RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retentionFile } from './retention.js'+import { mayBeLead, RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retainedLeads, retentionFile } from './retention.js'const roots: string[] = []const root = () => { const dir = mkdtempSync(join(tmpdir(), 'super-retention-')); roots.push(dir); return dir }@@ -58,3 +58,53 @@ it('pauses cleanup on corrupt or oversized retention until the host rewrites itunlinkSync(file)expect([...retainedHarnesses(dir, now)]).toEqual([])})++// The owner, 2026-10-23: the Lead of an active project is never stopped, in any case. It is kept from cleanup even when+// its groups read as archived, and never lapses: a machine signed out for a week still keeps its Lead.+it('keeps a Lead apart, never lapses it, and releases it only when a confirmed roster no longer marks it', () => {+ const dir = root(), now = Date.now()+ expect([...retainedLeads(dir)]).toEqual([])+ retainContributions(dir, 'machine', [row('lead', { lead: true, active: false }), row('worker'), row('foreign-lead', { lead: true }, 'other')], now)+ expect([...retainedLeads(dir)]).toEqual(['lead'])+ expect([...retainedHarnesses(dir, now)]).toEqual(['lead', 'worker'])+ expect([...retainedHarnesses(dir, now + RETENTION_LAPSE_MS + 1000)]).toEqual(['lead'])+ retainContributions(dir, 'machine', [row('lead', { closeSession: true }), row('worker')], now)+ expect([...retainedLeads(dir)]).toEqual([])+})++it('reopens no Lead from an unreadable file', () => {+ const dir = root()+ retainContributions(dir, 'machine', [row('lead', { lead: true })])+ writeFileSync(retentionFile(dir), '{')+ expect([...retainedLeads(dir)]).toEqual([])+})++// The review of #1635: a file from before Leads were kept, or one that cannot be read, must not let a stop through to a+// Lead. Until a roster says which members are Leads, each member may be one; a file nobody can read protects them all.+it('treats a stop as possibly of a Lead until a valid roster says otherwise', () => {+ const dir = root(), file = retentionFile(dir)+ expect(mayBeLead(dir, 'anyone')).toBe(false)+ retainContributions(dir, 'machine', [row('lead', { lead: true }), row('worker')])+ expect([mayBeLead(dir, 'lead'), mayBeLead(dir, 'worker'), mayBeLead(dir, 'personal')]).toEqual([true, false, false])+ writeFileSync(file, JSON.stringify({ version: 2, machineId: 'machine', harnesses: ['old-member'] }))+ expect([mayBeLead(dir, 'old-member'), mayBeLead(dir, 'personal')]).toEqual([true, false])+ writeFileSync(file, '{')+ expect([mayBeLead(dir, 'old-member'), mayBeLead(dir, 'personal')]).toEqual([true, true])+ retainContributions(dir, 'machine', [row('worker')])+ expect([mayBeLead(dir, 'old-member'), mayBeLead(dir, 'worker')]).toEqual([false, false])+})++// A session the backend ends is closed by the host, and only one it already kept as a member: the retention is that proof,+// across host restarts, for the host and for the core's close alike.+it('keeps a session the backend ends only while it was already a member', () => {+ const dir = root(), now = Date.now()+ retainContributions(dir, 'machine', [row('stranger', { closeSession: true, active: false })], now)+ expect([...retainedHarnesses(dir, now)]).toEqual([])+ retainContributions(dir, 'machine', [row('member')], now)+ retainContributions(dir, 'machine', [row('member', { closeSession: true, active: false }), row('stranger', { closeSession: true })], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['member'])+ retainContributions(dir, 'machine', [row('member', { closeSession: true })], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['member'])+ retainContributions(dir, 'machine', [], now)+ expect([...retainedHarnesses(dir, now)]).toEqual([])+})diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.tsindex bf15031e1..1d8c2852c 100644--- a/cli/src/superTabs/retention.ts+++ b/cli/src/superTabs/retention.ts@@ -3,13 +3,16 @@* roster read may release it to automatic cleanup. This grants no input access.** Membership only in archived groups is not in use, and a roster nobody confirms- * for a week (signed out, unlinked machine) lapses. A paused tab still counts:- * pause blocks new work, while discussion and running assignments continue. */+ * for a week (signed out, unlinked machine) lapses, except a project's Lead, which+ * is never stopped. A paused tab still counts: pause blocks new work, while+ * discussion and running assignments continue. */import { existsSync, mkdirSync, readFileSync, renameSync, statSync, utimesSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { identifier, object } from './wire.js'-interface Retention { version: 2; machineId: string; harnesses: string[] }+/** `leads`: the Leads of active projects here, which never lapse (owner, 2026-10-23: the Lead of an active project is never+ * stopped in any case). Absent in a file from before Leads were kept. */+interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[] }export const retentionFile = (dataDir: string) => join(dataDir, 'super-tabs', 'retained.json')export const RETENTION_LAPSE_MS = 7 * 24 * 60 * 60_000const REFRESH_MS = 60 * 60_000@@ -18,7 +21,8 @@ function read(file: string): Retention {if (statSync(file).size > 4 * 1024 * 1024) throw new Error('Super Tab retention is too large. Automatic cleanup is paused.')let value: Record<string, unknown> = {}try { value = object(JSON.parse(readFileSync(file, 'utf8'))) } catch { /* reported below */ }- if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)) {+ if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)+ || (value.leads !== undefined && (!Array.isArray(value.leads) || !value.leads.every(identifier)))) {throw new Error('Super Tab retention is unreadable. Automatic cleanup is paused.')}return value as unknown as Retention@@ -27,25 +31,50 @@ function read(file: string): Retention {export function retainedHarnesses(dataDir: string, now = Date.now()): Set<string> {const file = retentionFile(dataDir)// An unreadable file fails closed only until it lapses; the host rewrites it on its next roster.- if (!existsSync(file) || now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return new Set()+ if (!existsSync(file)) return new Set()+ if (now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return retainedLeads(dataDir)return new Set(read(file).harnesses)}+/** The Leads here the host may reopen: only those a valid roster named. */+export function retainedLeads(dataDir: string): Set<string> {+ try { return new Set(read(retentionFile(dataDir)).leads) } catch { return new Set() }+}++/** Whether a stop may reach a Lead, for the core's guard, which fails closed (the review of #1635): with no file this+ * machine never had a roster, so no Lead; one from before Leads were kept names no Lead apart, so each member may be one;+ * one that cannot be read may name anyone, until the host's next roster rewrites it. */+export function mayBeLead(dataDir: string, agentId: string): boolean {+ const file = retentionFile(dataDir)+ if (!existsSync(file)) return false+ try {+ const kept = read(file)+ return (kept.leads ?? kept.harnesses).includes(agentId)+ } catch { return true }+}+export function retainContributions(dataDir: string, machineId: string, rows: unknown[], now = Date.now()): void {if (!identifier(machineId)) throw new Error('Invalid Super Tab retention machine.')- const ids = new Set<string>()- for (const item of rows) {- const row = object(item), agent = object(row.agent)- if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue- if (row.active === false) continue- ids.add(agent.harnessId)- }const file = retentionFile(dataDir)- const next: Retention = { version: 2, machineId, harnesses: [...ids].sort() }// This machine's confirmed roster is authoritative: it replaces an unreadable// file and another identity's entry. Unchanged rosters only refresh the lapse clock.let previous: Retention | null = nulltry { if (existsSync(file)) previous = read(file) } catch { /* rebuilt below */ }+ const ids = new Set<string>(), leads = new Set<string>()+ for (const item of rows) {+ const row = object(item), agent = object(row.agent)+ if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue+ // A session the backend ends (its project deleted, the agent removed) stays kept until the host has closed it, and+ // only if it was a member here before: the host and the core close nothing this file did not already name.+ if (row.closeSession === true && row.lead !== true) {+ if (previous?.machineId === machineId && previous.harnesses.includes(agent.harnessId)) ids.add(agent.harnessId)+ continue+ }+ if (row.lead === true) leads.add(agent.harnessId)+ else if (row.active === false) continue+ ids.add(agent.harnessId)+ }+ const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort() }if (previous && JSON.stringify(previous) === JSON.stringify(next)) {if (now - statSync(file).mtimeMs > REFRESH_MS) utimesSync(file, new Date(now), new Date(now))returndiff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex d13db725b..153c6049a 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest'import { fakeCore } from '../testing/fakeCore.js'import type { CoreApi } from '../core/api.js'import { superTabService } from './service.js'-import { SuperTabHostError, type SuperTabHost } from './host.js'+import { SuperTabHostError, type SuperTabHost, type SuperTabHostOptions } from './host.js'const owner = { local: true, owner: true }, visitor = { local: false, owner: false }function setup(options: { prepareContribution?: typeof import('./contribution.js').prepareContribution } = {}) {@@ -229,7 +229,7 @@ it('keeps host capacity separate from account authority and closes it on disconnconst core = fakeCore()const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))const observe = vi.fn(async () => ({ ok: true, released: true }))- const stop = vi.fn(), factory = vi.fn(() => ({ reserve, observe, stop }))+ const stop = vi.fn(), factory = vi.fn(() => ({ reserve, observe, creationOf: vi.fn(() => null), stop }))const service = superTabService(core, { reservations: factory })const closed = new AbortController().signalexpect(factory).not.toHaveBeenCalled()@@ -247,6 +247,21 @@ it('keeps host capacity separate from account authority and closes it on disconnservice.port.stop(); expect(stop).toHaveBeenCalledTimes(3)})+it('gives the host this machine\'s record of the Swarm starts, to close a session the backend ends', async () => {+ const core = fakeCore()+ const creationOf = vi.fn((harnessId: string) => harnessId === 'harness' ? 'super-0123456789abcdef' : null)+ const factory = vi.fn(() => ({ reserve: vi.fn(), observe: vi.fn(), creationOf, stop: vi.fn() }))+ let options: SuperTabHostOptions = {}+ const host = vi.fn((_core: unknown, _machine: string, given: SuperTabHostOptions) => {+ options = given+ return { machineId: 'machine-1', start: vi.fn(), stop: vi.fn() } as unknown as SuperTabHost+ })+ const service = superTabService(core, { reservations: factory, host })+ expect(await service.requests.super_tabs({ action: 'wake' }, owner)).toEqual({ ok: true })+ expect(options.startReceipt?.('harness')).toBe('super-0123456789abcdef')+ expect(options.startReceipt?.('another')).toBeNull()+})+it('lets a machine client prepare only a backend-verified terminal context', async () => {const core = fakeCore(), prepareNative = vi.fn(async () => ({ ok: true, inputContext: 'context_1234567890' }))const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start: vi.fn(), stop: vi.fn(), prepareNative }) as unknown as SuperTabHost })diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 2ff81d140..75b863f91 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -2,7 +2,7 @@ import { readCapabilities } from './capacity.js'import { existsSync } from 'node:fs'import { createHash } from 'node:crypto'import type { CoreApi, ServiceRequests, SuperTabsPort } from '../core/api.js'-import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError } from './host.js'+import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError, type SuperTabHostOptions } from './host.js'import { within } from './wire.js'import { machineChoices } from '../lib/newCommand.js'import { START_REQUIREMENTS } from './capacity.js'@@ -90,7 +90,7 @@ function markAnswered(page: unknown, later: unknown[], agentId: string): unknownexport interface SuperTabServiceOptions {prepareContribution?: typeof prepareContributioncapacity?: typeof readCapabilities- host?: (core: CoreApi, machineId: string) => SuperTabHost+ host?: (core: CoreApi, machineId: string, options: SuperTabHostOptions) => SuperTabHostreservations?: (core: CoreApi, machineId: string) => ReservationBook/** The Swarm cards' reader (superTabs/cards.ts), for a spec. */cards?: (core: CoreApi, machineId: string) => SwarmCards@@ -108,7 +108,8 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =const wake = () => {const machine = core.daemon.machineId()if (host?.machineId !== machine) { host?.stop(); host = null }- host ??= (options.host ?? ((api, id) => new SuperTabHost(api, id)))(core, machine)+ host ??= (options.host ?? ((api, id, given) => new SuperTabHost(api, id, given)))(core, machine,+ { startReceipt: harnessId => reservations().creationOf(harnessId) })host.start()return host}