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
Adopt Swarm role skills when older sessions restart (#1539)
0xken150eb60d6ab36f
diff --git a/cli/e2e/swarmLegacySkills.e2e.ts b/cli/e2e/swarmLegacySkills.e2e.tsnew file mode 100644index 000000000..8e209eabb--- /dev/null+++ b/cli/e2e/swarmLegacySkills.e2e.ts@@ -0,0 +1,77 @@+/** Old sessions adopt skills only through current Swarm membership, on their execution machine. */+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'+import { retainContributions } from '../src/superTabs/retention.js'++const ME: FakeMachine = { machineId: 'c9'.repeat(16), computerId: 'legacy-sw-test', name: 'Fixture', token: 'legacy-sw-token' }+let daemon: IsolatedDaemon | undefined, relay: FakeBackend | undefined, client: LocalClient | undefined+afterEach(async () => { client?.close(); await daemon?.close(); await relay?.close(); client = undefined; daemon = undefined; relay = undefined })++it('old Lead and worker restarts and stopped resume gain only their skill; personal and removed sessions gain none', async () => {+ const b = await FakeBackend.start(); relay = b; b.addMachine(ME)+ const d = await IsolatedDaemon.create({ env: { BACKEND_WS_URL: b.wsUrl, WEB_URL: b.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,+ ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential' } }); daemon = d+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token, autonomousEnv: 'prod', computerId: ME.computerId,+ machineId: ME.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e' }), { mode: 0o600 })+ onTestFailed(() => console.log(d.log().split('\n').slice(-120).join('\n')))+ const agents: Array<Record<string, any>> = [], groups: Array<Record<string, any>> = []+ b.superTabs = async (_method, raw) => {+ const path = new URL(raw, b.httpUrl).pathname+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: agents.map(agent => ({ tabId: 'tab', agent, observers: [] })) }+ if (path === '/api/super-tabs/tab') return { data: { state: { agents: agents.filter(a => a.id !== 'removed'), conversations: groups } } }+ return { data: [] }+ }+ await d.start(); const c = await LocalClient.connect(d, { machineId: ME.machineId }); client = c+ const cwd = join(d.projectsDir, 'legacy'); mkdirSync(cwd)+ writeFileSync(join(cwd, 'AGENTS.md'), 'Project rules stay here\n')+ const argv = (): Array<{ engine: string; args: string[] }> => {+ try { return readFileSync(join(d.root, 'launch-argv'), 'utf8').trim().split('\n').map(line => JSON.parse(line)) } catch { return [] }+ }+ const saved = (id: string) => JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')).find((row: Record<string, any>) => row.agentId === id)+ const ids: Record<string, string> = {}, modes: Record<string, unknown> = {}+ for (const [name, engine] of [['lead', 'claude'], ['worker', 'codex'], ['personal', 'claude'], ['removed', 'codex'], ['resumed', 'claude']]) {+ const created = await c.request('agent_create', { engine, cwd, bypassPermission: true, prompt: 'hello' }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined(); ids[name!] = created.agent.id+ await until('old engine to bind', async () => {+ const listed = await c.request('agents_list', {})+ return listed.agents?.some((row: Record<string, any>) => row.id === created.agent.id && row.sessionId) || null+ }, 30_000)+ expect(saved(created.agent.id).swarmSkill).toBeUndefined()+ modes[name!] = saved(created.agent.id).permissionMode+ if (name !== 'personal') agents.push({ id: name, harnessId: created.agent.id, machineId: ME.machineId })+ }+ groups.push({ leadId: 'lead', agentIds: ['lead', 'worker', 'removed', 'resumed'], archived: false })+ retainContributions(d.dataDir, ME.machineId, agents.map(agent => ({ tabId: 'tab', agent })))+ for (const [name, engine, role] of [['lead', 'claude', 'lead'], ['worker', 'codex', 'dev'], ['personal', 'claude', null], ['removed', 'codex', null]] as const) {+ const before = argv().length+ const reply = await c.request('agent_restart', { agentId: ids[name] }, 90_000)+ expect(reply.error, JSON.stringify(reply)).toBeUndefined()+ expect(saved(ids[name]!).permissionMode).toBe(modes[name])+ const launch = await until('restarted engine argv', () => argv().slice(before).find(row => row.engine === engine) ?? null, 30_000)+ if (role) {+ expect(launch.args.join(' ')).toContain(`swarm-${role}/SKILL.md`)+ expect(saved(ids[name]!).swarmSkill).toEqual({ role, key: ids[name] })+ } else {+ expect(launch.args.join(' ')).not.toContain('/swarm/skills/')+ expect(saved(ids[name]!).swarmSkill).toBeUndefined()+ }+ }+ expect((await c.request('agent_delete', { agentId: ids.resumed }, 90_000)).error).toBeUndefined()+ const before = argv().length+ const resumed = await c.request('agent_resume', { agentId: ids.resumed }, 90_000)+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()+ const launch = await until('resumed worker argv', () => argv().slice(before).find(row => row.engine === 'claude') ?? null, 30_000)+ expect(launch.args.join(' ')).toContain('swarm-dev/SKILL.md')+ expect(saved(ids.resumed!).swarmSkill).toEqual({ role: 'dev', key: ids.resumed })+ expect(readFileSync(join(cwd, '.harness', '.gitignore'), 'utf8')).toContain('runtime/')+ expect(readFileSync(join(cwd, 'AGENTS.md'), 'utf8')).toBe('Project rules stay here\n')+ expect(readdirSync(join(cwd, '.harness', 'runtime'))).toHaveLength(3)+ for (const home of [d.engineConfig.codexHome, join(d.root, 'home', '.claude')]) {+ expect(readdirSync(home, { recursive: true }).map(String).some(file => file.includes('swarm-lead') || file.includes('swarm-dev'))).toBe(false)+ }+})diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex 326b737ac..33b78cbfa 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -17,6 +17,7 @@ import type { ResumeAgent } from './launches.js'import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'export interface LifecycleDeps {+ adoptSwarmSkill?: ResumeAgentServiceDeps['adoptSwarmSkill']settlePane?: StopAgentServiceDeps['settlePane']cancelExternal?: StopAgentServiceDeps['cancelExternal']registry: typeof registry@@ -61,7 +62,7 @@ export interface LifecycleDeps {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, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer,+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, adoptSwarmSkill, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer,}: LifecycleDeps) {/*** Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live@@ -97,7 +98,7 @@ export function createAgentLifecycle({const resume = createResumeAgentService({registry, stoppedAgents, createBackend, noBackendCode, backendFor, restartJobs, stopJobs, pinnedControls,- retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,+ retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume, adoptSwarmSkill,refreshGridWebSearch, clearDeleted, attachDsh, attachSession, relaunchMarks,})const resumeAgent: ResumeAgent = (id, permissionMode) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guestdiff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.tsindex a9eb81d4b..82bdbec9f 100644--- a/cli/src/core/agents/restart.spec.ts+++ b/cli/src/core/agents/restart.spec.ts@@ -10,6 +10,8 @@ import { terminalRouteKey } from '../../lib/terminalRuntime.js'import { processLaunchArgs } from '../../lib/processTable.js'import { workspaceMissing } from '../../lib/workspaceCheck.js'import { createAgentRestarter, type RestartDeps } from './restart.js'+import { createLaunchAuthority } from './launchAuthority.js'+import { createSwarmSkillAdoption } from './swarmSkills.js'import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => undefined) }))@@ -79,6 +81,33 @@ describe('restarting an agent', () => {beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('adopts an old role before native inspection and relaunch', async () => {+ const skill = { role: 'lead' as const, key: 'a1' }+ const run = setup(agent(), { adoptSwarmSkill: async row => ({ ...row, swarmSkill: skill }) })+ expect(await run.restart('a1')).toMatchObject({ ok: true })+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.objectContaining({ swarmSkill: skill }),+ expect.objectContaining({ swarmSkill: skill }), expect.any(Function), undefined)+ })++ it('does not restart if role adoption loses the session binding', async () => {+ const run = setup(agent(), { adoptSwarmSkill: async () => null })+ expect(await run.restart('a1')).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()+ expect(restartAgent).not.toHaveBeenCalled()+ })++ it('restarts when an unrelated registry field changes during a no-role lookup', async () => {+ const session = agent({ registeredAt: 1 })+ const authority = createLaunchAuthority({ byAgent: () => session, revision: () => 0, cancelled: () => false })+ const adoptSwarmSkill = createSwarmSkillAdoption({+ authority, save: vi.fn(), candidate: () => true,+ role: async () => { session.dsh = 'changed-during-lookup'; return null },+ })+ const run = setup(session, { adoptSwarmSkill })+ expect(await run.restart('a1')).toMatchObject({ ok: true })+ expect(restartAgent).toHaveBeenCalledOnce()+ })+it.each(['starting', 'held'] as const)('does not replace an unbound native %s launch with a generic fresh restart', async state => {const run = setup(agent({ sessionId: '', launch: state === 'starting' ? { state, nativeToken: 'original' }: { state, nativeToken: 'original', service: 'native', detail: 'Original request held' } }))diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex d77c465e3..3c19586a3 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -3,6 +3,7 @@** Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).*/+import type { AdoptSwarmSkill } from './swarmSkills.js'import { homedir } from 'node:os'import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'import { engineBin, enginePathOverride } from '../../lib/engineBin.js'@@ -48,6 +49,7 @@ async function engineInstalled(engine: AgentEngine): Promise<boolean | null> {type RestartAgentHandler = RestartAgentexport interface RestartDeps {+ adoptSwarmSkill?: AdoptSwarmSkillnative?: LaunchOverridesDeps['native']restartJobs: PaneSwap['restartJobs']registry: typeof registry@@ -75,7 +77,7 @@ export interface RestartDeps {}export function createAgentRestarter({- native: inspectNative,+ native: inspectNative, adoptSwarmSkill,restartJobs, registry, purgeBusy, stopJobs, pinnedControls, terminals, sameRestartTarget, agentReconciler,terminalHintMachineName, announceSession, refreshGridAssignment, relaunchOverrides, downgradedPermission, refreshGridWebSearch,liveBypassPermission, paneSwapDeps, restartHeld,@@ -101,7 +103,7 @@ export function createAgentRestarter({*/const restartAgentHandler: RestartAgentHandler = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }- const session = registry.resolve(agentId)+ let session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }if (session.guest) return GUEST_HARNESS_REFUSALif (!session.sessionId && (session.launch?.state === 'held' || session.launch?.state === 'starting') && session.launch.nativeToken) {@@ -155,6 +157,12 @@ export function createAgentRestarter({}if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }+ // Fill a missing Swarm role before native inspection and launch preparation.+ if (adoptSwarmSkill) {+ const adopted = await adoptSwarmSkill(session, current)+ if (!adopted || !current()) return changed+ session = adopted+ }// The relaunch runs the engine's command again, so an engine uninstalled since the agent started// cannot come back. Asked anyway, the swap killed the working agent and gave up twenty seconds// later with "did not come back up" (updates.e2e.ts, round 24). Asked here, before anything isdiff --git a/cli/src/core/agents/swarmSkills.spec.ts b/cli/src/core/agents/swarmSkills.spec.tsnew file mode 100644index 000000000..67dca3e7f--- /dev/null+++ b/cli/src/core/agents/swarmSkills.spec.ts@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import { createLaunchAuthority } from './launchAuthority.js'+import { createSwarmSkillAdoption } from './swarmSkills.js'++const row = (over: Partial<RegisteredSession> = {}) => ({ agentId: 'old-session', engine: 'claude', sessionId: 'conversation',+ registeredAt: 1, cwd: '/project', runtimes: [], ...over }) as RegisteredSession++function setup(saved = row(), live: RegisteredSession | null = saved) {+ let current = true+ const role = vi.fn(async (): Promise<'lead' | 'dev' | null | undefined> => 'lead')+ const save = (id: string, skill: NonNullable<RegisteredSession['swarmSkill']>) => {+ if (!live || live.agentId !== id) return false+ live.swarmSkill = skill; return true+ }+ const authority = createLaunchAuthority({ byAgent: () => live ?? undefined, revision: () => 0, cancelled: () => !current })+ return { saved, role, adopt: createSwarmSkillAdoption({ role, authority, save, candidate: () => true }), cancel: () => { current = false },+ change: () => { if (live) live.cwd = '/replacement' }, current: () => current }+}++describe('old Swarm role adoption', () => {+ it.each(['claude', 'codex'] as const)('adopts each role for old %s sessions and persists it before launch', async engine => {+ for (const role of ['lead', 'dev'] as const) {+ const t = setup(row({ engine })); t.role.mockResolvedValue(role)+ expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role, key: 'old-session' } })+ expect(t.saved.swarmSkill).toEqual({ role, key: 'old-session' })+ }+ })+ it('carries metadata into a stopped resume without requiring a live registry row', async () => {+ const t = setup(row(), null)+ expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'lead', key: 'old-session' } })+ expect(t.saved.swarmSkill).toBeUndefined()+ })+ it.each([null, 'unavailable'] as const)('leaves a personal/removed/unreadable session untouched (%s)', async role => {+ const t = setup()+ if (role === null) t.role.mockResolvedValue(null)+ else t.role.mockRejectedValue(new Error('Offline'))+ expect(await t.adopt(t.saved, t.current)).toEqual(t.saved)+ expect(t.saved.swarmSkill).toBeUndefined()+ })+ it('does not wait for an offline backend when local membership excludes a personal session', async () => {+ const t = setup()+ t.role.mockImplementation(() => new Promise(() => {}))+ const adopt = createSwarmSkillAdoption({ role: t.role, authority: () => () => true, save: vi.fn(), candidate: () => false })+ const answer = await Promise.race([adopt(t.saved, t.current), new Promise(resolve => setTimeout(() => resolve('waiting'), 30))])+ expect(answer).toBe(t.saved)+ expect(t.role).not.toHaveBeenCalled()+ })+ it('does not call the backend when the local roster record is unreadable', async () => {+ const t = setup()+ const adopt = createSwarmSkillAdoption({ role: t.role, authority: () => () => true, save: vi.fn(), candidate: () => { throw new Error('Unreadable roster') } })+ expect(await adopt(t.saved, t.current)).toBe(t.saved)+ expect(t.role).not.toHaveBeenCalled()+ })+ it('remembers a confirmed no-role result across restarts', async () => {+ const t = setup()+ t.role.mockResolvedValue(null)+ await t.adopt(t.saved, t.current)+ await t.adopt(t.saved, t.current)+ expect(t.role).toHaveBeenCalledTimes(1)+ })+ it.each(['offline', 'unregistered'] as const)('retries an %s lookup and adopts the role when available', async unavailable => {+ const t = setup()+ if (unavailable === 'offline') t.role.mockRejectedValueOnce(new Error('Offline'))+ else t.role.mockResolvedValueOnce(undefined)+ t.role.mockResolvedValueOnce('dev')+ expect(await t.adopt(t.saved, t.current)).toBe(t.saved)+ expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'dev' } })+ expect(t.role).toHaveBeenCalledTimes(2)+ })+ it('can adopt after a local roster snapshot first excludes the session', async () => {+ const t = setup()+ let present = false+ const adopt = createSwarmSkillAdoption({ role: t.role, authority: () => () => true, save: vi.fn(), candidate: () => present })+ expect(await adopt(t.saved, t.current)).toBe(t.saved)+ present = true+ expect(await adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'lead' } })+ expect(t.role).toHaveBeenCalledOnce()+ })+ it('allows an unrelated live-row update while a no-role lookup runs', async () => {+ const t = setup()+ t.role.mockImplementation(async () => { t.change(); return null })+ expect(await t.adopt(t.saved, t.current)).toBe(t.saved)+ expect(t.saved.swarmSkill).toBeUndefined()+ })+ it.each([{ engine: 'opencode' }, { cwd: '' }, { guest: {} }, { swarmSkill: { role: 'dev', key: 'already-saved' } }] as Partial<RegisteredSession>[])+ ('does not consult the roster for ineligible or already-tagged sessions: %j', async over => {+ const t = setup(row(over))+ expect(await t.adopt(t.saved, t.current)).toEqual(t.saved)+ expect(t.role).not.toHaveBeenCalled()+ })+ it.each(['cancel', 'rebind'] as const)('does not adopt after %s while the roster is being read', async change => {+ const t = setup()+ t.role.mockImplementation(async () => { if (change === 'cancel') t.cancel(); else t.change(); return 'lead' })+ expect(await t.adopt(t.saved, t.current)).toBeNull()+ expect(t.saved.swarmSkill).toBeUndefined()+ })+ it('does not read or write for an already-cancelled operation', async () => {+ const t = setup(); t.cancel()+ expect(await t.adopt(t.saved, t.current)).toBeNull()+ expect(t.role).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/agents/swarmSkills.ts b/cli/src/core/agents/swarmSkills.tsnew file mode 100644index 000000000..083396ac0--- /dev/null+++ b/cli/src/core/agents/swarmSkills.ts@@ -0,0 +1,37 @@+/** Older Swarm sessions predate role metadata. Adopt only at restart/resume, from current membership,+ * before native launch authority is captured; changing the live row later would revoke that launch. */+import type { RegisteredSession, registry } from '../../lib/registry.js'+import type { SwarmRole } from '../../lib/swarmSkills.js'++export type AdoptSwarmSkill = (session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>++export function createSwarmSkillAdoption(deps: {+ role(harnessId: string): Promise<SwarmRole | null | undefined>+ candidate(harnessId: string): boolean+ authority(agentId: string): () => boolean+ save: typeof registry.setSwarmSkill+}): AdoptSwarmSkill {+ const noRole = new Set<string>()+ return async (session, current) => {+ if (!current()) return null+ if (session.swarmSkill || session.guest || !session.cwd || (session.engine !== 'claude' && session.engine !== 'codex')) return session+ if (noRole.has(session.agentId)) return session+ // The host's last confirmed roster is only a cheap candidate filter; the live backend remains authoritative.+ try { if (!deps.candidate(session.agentId)) return session } catch { return session }+ const owns = deps.authority(session.agentId)+ const saved = structuredClone(session)+ let role: SwarmRole | null | undefined+ try { role = await deps.role(saved.agentId) } catch { /* An unreadable roster grants no skill. */ }+ if (!current()) return null+ if (role === undefined) return session+ if (role === null) {+ noRole.add(saved.agentId)+ return session+ }+ if (!owns()) return null+ const swarmSkill = { role, key: saved.agentId }+ // A stopped row is not live yet: resumePendingAgent persists the returned copy when dispatch allocates its pane.+ deps.save(saved.agentId, swarmSkill)+ return { ...saved, swarmSkill }+ }+}diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex cb1b01db1..897ecbfb5 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -647,8 +647,8 @@ export const MEMORY_REQUESTS = ['memory_snapshot', 'memory_about_put', 'memory_d* the client that asks, which acts on it. */export const ROUTER_REQUESTS = ['route_decide'] as constexport const SUPER_TAB_REQUESTS = ['super_tabs'] as const-export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void }-export const SUPER_TAB_FALLBACKS: PortFallbacks<SuperTabsPort> = { connected: undefined, disconnected: undefined, stop: undefined }+export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void; swarmRole(harnessId: string): Promise<'lead' | 'dev' | null | undefined> }+export const SUPER_TAB_FALLBACKS: PortFallbacks<SuperTabsPort> = { connected: undefined, disconnected: undefined, stop: undefined, swarmRole: later(undefined) }/** The project and folder readers (services/projects.ts). */export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex e2eb03848..df4981857 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1,3 +1,6 @@+import { createSwarmSkillAdoption } from './agents/swarmSkills.js'+import { swarmRoleThrough } from './superTabSkills.js'+import { retainedHarnesses } from '../superTabs/retention.js'import { createGridAssignments } from './agents/gridAssignments.js'import { createQuestionControls } from './engines/questionControls.js'import { masterRunsEngineQuestionControl } from '../harnessd/services.js'@@ -2292,6 +2295,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {// What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restore// pass below, which calls these for every pane it rebuilds.const launchAuthority = createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: restoreRevision, cancelled: id => launchCancelled(id) })+ const adoptSwarmSkill = createSwarmSkillAdoption({+ authority: launchAuthority,+ candidate: id => retainedHarnesses(env.ADAPTER_DATA_DIR).has(id),+ role: outOfProcess.has('superTabs')+ ? swarmRoleThrough((type, payload) => serviceLinks.call('superTabs', type, payload, 3500))+ : id => ports.superTabs?.swarmRole(id) ?? Promise.resolve(undefined),+ save: (id, skill) => registry.setSwarmSkill(id, skill),+ })const launchHelpers = createLaunchHelpers({authority: launchAuthority,prepareApiTools,@@ -2657,6 +2668,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Stopping, purging and resuming an agent (core/agents/lifecycle.ts).const lifecycle = createAgentLifecycle({+ adoptSwarmSkill,settlePane: restorePanes.settle,cancelExternal: externalResumes.cancel,registry,@@ -2725,6 +2737,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Restarting an agent in its own pane (core/agents/restart.ts).const restartAgent = createAgentRestarter({+ adoptSwarmSkill,native: prepareNativeLaunch,restartJobs,registry,diff --git a/cli/src/core/superTabSkills.spec.ts b/cli/src/core/superTabSkills.spec.tsnew file mode 100644index 000000000..10e31dc8e--- /dev/null+++ b/cli/src/core/superTabSkills.spec.ts@@ -0,0 +1,13 @@+import { expect, it, vi } from 'vitest'+import { swarmRoleThrough } from './superTabSkills.js'++it('reads only validated role answers through the Super Tab process', async () => {+ const answers = [{ ok: true, role: 'lead' }, { ok: true, role: 'dev' }, { ok: true, role: null }, { role: 'lead' }, { ok: true, role: 'owner' }, { error: 'SERVICE_UNAVAILABLE' }]+ const call = vi.fn(async () => answers.shift()!)+ const read = swarmRoleThrough(call)+ expect(await read('native')).toBe('lead')+ expect(await read('native')).toBe('dev')+ expect(await read('native')).toBeNull()+ for (let i = 0; i < 3; i++) expect(await read('native')).toBeUndefined()+ expect(call).toHaveBeenCalledWith('super_tabs', { action: 'swarmRole', harnessId: 'native' })+})diff --git a/cli/src/core/superTabSkills.ts b/cli/src/core/superTabSkills.tsnew file mode 100644index 000000000..0ac390ace--- /dev/null+++ b/cli/src/core/superTabSkills.ts@@ -0,0 +1,11 @@+/** The same role lookup in a separate Super Tab process. Missing/older services grant no skill. */+import type { SwarmRole } from '../lib/swarmSkills.js'++export function swarmRoleThrough(call: (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>) {+ return async (harnessId: string): Promise<SwarmRole | null | undefined> => {+ const answer = await call('super_tabs', { action: 'swarmRole', harnessId })+ if (answer.ok !== true) return undefined+ if (answer.role === null) return null+ return answer.role === 'lead' || answer.role === 'dev' ? answer.role : undefined+ }+}diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex a93a419d5..a2c5dab2e 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1835,6 +1835,19 @@ describe('registry across a reboot and pane loss', () => {expect(bound?.entry.subscriptionModel).toBe('opus')})+ it('fills an old supported session role once and persists it through reload', async () => {+ const { registry } = await loadRegistryModule(); registry.load()+ const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%21' }] })!+ const skill = { role: 'lead' as const, key: pending.agentId }+ expect(registry.setSwarmSkill('missing', skill)).toBe(false)+ expect(registry.setSwarmSkill(pending.agentId, skill)).toBe(true)+ expect(registry.setSwarmSkill(pending.agentId, { role: 'dev', key: 'replacement' })).toBe(false)+ const { registry: reloaded } = await loadRegistryModule(); reloaded.load()+ expect(reloaded.byAgent(pending.agentId)?.swarmSkill).toEqual(skill)+ const other = reloaded.openPendingAgent({ engine: 'opencode', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%22' }] })!+ expect(reloaded.setSwarmSkill(other.agentId, skill)).toBe(false)+ })+it('preserves Swarm role and runtime key across hooks and reload', async () => {const { registry } = await loadRegistryModule()registry.load()diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex b23b5034c..767ee77dc 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -2462,6 +2462,16 @@ class Registry {return true}+ /** Older Swarm members adopt a role at restart, once; later roster reads cannot replace a saved role. */+ setSwarmSkill(agentId: string, skill: SwarmSkill): boolean {+ const session = this.agents.get(agentId)+ if (!session || session.swarmSkill || (session.engine !== 'claude' && session.engine !== 'codex')) return false+ session.swarmSkill = { ...skill }+ session.touchedAt = Date.now()+ this.save()+ return true+ }+/** Fill in the DSH a row did not know (discovery read `HARNESS_DSH` off the live process). Never* replaces one it already has — the harness is chosen once, at creation. */setDsh(agentId: string, dsh: string): boolean {diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex ac117dea7..fe7af69b2 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -149,6 +149,20 @@ describe('production resume handler', () => {expect(create).toHaveBeenCalledOnce()})+ it('persists an adopted old worker role in the resumed registry row', async () => {+ const swarmSkill = { role: 'dev' as const, key: saved.agentId }+ deps.adoptSwarmSkill = async row => ({ ...row, swarmSkill })+ expect(await start()).toMatchObject({ ok: true, session: { swarmSkill } })+ registry.load()+ expect(registry.byAgent(saved.agentId)?.swarmSkill).toEqual(swarmSkill)+ })++ it('does not resume a session that changed during role adoption', async () => {+ deps.adoptSwarmSkill = async () => null+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(create).not.toHaveBeenCalled()+ })+it.each(['auto', 'ask'])('resumes the same conversation with an explicit %s permission choice', async permissionMode => {rewrite({ engine: 'opencode', permissionMode: permissionMode === 'auto' ? 'ask' : 'auto' })vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true, overrides: {diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex d165a0e2d..bc87ee8e6 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -1,4 +1,5 @@/** Exact-resume lifecycle shared by the daemon and its isolated acceptance tests. */+import type { AdoptSwarmSkill } from '../core/agents/swarmSkills.js'import { transcriptSize, type RelaunchMarks } from '../core/transcripts/relaunch.js'import { isTerminalEngine } from '../engines/types.js'import { installedDsh } from '../dsh/installed.js'@@ -25,6 +26,7 @@ import type { TerminalRuntimeRef } from './terminalTypes.js'import { harnessPermissionEnvironment } from './harnessDefaults.js'export interface ResumeAgentServiceDeps {+ adoptSwarmSkill?: AdoptSwarmSkillregistry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch' | 'updateProcessIdentity'>stoppedAgents: StoppedAgentStore/** Where a resumed harness's new pane is made (main.ts `createBackend`); null with no backend ready. */@@ -53,7 +55,7 @@ export interface ResumeAgentServiceDeps {export function createResumeAgentService(deps: ResumeAgentServiceDeps) {const { registry, stoppedAgents, createBackend, noBackendCode = 'TMUX_UNAVAILABLE', backendFor, restartJobs, stopJobs, pinnedControls,- retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,+ retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume, adoptSwarmSkill,refreshGridWebSearch, clearDeleted, attachDsh, attachSession, relaunchMarks } = depsconst resumeConversations = new Set<string>()/** Same short form every other `[…]` line in the daemon logs uses. */@@ -221,6 +223,11 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {if (resumeSessionId && engineKeepsTranscriptFile(saved.engine) && !saved.transcriptPath) {return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'The saved conversation file is unavailable. Start a new conversation separately.' }}+ if (adoptSwarmSkill) {+ const adopted = await adoptSwarmSkill(saved, current)+ if (!adopted || !current()) return resumeChanged+ saved = adopted+ }const sourceEvidence = () => resumeSessionId && engineKeepsTranscriptFile(saved.engine)? controlTranscriptEvidence(saved.engine, resumeSessionId, saved.transcriptPath!, saved.codexHome ?? undefined, saved.cwd) : undefined// Match the registry's globally unique conversation index, including aliases/profiles.diff --git a/cli/src/services/superTabsProcess.spec.ts b/cli/src/services/superTabsProcess.spec.tsindex df25f92e5..3198a42b7 100644--- a/cli/src/services/superTabsProcess.spec.ts+++ b/cli/src/services/superTabsProcess.spec.ts@@ -9,7 +9,7 @@ const flush = () => new Promise(resolve => setTimeout(resolve, 0))function setup(withPort = true) {let api!: CoreApi, wire!: ServiceProcessOptions- const port = { connected: vi.fn(), disconnected: vi.fn(), stop: vi.fn() }+ const port = { connected: vi.fn(), disconnected: vi.fn(), stop: vi.fn(), swarmRole: vi.fn(async () => null) }const stopped = vi.fn()const process = runSuperTabsService({ dataDir: '/not-a-real-data-dir', socketPath: '/not-a-real-socket', machineId: 'm', token: 't',run: options => { wire = options; return { stop: stopped } },diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 032b22ec5..059d4ec43 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -4,7 +4,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { CoreApi, TurnDelivery } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'-import { backend, hostJournalFile, SuperTabHost } from './host.js'+import { backend, swarmRoleFor, hostJournalFile, SuperTabHost } from './host.js'import { retainedHarnesses, retentionFile } from './retention.js'const roots: string[] = []@@ -47,6 +47,40 @@ function setup(messageFields: Record<string, unknown> = {}) {return { core, call, open, event, receipts, holds, log, wait: (ms: number) => { clock += ms }, saved, dir, remove: () => { removed = true }, revoke: (value = true) => { revoked = value }, foreignClaim: () => { claimId = 'another-process' } }}+describe('current Swarm role lookup', () => {+ it.each(['lead', 'member', 'assigned'] as const)('derives an old %s from current groups on its machine', async kind => {+ const t = setup()+ const agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }+ const group = { leadId: kind === 'lead' ? 'agent' : 'other', agentIds: kind === 'member' ? ['agent'] : [],+ assignment: kind === 'assigned' ? { agentId: 'agent', execution: { machineId: 'machine-1' } } : null }+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:+ path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations: [group] } } } }))+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBe(kind === 'lead' ? 'lead' : 'dev')+ expect(await swarmRoleFor(t.core, 'machine-1', 'personal')).toBeNull()+ })+ it.each(['removed-roster', 'foreign', 'removed-state', 'archived', 'released', 'none', 'malformed'] as const)+ ('never adopts a session whose membership is %s', async kind => {+ const t = setup()+ const agent = { id: 'agent', harnessId: 'harness', machineId: kind === 'foreign' ? 'other' : 'machine-1' }+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/')+ ? kind === 'malformed' ? {} : kind === 'removed-roster' ? [] : [{ tabId: 'tab', agent, stopRequested: kind === 'released' }]+ : { state: { agents: kind === 'removed-state' ? [] : [agent], conversations:+ kind === 'none' ? [] : [{ leadId: 'agent', agentIds: ['agent'], archived: kind === 'archived' }] } } } }))+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()+ })+ it('prefers Lead when a session also works in another group and never reuses a stale roster', async () => {+ const t = setup(), agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }+ let present = true+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/')+ ? present ? [{ tabId: 'tab', agent }] : []+ : { state: { agents: [agent], conversations: [{ agentIds: ['agent'] }, { leadId: 'agent' }] } } } }))+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBe('lead')+ present = false+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()+ })+})+describe('Super Tab native delivery handoff', () => {it('names all five task parts in the worker delivery header', async () => {const t = setup()diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex d9d5964fc..96f0641e8 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -18,6 +18,7 @@ export class SuperTabHostError extends Error {}export { identifier, object } from './wire.js'import { ENDED_WORK, identifier, object } from './wire.js'+import type { SwarmRole } from '../lib/swarmSkills.js'/** The core signs each request. Neither the service nor its journal holds an account credential. */export async function backend(core: CoreApi, method: string, path: string, body?: unknown): Promise<unknown> {@@ -30,6 +31,31 @@ export async function backend(core: CoreApi, method: string, path: string, body?return reply.body.data}+/** Restart/resume can include stopped harnesses, so the live process list is not membership proof.+ * Re-read the exact machine roster and its groups; a removed contribution must never adopt a skill. */+export async function swarmRoleFor(core: CoreApi, machineId: string, harnessId: string): Promise<SwarmRole | null> {+ if (!identifier(machineId) || !identifier(harnessId)) return null+ const rows = await backend(core, 'GET', `/api/super-tabs/hosts/${machineId}`)+ if (!Array.isArray(rows)) return null+ const roles = await Promise.all(rows.map(object).filter(row => {+ const agent = object(row.agent)+ return identifier(row.tabId) && identifier(agent.id) && agent.machineId === machineId+ && agent.harnessId === harnessId && row.stopRequested !== true+ }).map(async row => {+ const target = object(row.agent)+ const answer = object(await backend(core, 'GET', `/api/super-tabs/${row.tabId}?asAgentId=${target.id}`))+ const state = object(answer.state)+ const agent = Array.isArray(state.agents) && state.agents.map(object).find(agent => agent.id === target.id+ && agent.harnessId === harnessId && agent.machineId === machineId && agent.workDecision !== 'stop')+ if (!agent) return null+ const groups = (Array.isArray(state.conversations) ? state.conversations.map(object) : []).filter(group => group.archived !== true)+ if (groups.some(group => group.leadId === target.id)) return 'lead'+ return groups.some(group => Array.isArray(group.agentIds) && group.agentIds.includes(target.id)+ || object(group.assignment).agentId === target.id && object(object(group.assignment).execution).machineId === machineId) ? 'dev' : null+ }))+ return roles.includes('lead') ? 'lead' : roles.includes('dev') ? 'dev' : null+}+interface Entry {tabId: stringagentId: stringdiff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 70eaed11d..f039fafec 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -20,6 +20,40 @@ function setup(options: { jev?: () => JevDecide; prepareContribution?: typeof imconst service = superTabService(core, { host: () => ({ machineId: 'machine-1', start, stop }) as unknown as SuperTabHost, ...options })return { ...service, call, core, agent, agentId, start, stop, ask: service.requests.super_tabs }}+describe('restart role lookup through the service', () => {+ it('does not start the delivery loop when a personal session restarts', async () => {+ const host = vi.fn(() => ({ machineId: 'machine-1', start: vi.fn(), stop: vi.fn(), swarmRole: async () => null }) as never)+ const core = fakeCore({ account: { backend: vi.fn(async () => ({ status: 200, body: { data: [] } })) } })+ const service = superTabService(core, { host })+ expect(await service.port.swarmRole('personal')).toBeNull()+ expect(host).not.toHaveBeenCalled()+ service.port.stop()+ })+ it('answers the same current role in inline and process requests, for the owner only', async () => {+ const agent = { id: 'agent', machineId: 'machine-1', harnessId: 'old-native' }+ const call = vi.fn<CoreApi['account']['backend']>(async (_method, path) => ({ status: 200, body: { data:+ path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations: [{ leadId: 'agent' }] } } } }))+ const service = superTabService(fakeCore({ account: { backend: call } }))+ expect(await service.port.swarmRole('old-native')).toBe('lead')+ expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'old-native' }, owner)).toEqual({ ok: true, role: 'lead' })+ expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'old-native' }, visitor)).toMatchObject({ error: 'OWNER_REQUIRED' })+ call.mockRejectedValueOnce(new Error('Offline'))+ expect(await service.port.swarmRole('old-native')).toBeUndefined()+ service.port.stop()+ })+ it('bounds an unavailable backend lookup without delaying restart indefinitely', async () => {+ vi.useFakeTimers()+ try {+ const core = fakeCore({ account: { backend: () => new Promise(() => {}) } })+ const service = superTabService(core)+ const read = service.port.swarmRole('old-native')+ await vi.advanceTimersByTimeAsync(3000)+ expect(await read).toBeUndefined()+ service.port.stop()+ } finally { vi.useRealTimers() }+ })+})+describe('five-part task commands', () => {const task = { goal: 'Save edits', changes: 'Persist drafts', constraints: 'No dependencies', owns: ['cli/src/superTabs'] }const brief = 'Goal:\nSave edits\n\nChanges:\nPersist drafts\n\nConstraints:\nNo dependencies\n\nOwns:\n- cli/src/superTabs'diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 15a39dd8f..898a418f4 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, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError } from './host.js'+import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError } from './host.js'import { within } from './wire.js'import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'import { machineChoices } from '../lib/newCommand.js'@@ -109,6 +109,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =},disconnected: disconnect,stop: disconnect,+ swarmRole: async (harnessId: string) => (await within(swarmRoleFor(core, core.daemon.machineId(), harnessId).then(role => ({ role }))))?.role,}const requests: ServiceRequests = {super_tabs: async (payload, asker, closed) => {@@ -127,6 +128,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =return await wake().prepareNative(payload.tabId, payload.contextId, payload.action === 'renewNative', closed)}if (!asker.owner || (!asker.local && asker.accountOwner !== true)) return { error: 'OWNER_REQUIRED' }+ if (payload.action === 'swarmRole') return { ok: true, role: await port.swarmRole(String(payload.harnessId ?? '')) }if (payload.action === 'prepareContribution') return preparations.read(payload)if (payload.action === 'backend') {const { method, path } = payloaddiff --git a/docs/plans/2026-10-22-swarm-legacy-role-skills.md b/docs/plans/2026-10-22-swarm-legacy-role-skills.mdnew file mode 100644index 000000000..cd867246e--- /dev/null+++ b/docs/plans/2026-10-22-swarm-legacy-role-skills.md@@ -0,0 +1,33 @@+# Adopt role skills when old Swarm sessions restart++Approved by the project Lead after #1533 merged. The owner reversed the earlier fresh-launch-only scope.++Goal: an existing Claude Code or Codex Swarm session without stored role metadata gains the correct built-in skill when restarted or resumed on its own machine. Current group Leads receive Lead; assigned/member workers receive DEV. A personal session, missing roster entry or unsupported engine receives nothing. Existing role metadata stays unchanged.++Implementation decisions: confirm the exact harness in a fresh machine-scoped host roster, then read its current tab state to derive the group role. Both reads use the existing account backend and a bounded Super Tab service lookup; no backend changes or stale roster cache. A removed entry in either read cannot be adopted. Lead takes precedence if the same session leads one group and works in another. Archived groups do not grant a role. Adopt metadata before native preparation while checking cancellation/binding authority; live rows persist it, and stopped rows carry it into their resumed registry entry. Reuse prepareSwarmSkill through the existing relaunch path so generated files remain session-workspace-only and git-ignored.++1. Add failing roster/service tests for Lead, member/assigned worker, personal/removed/foreign sessions, stopped service and unavailable backend. Add lifecycle regressions for adoption before restart/resume and persistence.+2. Implement a guarded, bounded service lookup, core wiring and role fill-in; reuse fresh-launch materialization. Preserve launch authority, permission modes, Store harnesses and native launch recovery.+3. Verify affected CLI tests, typecheck, Super Tab routing coverage and full core coverage. Exercise old Lead/worker restarts and personal-session exclusion through the real daemon with fake engines, loopback backend, throwaway homes and private tmux. No tests use the live daemon, personal engine homes or real tmux.+4. Review the final diff, push one branch and open a draft PR with exact evidence and unverified limits. Do not mark ready, merge or release.++Owned code: CLI Super Tab host/service and process adapter, core agent restart/lifecycle and their wiring, registry fill-in, isolated tests and this plan. No Desktop or backend behavior changes.++Validation record (2026-10-22, macOS arm64, Node 24.3.0):+- New lifecycle regression tests failed before implementation: four adoption, cancellation and persistence checks. A separate regression showed that waking the host for a personal restart would start its delivery loop; the final lookup is a one-shot roster and tab-state read with no host wake.+- `npm run typecheck` passed.+- Affected CLI unit tests passed: 26 files, 669 tests.+- `npm run test:super-tabs` passed: 111 tests and 100% statement, branch, function and line coverage.+- `npm run test:core -- --maxWorkers=3` passed: 201 files, 2,976 tests and 100% coverage in all four measures.+- The bundled isolated daemon acceptance test passed. It restarted old Claude Code Lead and Codex worker sessions, resumed a stopped Claude Code worker, excluded a personal session and a removed roster entry, and verified stored roles, actual skill launch arguments, unchanged permission modes and workspace-only generated files. It used fake engines, a loopback backend, throwaway homes and private tmux; real engine execution and a physical second machine were not exercised.+- `git diff --check` passed. No Desktop or backend files changed; their tests are outside the changed input scope.++Review correction (2026-10-22): the host's durable retained-roster file now screens candidate harness IDs locally before the bounded backend lookup. A missing local entry is not cached, so a later confirmed roster can still make the session eligible. A completed lookup with no role (including an unreadable backend) is cached per session for the current daemon, avoiding repeated waits; a daemon restart permits another check. No-role lookups return the current session without requiring the full-row write authority, while a positive role still requires that authority before persistence. Four new regression cases failed before the correction, including an offline personal restart and a row change during a no-role restart; the affected tests pass after it. The acceptance fixture now records the same local roster the real host does.++Review validation: typecheck passed; affected CLI suite passed (26 files, 669 tests); isolated daemon acceptance passed (1 test); full core gate passed (201 files, 2,983 tests, 100% statement, branch, function and line coverage); `git diff --check` passed. These native CLI checks ran with macOS boot and process access. Earlier sandboxed attempts could not read the boot marker and are not counted as evidence.++Final review correction: an unavailable role lookup (timeout, backend error, missing port or invalid process reply) is now distinct from a confirmed no-role response. Only the latter enters the daemon's negative cache, so a worker can retry after the service recovers. Five focused tests failed before this distinction; after it, 212 focused tests, typecheck and the 201-file/2,984-test core gate passed, with 100% coverage in all four measures. The restart comment and file header imports were also restored to their proper positions.++Final integration on main after #1542: typecheck passed; the affected CLI suite passed (26 files, 672 tests); the core gate passed (201 files, 2,986 tests and 100% coverage in all four measures); the isolated daemon acceptance test passed (1 test); `git diff --check` passed. The rebase was clean. Main's concurrent CLI changes add process API and reservation cleanup fields without changing this role-lookup path.++Final rebase after #1543, #1546 and #1547: the host import conflict was resolved with both the new ended-work statuses and Swarm role lookup. Typecheck passed; the combined Super Tab host/service/process suite passed (22 files, 429 tests); the routing gate passed (111 tests, 100% coverage); the core gate passed (201 files, 2,986 tests, 100% coverage); `git diff --check` passed. The earlier isolated daemon acceptance still covers unchanged role adoption and native launch code; this rebase changed the host stop/cancel path and a shared import, which the Super Tab and core suites exercised.