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
Swarm: a project's Product Manager on a teammate's Team account, with a queue when no machine is free (#2089)
0xken153571a6cef50d
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.tsindex 6bb4340a5..48d047dfd 100644--- a/backend/integration/superTabGithub.test.ts+++ b/backend/integration/superTabGithub.test.ts@@ -228,7 +228,8 @@ describe('the GitHub token endpoint', () => {describe('a queued start\'s preparation token', () => {/** The host's pool rows, now each Swarm's `pool` in the host form (design 4.10), in the shape the old pools route answered. */const hostPools = async (env: Env) => {- const response = await env.app.inject({ method: 'GET', url: '/api/super-tabs/hosts/gh-pool/changes?full=1', headers: { authorization: `Bearer ${host.sub}` } })+ // gh-pool is a Team machine (`queued`): its host reads are its team session's.+ const response = await env.app.inject({ method: 'GET', url: '/api/super-tabs/hosts/gh-pool/changes?full=1', headers: { authorization: `Bearer ${host.sub}`, 'x-test-team': '1' } })const rows = (response.json().data.tabs as Array<{ pool: unknown }>).flatMap(tab => tab.pool ? [tab.pool] : [])return { json: () => ({ data: rows }) }}@@ -245,22 +246,31 @@ describe('a queued start\'s preparation token', () => {await env.run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string } as Command, contributor)}await env.run(tab, { type: 'machine.contribute', machineId, name: 'Pool', cwd: '/swarm-root', scope: 'swarm', engines: ['codex'], maxAgents: 2 } as Command, contributor)- const pool = (await poolRows(env.store, contributor, machineId)).find(p => p.tabId === tab)!- if (contributor === owner) await env.store.observeMachine(contributor, tab, machineId, { generation: pool.machine.generation, ...observed })- else {+ if (contributor === owner) {+ const pool = (await poolRows(env.store, contributor, machineId)).find(p => p.tabId === tab)!+ await env.store.observeMachine(contributor, tab, machineId, { generation: pool.machine.generation, ...observed })+ } else {// Another person's project runs only on a Team machine (#1694): this one is used only for agents (`harness team on`).const computerId = createHash('sha256').update(machineId).digest('hex').slice(0, 32)await db.machine.update({ where: { machineId }, data: { computerId, sessionKind: 'team' } })onTestFinished(async () => { await db.machine.update({ where: { machineId }, data: { computerId: null, sessionKind: null } }) })const team: AuthUser = { ...contributor, harnessSessionId: `team-${machineId}`, harnessSessionKind: 'team', harnessComputerId: computerId }+ // Its host routes take its team session alone (security review 2 of #2089): `prepare` signs in as it.+ if (!users.some(u => u.sub === team.sub && u.harnessSessionKind === 'team')) {+ users.push(team)+ onTestFinished(() => { users.splice(users.indexOf(team), 1) })+ }+ const pool = (await poolRows(env.store, team, machineId)).find(p => p.tabId === tab)!await env.store.observeMachine(team, tab, machineId, { generation: pool.machine.generation, ...observed, privacy: { mode: 'dedicated' } })}const startId = String((await env.run(tab, { type: 'agent.start', request: { conversationId: 'lead', machineId, engine: 'codex', name: 'Builder',cwd: '/swarm-root/lead', permissionMode: 'full', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as Command)).result.startId)return { tab, startId }}- const prepare = (env: Env, tab: string, startId: string, machineId = 'gh-pool', user = host, payload: Record<string, unknown> = {}) => env.app.inject({ method: 'POST',- url: `/api/super-tabs/hosts/${machineId}/starts/${tab}/${startId}/github-token`, headers: { authorization: `Bearer ${user.sub}` }, payload })+ /** As [user]'s Harness Team account by default on `gh-pool`, the Team machine `queued` makes for another person's start. */+ const prepare = (env: Env, tab: string, startId: string, machineId = 'gh-pool', user = host, payload: Record<string, unknown> = {},+ team = user === host && machineId === 'gh-pool') => env.app.inject({ method: 'POST',+ url: `/api/super-tabs/hosts/${machineId}/starts/${tab}/${startId}/github-token`, headers: { authorization: `Bearer ${user.sub}`, ...(team ? { 'x-test-team': '1' } : {}) }, payload })it('gives the host of another person\'s start a token that only reads the project\'s repository, and says whom the work is for', async () => {const env = await fresh()@@ -434,7 +444,9 @@ describe('a queued start\'s preparation token', () => {expect((await prepare(env, tab, startId, 'gh-host-mini')).statusCode).toBe(403)expect((await prepare(env, tab, 'missing-start')).statusCode).toBe(404)expect((await prepare(env, tab, startId, 'gh-pool', host, { machineId: 'gh-pool' })).statusCode).toBe(400)- const hostRun = (command: Command) => env.store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'gh-pool')+ // gh-pool is a Team machine (`queued`): its team session hosts it.+ const team = users.find(u => u.sub === host.sub && u.harnessSessionKind === 'team')!+ const hostRun = (command: Command) => env.store.execute(team, tab, { operationId: randomUUID(), command }, undefined, 'gh-pool')await hostRun({ type: 'agent.startDispatch', startId } as Command)await hostRun({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config } as Command)const settled = await prepare(env, tab, startId)diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 0d7588b10..5eb224f29 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -119,8 +119,9 @@ describe('a team session hosting its own machine', () => {// The reading is stamped with how the machine is signed in, from the session and never from the request.const pool = () => store.read(owner, f.tab).then(r => r.state.machines!.find(m => m.machineId === 'team-mac')!)expect((await pool()).observation).toMatchObject({ sessionKind: 'team' })- await store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))- expect((await pool()).observation).toMatchObject({ sessionKind: 'computer' })+ // The person's own sign-in may not report for it (security review 2 of #2089): only its team session hosts it.+ await expect(store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ expect((await pool()).observation).toMatchObject({ sessionKind: 'team' })})it('settles the starts queued for its own machine, as the pool host', async () => {@@ -332,9 +333,8 @@ describe('a teammate\'s work and the machines that take it', () => {expect((await pool(f.tab, 'team-mac', person)).observation!.privacy).toMatchObject({ item: 'gitconfig', detail: FAILED.detail })expect((await pool(f.tab, 'team-mac')).observation!.privacy).toEqual({ mode: 'account', passed: false, item: 'gitconfig', checkedAt: FAILED.checkedAt, seenAt: expect.any(Number) })expect((await pool(f.tab, 'team-mac')).teamWork).toMatchObject({ allowed: false, code: 'PRIVACY_CHECK_FAILED' })- // A reading of the team machine from the person's own sign-in drops the check; its account row still says team.- await store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))- expect((await pool(f.tab, 'team-mac')).teamWork).toMatchObject({ allowed: false, code: 'PRIVACY_UNCHECKED' })+ // The person's own sign-in may not report for the team machine at all (security review 2 of #2089).+ await expect(store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY' })})it('refuses the owner\'s project on the person\'s personal Mac and admits it on their Team machine; the person\'s own work is unchanged', async () => {@@ -352,7 +352,9 @@ describe('a teammate\'s work and the machines that take it', () => {await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, FAILED))await expect(start(f.tab, f.teamGroup, 'team-mac')).rejects.toMatchObject({ code: 'PRIVACY_CHECK_FAILED',message: 'The Harness Team account on MacBook Pro · Team is not private (gitconfig: it could read its owner\'s ~/.gitconfig), so it runs only its owner\'s projects.' })- await store.observeMachine(person, f.tab, 'team-mac', reading(f.generation))+ // A reading with no check at all (the person's own sign-in may no longer report for it, security review 2 of #2089).+ const { privacy: _privacy, ...unchecked } = reading(f.generation) as Record<string, unknown>+ await store.observeMachine(team, f.tab, 'team-mac', unchecked as Parameters<SuperTabStore['observeMachine']>[3])await expect(start(f.tab, f.teamGroup, 'team-mac')).rejects.toMatchObject({ code: 'PRIVACY_UNCHECKED' })await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation))// Twenty minutes on, the team daemon still sends the same check: it stopped running.@@ -689,3 +691,97 @@ describe('one machine: a Mac and its Harness Team account', () => {expect(await pending()).toEqual({ cleanups: ['kept-pc'], indexed: ['kept-pc'] })})})++// A project's Product Manager on another person's Team machine (leadStart.ts, Dee 10-29): placed by the store when a+// machine reports, launched from a list older hosts do not read, and the project's Lead once it runs.+describe('a project\'s Product Manager on a teammate\'s Team machine', () => {+ const capable = (generation: string) => ({ ...reading(generation), capabilities: ['leadStart'] }) as Parameters<SuperTabStore['observeMachine']>[3]++ it('waits for a machine that can run it, starts on the Team machine once it reports, and leads the project', async () => {+ const f = await fixture()+ const created = (await run(f.tab, { type: 'project.create', name: 'App', visibility: 'private', brief: 'Build it.' })).result+ const projectId = String(created.projectId), home = String(created.conversationId)+ // The team daemon has not said it starts Product Managers yet: nothing is free, so it waits.+ const asked = await run(f.tab, { type: 'lead.start', projectId, machineId: null, engine: 'codex', repositoryUrl: 'https://github.com/example/app' })+ expect(asked.result).toMatchObject({ waiting: true })+ expect((await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.leadStarts).toBeUndefined()+ // Contributed for every project, as a Mac added to a Swarm with projects is; the fixture's serves only the first. Its+ // Builder of that first project goes, so the account can serve this project alone.+ await run(f.tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', scope: 'swarm', engines: ['codex'], maxAgents: 4 }, person)+ await run(f.tab, { type: 'agent.remove', agentId: f.builder })+ const generation = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.machine.generation+ await store.observeMachine(team, f.tab, 'team-mac', capable(generation))+ const row = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!+ expect(row.leadStarts).toEqual([expect.objectContaining({ request: expect.objectContaining({ machineId: 'team-mac', cwd: `/team/${projectId}`,+ leadFor: expect.objectContaining({ projectId, personId: owner.sub }) }) })])+ expect(row.starts.some(s => s.request.leadFor)).toBe(false)+ const startId = row.leadStarts![0]!.id+ await hostRun(f.tab, { type: 'agent.startDispatch', startId })+ const agentId = String((await hostRun(f.tab, { type: 'agent.started', startId, harnessId: `team-pm-${randomUUID()}`, configuration: config })).result.agentId)+ const read = await store.read(owner, f.tab)+ expect(read.state.conversations.find(c => c.id === home)).toMatchObject({ leadId: agentId })+ expect(read.state.projects!.find(p => p.id === projectId)!.lead).toMatchObject({ status: 'started', machineId: 'team-mac' })+ expect((await store.messages(owner, f.tab, home, {})).messages.map(m => m.text))+ .toEqual(expect.arrayContaining(['Waiting for a machine to start the Product Manager.', 'Product Manager started on MacBook Pro · Team.']))+ })++ // The isolated confidential run (docs/performance/2026-10-27-pm-confidential-isolated-run.test.mts), its Team machine case:+ // a Product Manager in another person's Team account, every way of watching or driving it through the Swarm.+ it('in another person\'s Team account: its project\'s owner only watches it, and the Mac\'s owner neither watches nor drives it', async () => {+ const f = await fixture()+ const created = (await run(f.tab, { type: 'project.create', name: 'App', visibility: 'public', brief: '' })).result+ const projectId = String(created.projectId)+ await run(f.tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', scope: 'swarm', engines: ['codex'], maxAgents: 4 }, person)+ const generation = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.machine.generation+ await store.observeMachine(team, f.tab, 'team-mac', capable(generation))+ // The fixture's own Builder of the owner's first project runs there: it goes first, so the account serves one project.+ await run(f.tab, { type: 'agent.remove', agentId: f.builder })+ const placed = await run(f.tab, { type: 'lead.start', projectId, machineId: 'team-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' })+ const startId = String(placed.result.startId)+ await hostRun(f.tab, { type: 'agent.startDispatch', startId })+ const pm = String((await hostRun(f.tab, { type: 'agent.started', startId, harnessId: `team-pm-${randomUUID()}`, configuration: config })).result.agentId)+ const terminal = (user: AuthUser, command: Command) => run(f.tab, command, user).then(() => 'ok', (error: { code?: string }) => error.code)+ expect(await terminal(owner, { type: 'agent.screen', agentId: pm, scrollback: 50 })).toBe('ok')+ expect(await terminal(owner, { type: 'agent.input', agentId: pm, text: 'ls ~' })).toBe('TERMINAL_PRIVATE')+ expect(await terminal(person, { type: 'agent.screen', agentId: pm, scrollback: 50 })).toBe('TERMINAL_PRIVATE')+ expect(await terminal(person, { type: 'agent.input', agentId: pm, text: 'ls ~' })).toBe('TERMINAL_PRIVATE')+ // Its host's roster: confidential, watched by its project's owner alone, never by the Mac's owner.+ const row = (await rosterRows(store, team, 'team-mac')).find(r => r.tabId === f.tab && r.agent.id === pm)!+ expect(row).toMatchObject({ confidential: true })+ expect(row.observers.map((o: { email: string }) => o.email)).toEqual([owner.email])+ // Security review 2 of #2089: the Mac owner's own sign-in, ordinary tools, cannot act as the Team machine's host or as+ // its Product Manager: no reading the chats it reads, no claiming its deliveries, no posting as it.+ // People talk to the PM in its project's conversation (Chat with PM is closed on main): what it reads there, it reads.+ const chat = String(created.conversationId)+ await run(f.tab, { type: 'message.send', conversationId: chat, text: 'For the PM: the launch slips a week.', replyTo: null, recipientIds: [] })+ await expect(store.messages(person, f.tab, chat, {}, pm)).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(store.deliveries(person, f.tab, pm)).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(store.execute(person, f.tab, { operationId: randomUUID(), command: { type: 'message.send', conversationId: chat, text: 'as the PM',+ replyTo: null, recipientIds: [] } }, pm)).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(store.observeMachine(person, f.tab, 'team-mac', capable(generation))).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ // Its own team session still is its host.+ await expect(store.deliveries(team, f.tab, pm)).resolves.toBeInstanceOf(Array)+ // An ordinary sign-in connecting as the Team computer resets its account row's mark (lib/adapterWs.ts): the Swarm's own+ // record that it is a Team account still refuses the owner (security re-check 2 of #2089).+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { sessionKind: 'computer' } })+ onTestFinished(async () => { await db.machine.update({ where: { machineId: 'team-mac' }, data: { sessionKind: 'team' } }) })+ await expect(store.messages(person, f.tab, chat, {}, pm)).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(store.deliveries(person, f.tab, pm)).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(store.observeMachine(person, f.tab, 'team-mac', capable(generation))).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await expect(rosterRows(store, person, 'team-mac')).rejects.toMatchObject({ code: 'TEAM_HOST_ONLY', status: 403 })+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { sessionKind: 'team' } })+ // And no other project's work starts there while it runs.+ await expect(run(f.tab, { type: 'agent.start', request: { conversationId: f.teamGroup, machineId: 'team-mac', engine: 'codex', name: 'Builder',+ cwd: '/team/lead', worktree: true, requirements } })).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_HELD' })+ })++ it('is refused on the teammate\'s personal Mac even while the Swarm does not yet require Team accounts', async () => {+ const f = await fixture()+ const projectId = String((await run(f.tab, { type: 'project.create', name: 'App', visibility: 'private', brief: '' })).result.projectId)+ await run(f.tab, { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', scope: 'swarm', engines: ['codex'], maxAgents: 2 }, person)+ const generation = (await poolRows(store, person, 'personal-mac')).find(p => p.tabId === f.tab)!.machine.generation+ await store.observeMachine(person, f.tab, 'personal-mac', capable(generation))+ await expect(run(f.tab, { type: 'lead.start', projectId, machineId: 'personal-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' }))+ .rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403 })+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 46a2e1dcc..f335ef25a 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -61,7 +61,8 @@ async function routedStart(tab: string, lead: string, role?: 'reviewer') {const message = (text: string): Command => ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [] })/** Makes [machineId], a machine of `host`'s, one used only for agents (`harness team on`) for this test: its account row* is a team machine and it reports from its team session with that privacy, so it may take the owner's projects- * (docs/plans/2026-10-24-swarm-team-account.md, Task 3). A teammate's work runs only on such a machine. */+ * (docs/plans/2026-10-24-swarm-team-account.md, Task 3). A teammate's work runs only on such a machine. Its host routes then+ * take its team session alone, never its owner's own sign-in (security review 2 of #2089). */async function teamMachine(machineId: string) {const computerId = createHash('sha256').update(machineId).digest('hex').slice(0, 32)await db.machine.update({ where: { machineId }, data: { computerId, sessionKind: 'team' } })@@ -696,7 +697,7 @@ describe('private swarm projects on the real control API', () => {await expect(run(tab, { type: 'agent.start', request })).rejects.toMatchObject({ code: 'PROJECT_CONTRIBUTION' })await run(tab, { type: 'machine.contribute', machineId, name: 'Shared capacity', cwd: '/swarm-root',scope: 'swarm', engines: ['codex'], maxAgents: 2 }, host)- const pool = (await poolRows(store, host, machineId))[0]!+ const pool = (await poolRows(store, team.session, machineId))[0]!await store.observeMachine(team.session, tab, machineId, { generation: pool.machine.generation,resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, projectDiskFreeBytes: 100e9,diskFreeBytes: 100e9, diskTotalBytes: 500e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },@@ -706,20 +707,20 @@ describe('private swarm projects on the real control API', () => {.rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })const secondStart = (await run(tab, { type: 'agent.start', request })).result.startId as stringawait run(tab, { type: 'agent.start', request: { ...request, conversationId: 'lead', cwd: '/swarm-root/lead' } })- const queued = (await poolRows(store, host, machineId))[0]!+ const queued = (await poolRows(store, team.session, machineId))[0]!expect(queued.starts).toHaveLength(2)expect(queued.projects!.find(p => p.id === projectId)).toMatchObject({repository: { machineId: 'test-host', cwd: '/lead/second', repositoryUrl: 'https://github.com/example/second' },conversationIds: [conversationId],})expect((await store.read(host, tab)).state.projects!.some(p => p.id === projectId)).toBe(false)- const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, machineId)+ const hostRun = (command: Command) => store.execute(team.session, tab, { operationId: randomUUID(), command }, undefined, machineId)await hostRun({ type: 'agent.startDispatch', startId: secondStart })const started = await hostRun({ type: 'agent.started', startId: secondStart, harnessId: 'second-builder', configuration: config })await hostRun({ type: 'agent.startSettled', startId: secondStart, warning: null })const agentId = String(started.result.agentId)- expect((await store.read(host, tab, agentId)).state.conversations.map(c => c.id)).toEqual([conversationId])- await expect(store.messages(host, tab, 'lead', {}, agentId)).rejects.toMatchObject({ code: 'NOT_FOUND' })+ expect((await store.read(team.session, tab, agentId)).state.conversations.map(c => c.id)).toEqual([conversationId])+ await expect(store.messages(team.session, tab, 'lead', {}, agentId)).rejects.toMatchObject({ code: 'NOT_FOUND' })expect(await db.machineShare.findUnique({ where: { machineId } })).toBeNull()})@@ -891,7 +892,7 @@ describe('Super Tabs on a real Mongo replica set', () => {const team = await teamMachine('grid-host')await run(tab, { type: 'machine.contribute', machineId: 'grid-host', name: 'Grid laptop', cwd: '/project', engines: ['claude'], maxAgents: 2 }, host)const grid = (await store.read(owner, tab)).state.localModels!.grid- const generation = (await poolRows(store, host, 'grid-host'))[0]!.machine.generation+ const generation = (await poolRows(store, team.session, 'grid-host'))[0]!.machine.generationawait store.observeMachine(team.session, tab, 'grid-host', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy,@@ -901,7 +902,7 @@ describe('Super Tabs on a real Mongo replica set', () => {const startId = String((await run(tab, { type: 'agent.start', request: { conversationId: group, machineId: 'grid-host', engine: 'claude', name: 'Builder',cwd: '/project', worktree: true, gridModel: 'moonshotai/kimi-k3', gridName: grid,requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } })).result.startId)- const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'grid-host')+ const hostRun = (command: Command) => store.execute(team.session, tab, { operationId: randomUUID(), command }, undefined, 'grid-host')await hostRun({ type: 'agent.startDispatch', startId })const agentId = String((await hostRun({ type: 'agent.started', startId, harnessId: 'grid-builder',configuration: { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null } })).result.agentId)@@ -924,14 +925,14 @@ describe('Super Tabs on a real Mongo replica set', () => {await db.machine.create({ data: { machineId: 'skills-host', userId: host.sub, apiKey: 'fixture-skills-host', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })const team = await teamMachine('skills-host')await run(tab, { type: 'machine.contribute', machineId: 'skills-host', name: 'Skills laptop', cwd: '/project', engines: ['claude'], maxAgents: 4 }, host)- const generation = (await poolRows(store, host, 'skills-host'))[0]!.machine.generation+ const generation = (await poolRows(store, team.session, 'skills-host'))[0]!.machine.generationawait store.observeMachine(team.session, tab, 'skills-host', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy })const start = async () => String((await run(tab, { type: 'agent.start', request: { conversationId: 'lead', machineId: 'skills-host', engine: 'claude',name: 'Builder', cwd: '/project', worktree: true,requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } })).result.startId)- const skillMode = async (startId: string) => (await store.start(host, tab, startId, undefined, 'skills-host')).skillMode+ const skillMode = async (startId: string) => (await store.start(team.session, tab, startId, undefined, 'skills-host')).skillModeexpect(await skillMode(await start())).toBe('default')await run(tab, { type: 'project.skills', projectId: 'lead', mode: 'orchestration' })@@ -953,7 +954,7 @@ describe('Super Tabs on a real Mongo replica set', () => {await expect(run(tab, contribute)).rejects.toMatchObject({ code: 'HOST_REQUIRED' })await run(tab, contribute, host)expect(await db.machineShare.findUnique({ where: { machineId: 'pool-host' } })).toBeNull()- const pools = await poolRows(store, host, 'pool-host')+ const pools = await poolRows(store, team.session, 'pool-host')expect(pools).toHaveLength(1)const generation = pools[0]!.machine.generationconst observation = { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,@@ -973,7 +974,7 @@ describe('Super Tabs on a real Mongo replica set', () => {expect(queued.request.permissionMode).toBe('full')await expect(run(tab, { type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })await expect(store.start(peer, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })- const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'pool-host')+ const hostRun = (command: Command) => store.execute(team.session, tab, { operationId: randomUUID(), command }, undefined, 'pool-host')await expect(hostRun(message('Not a generic proxy'))).rejects.toMatchObject({ code: 'FORBIDDEN' })await run(tab, { type: 'machine.pause', machineId: 'pool-host', paused: true }, host)await expect(hostRun({ type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'MACHINE_PAUSED' })@@ -989,10 +990,10 @@ describe('Super Tabs on a real Mongo replica set', () => {expect((await store.start(owner, tab, startId)).poolSettled).toBe(true)expect((await store.read(owner, tab)).state.agents[0]).toMatchObject({ contributorId: host.sub, machineOwnerId: host.sub, harnessId: 'pool-builder' })await run(tab, { type: 'member.remove', userId: host.sub })- expect(await poolRows(store, host, 'pool-host')).toEqual([])+ expect(await poolRows(store, team.session, 'pool-host')).toEqual([])// The machine stays listed while its host cleans up, but its owner left: a reading is refused as theirs no longer.- await expect(store.observeMachine(host, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'FORBIDDEN' })- await expect(store.start(host, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })+ await expect(store.observeMachine(team.session, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'FORBIDDEN' })+ await expect(store.start(team.session, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })})it('resolves a reply beyond recent history without crossing conversation or membership boundaries', async () => {@@ -1557,7 +1558,7 @@ describe('Super Tabs on a real Mongo replica set', () => {const request = { conversationId: 'lead', machineId: 'test-host', engine: 'codex', name: 'Builder', cwd: '/work/app', worktree: true,requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }await run(tab, { type: 'agent.start', request })- expect((await poolRows(store, host, 'test-host')).find(p => p.tabId === tab)!.projects).toEqual([expect.objectContaining({ id: 'lead', repository })])+ expect((await poolRows(store, team.session, 'test-host')).find(p => p.tabId === tab)!.projects).toEqual([expect.objectContaining({ id: 'lead', repository })])})it('lets a project\'s Lead change its skills only by quoting a message the project owner wrote there, and tells the host', async () => {const tab = (await store.create(owner, randomUUID(), 'Skills')).iddiff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 22716beab..5863bc83f 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1102,7 +1102,9 @@ it('allows the contributor to keep a completed worker and refuses another projecf.run({ type: 'agent.release', agentId: worker, decision: 'keep' }, peer)expect(f.state.agents.find(a => a.id === worker)!.workDecision).toBe('keep')const project = f.run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result- const otherLead = f.add('other-lead', 'owner', project.conversationId as string, true)+ // On another machine: a Team account running this project's Lead takes no other project's work (leadStart.ts, #895).+ const otherLead = f.run({ type: 'agent.add', conversationId: project.conversationId as string, machineId: 'other-host', harnessId: 'other-lead',+ name: 'other-lead', configuration: config, lead: true }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as stringexpect(() => f.run({ type: 'agent.release', agentId: worker, decision: 'stop' }, { kind: 'agent', agentId: otherLead, machineOwnerId: 'host-owner' })).toThrow()})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 70d90890a..78066b475 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,4 +1,4 @@-import { admitMachineStart, cleanupOverdue, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, ownedMachine, projectFolder, requireTeamWork, teamMachineFor, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'+import { admitMachineStart, cleanupOverdue, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'import { assignAgentDisplayNames } from './agentNames.js'import { z } from 'zod'import { tokensByModelSchema } from './costs/tokens.js'@@ -27,9 +27,10 @@ import { react, reactionSchema, type ReactionTarget } from './reactions.js'import { shipNotice, shippedAt } from './ship.js'import { openReview, openReviewOf, projectPullRequest, verdictPending } from './autoReview.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'-import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'+import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'import { CODEX_BUDDY_REFUSAL } from './buddyContract.js'+import { LEAD_NAME, leadJoined, leadStartFailed, leadStarting, requestLead, WAITING_TEXT } from './leadStart.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const title = z.string().trim().min(1).max(160)@@ -110,6 +111,9 @@ export const commandSchema = z.discriminatedUnion('type', [throughRevision: z.number().int().nonnegative().safe().optional(), text: text.nullable() }).strict().refine(c => (c.through === undefined) !== (c.throughRevision === undefined), 'Acknowledge with through, the map your wake-up names.'),z.object({ type: z.literal('project.repository'), projectId: id, repositoryUrl }).strict(),+ z.object({ type: z.literal('lead.start'), projectId: id, machineId: id.nullable(), engine: swarmEngine,+ model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),+ branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(), repositoryUrl: repositoryUrl.optional() }).strict(),z.object({ type: z.literal('project.skills'), projectId: id, mode: z.enum(['default', 'orchestration', 'custom']), askedIn: askedInSchema.optional() }).strict(),z.object({ type: z.literal('project.roles.create'), projectId: id, roles: roleSet }).strict(),z.object({ type: z.literal('project.role.set'), projectId: id, role }).strict(),@@ -710,7 +714,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst removeAgent = (target: Agent, { lead = false, close = true } = {}) => {if (!lead) protectLead(state, target.id)if (close && !state.closingSessions?.some(c => c.agentId === target.id && c.harnessId === target.harnessId)) {- (state.closingSessions ??= []).push({ agentId: target.id, machineId: target.machineId, harnessId: target.harnessId, machineOwnerId: target.machineOwnerId })+ // A confidential session in a Team account keeps the account for its project until its host confirms the close, which+ // it does once the session's data there is deleted (security re-check 2 of #2089).+ const held = onTeamAccount(state, target) && isConfidential(state, target) ? { heldFor: agentProjectId(state, target), since: context.now } : {}+ ;(state.closingSessions ??= []).push({ agentId: target.id, machineId: target.machineId, harnessId: target.harnessId, machineOwnerId: target.machineOwnerId, ...held })}state.agents = state.agents.filter(a => a.id !== target.id)effects.cancelledAgents.push(target.id)@@ -879,6 +886,20 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaresult.conversationId = leadConversationIdbreak}+ case 'lead.start': {+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', `A person starts a project's ${LEAD_NAME}.`, 403)+ if (state.paused) fail('PAUSED', 'New work is paused in this Swarm.')+ const project = manageProject(state, actor, command.projectId)+ const home = conversation(state, project.leadConversationId)+ if (home.leadId && home.agentIds.includes(home.leadId)) fail('LEAD_EXISTS', `This project already has its ${LEAD_NAME}.`)+ if (leadStarting(state, project.id)) fail('LEAD_STARTING', `This project's ${LEAD_NAME} is already starting.`)+ if (!project.repository?.repositoryUrl && !command.repositoryUrl) fail('REPOSITORY_REQUIRED', 'Choose the repository this project works in.', 400)+ const { type: _type, projectId: _projectId, machineId, ...request } = command+ const placed = requestLead(state, project, person(state, actor.userId), machineId, request, operationId, context)+ Object.assign(result, placed)+ if ('waiting' in placed) message(home.id, WAITING_TEXT, [], null, SYSTEM_ROW)+ break+ }case 'project.skills': {// Only the project owner, or that project's Lead quoting a chat message the project owner wrote in the last day. The// same check as ruleChange, but against the project owner: the Swarm owner does not choose another person's skills.@@ -1267,6 +1288,16 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst chosen = command.roleId ? chosenRole(project, command.roleId, kind) : nullif (existing?.workDecision === 'stop' && command.lead) fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')if (existing && agentRole(existing) === 'reviewer' && command.lead) fail('REVIEWER_NOT_LEAD', 'A Reviewer reviews work and cannot lead a group.')+ // A Harness Team account hosting a Product Manager serves only its project, and one is never added where another+ // project's work runs (machines.ts productManagerOn, as admitMachineStart holds a start; security re-review of #2089).+ const teamPool = teamAccountPool(machineContribution(state, command.machineId))+ if (!existing && teamPool) {+ const held = productManagerOn(state, command.machineId)+ if (held && held !== project.id) fail('TEAM_ACCOUNT_HELD', 'This machine\'s Harness Team account runs another project\'s Product Manager, so it takes only that project\'s work for now.', 403)+ if (kind === 'lead' && [...projectsOnMachine(state, command.machineId)].some(id => id !== project.id)) {+ fail('TEAM_ACCOUNT_BUSY', 'This machine\'s Harness Team account runs other projects\' agents, so it cannot host this Product Manager now.', 409)+ }+ }if (!existing) reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)// Added back before its host closed it: the session stays open.if (!existing) dropClosing(state, c => c.machineId !== command.machineId || c.harnessId !== command.harnessId)@@ -1275,7 +1306,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: CommamachineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,hostGrant: grant.hostGrant ?? null,name: command.name, configuration: command.configuration, configurationVersion: operationId,- ...(chosen?.kind === 'reviewer' ? { role: 'reviewer' as const } : {}), ...(chosen ? { roleId: chosen.id } : {}) })+ ...(chosen?.kind === 'reviewer' ? { role: 'reviewer' as const } : {}), ...(chosen ? { roleId: chosen.id } : {}),+ ...(teamPool ? { teamAccount: true as const } : {}) })if (existing && (existing.machineOwnerId !== grant.machineOwnerId || existing.contributorId !== grant.contributorId)) {fail('ALREADY_SHARED', 'This session already has a contributor. Use the existing tab agent.')}@@ -1478,7 +1510,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}if (command.type === 'agent.startSettled') {if (!start.poolGeneration || !start.harnessId || start.error) fail('START_PENDING', 'This contributed start is not ready to settle.')- if (!start.poolSettled) message(start.request.conversationId, command.warning+ // A Product Manager is never assigned work: its conversation already said where it started.+ if (!start.poolSettled && !start.request.leadFor) message(start.request.conversationId, command.warning? `${start.request.name}: ${command.warning}`: start.request.buddyOf ? buddyReady(start.request.name) : `${start.request.name} is ready for an assignment.`, [], null, SYSTEM_ROW)start.poolSettled = true@@ -1487,6 +1520,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.type === 'agent.startFailed') {if (start.harnessId) fail('ALREADY_STARTED', 'This agent already started.')start.error = command.error+ // A Product Manager's start says so in its project's conversation only when it stops trying (leadStart.ts).+ if (start.request.leadFor) {+ const ended = leadStartFailed(state, start, command.error, context.now)+ if (ended) message(start.request.conversationId, ended, [], null, SYSTEM_ROW)+ break+ }// The Lead is woken, so it starts the work elsewhere once or reports it (cli superTabs/start.ts): written in its own// name for nobody, this notice left the round-device group without a worker for an hour (2026-10-27).const group = conversation(state, start.request.conversationId)@@ -1510,12 +1549,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma...(start.request.role ? { role: start.request.role } : {}), ...(start.request.roleId ? { roleId: start.request.roleId } : {}),...(start.request.gridModel ? { gridModel: start.request.gridModel } : {}),...(start.request.buddyOf ? { buddyOf: start.request.buddyOf } : {}),+ ...(teamAccountPool(machineContribution(state, start.request.machineId)) ? { teamAccount: true as const } : {}),...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })group.agentIds.push(agentId)start.harnessId = command.harnessIdresult.agentId = agentId+ if (start.request.leadFor) {+ // Taking over from a Lead that left, as agent.add does.+ if (group.leadId && !group.agentIds.includes(group.leadId)) keepLead(group, agentId)+ message(group.id, leadJoined(state, start, group, agentId), [], null, SYSTEM_ROW)+ }// A Buddy always starts on a Swarm machine: its chat hears once it settles, as the Lead does for a worker.- if (!start.request.buddyOf) message(group.id, start.poolGeneration+ else if (!start.request.buddyOf) message(group.id, start.poolGeneration? `${start.request.name} joined. Preparing its model.`: `${start.request.name} joined. Ready for an assignment.`, [], null, SYSTEM_ROW)breakdiff --git a/backend/src/superTabs/leadStart.test.ts b/backend/src/superTabs/leadStart.test.tsnew file mode 100644index 000000000..e772a5a22--- /dev/null+++ b/backend/src/superTabs/leadStart.test.ts@@ -0,0 +1,446 @@+import { afterEach, describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import type { ContributedMachine, MachinePrivacy } from './machines.js'+import type { LeadContext } from './leadStart.js'+import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'++// A project's Product Manager started by the Swarm on one of its machines (Dee, 10-29, option B): on another person's Mac it+// runs only in that Mac's Harness Team account, never as the Mac's owner; with no machine free it waits for one.++const NOW = 50_000_000+const MINUTE = 60_000+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,+ deviceType: null, chip: null, os: null, gpuPercent: null }+const PASSED: MachinePrivacy = { mode: 'account', passed: true, checkedAt: NOW - MINUTE }+const FAILED: MachinePrivacy = { mode: 'account', passed: false, item: 'gitconfig', detail: 'The team account could read ~/.gitconfig.', checkedAt: NOW - MINUTE }+const REPO = 'https://github.com/example/app'+type Reading = NonNullable<ContributedMachine['observation']>+/** A reading as the store keeps it, from a host that starts Product Managers unless [capable] is false. */+const reading = (sessionKind: 'team' | 'computer', privacy?: MachinePrivacy, capable = true): Reading => ({+ generation: 'g1', receivedAt: NOW, sessionKind, resources, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [],+ ...(capable ? { capabilities: ['leadStart'] } : {}), ...(privacy ? { privacy: { ...privacy, seenAt: NOW } } : {}) })+const refusal = (body: () => unknown): SuperTabError | null => {+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error; throw error }+}++afterEach(() => { delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED })++/** The owner's Swarm with the owner's project App: the owner's Mac, and the teammate's MacBook with its Harness Team account. */+function swarm() {+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const teamMachines = (state.machines ?? []).filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines, ...context })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: mate.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, mate)+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation+ const pool = (machineId: string, contributorId: string, name: string, observation: Reading, extra: Partial<ContributedMachine> = {}): ContributedMachine => ({+ machineId, name, contributorId, membershipGeneration: generation(contributorId), generation: 'g1', cwd: '/swarm', scope: 'swarm',+ engines: ['claude', 'codex'], maxAgents: 4, paused: false, observation, ...extra })+ state.machines = [+ pool('owner-mac', 'owner', 'Owner Mac', reading('computer')),+ pool('mate-mac', 'mate', 'MacBook Pro', reading('computer')),+ pool('mate-team', 'mate', 'MacBook Pro', reading('team', PASSED), { hostMachineId: 'mate-mac', cwd: '/team-swarm' }),+ ]+ const app = run({ type: 'project.create', name: 'App', visibility: 'private', brief: 'Build the app.' }).result as { projectId: string; conversationId: string }+ const machine = (machineId: string) => state.machines!.find(m => m.machineId === machineId)!+ const project = () => state.projects!.find(p => p.id === app.projectId)!+ const lead = (machineId: string | null, extra: Record<string, unknown> = {}, actor: Actor = owner, context: Partial<CommandContext> = {}) =>+ run({ type: 'lead.start', projectId: app.projectId, machineId, engine: 'claude', repositoryUrl: REPO, ...extra } as Command, actor, context)+ return { run, app, machine, project, lead, get state() { return state } }+}++describe('starting a project\'s Product Manager on a Swarm machine', () => {+ it('on the project owner\'s own machine, runs as its owner in the project\'s folder there', () => {+ const f = swarm()+ const started = f.lead('owner-mac', { model: 'opus', effort: 'high' })+ expect(f.state.starts).toEqual([expect.objectContaining({ id: started.result.startId, poolGeneration: 'g1', machineOwnerId: 'owner',+ contributorId: 'owner', actorKey: 'person:owner',+ request: expect.objectContaining({ conversationId: f.app.conversationId, machineId: 'owner-mac', engine: 'claude', model: 'opus', effort: 'high',+ cwd: `/swarm/${f.app.projectId}`, worktree: true, leadFor: { projectId: f.app.projectId, personId: 'owner', generation: expect.any(String) } }) })])+ expect(started.result).toMatchObject({ machineId: 'owner-mac' })+ expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'owner-mac', machineName: 'Owner Mac', startId: started.result.startId })+ // The repository it clones, recorded for the project.+ expect(f.project().repository).toEqual({ machineId: 'owner-mac', cwd: `/swarm/${f.app.projectId}`, repositoryUrl: REPO })+ })++ it('on a teammate\'s Mac, runs in that Mac\'s Harness Team account and its folder, never as the Mac\'s owner', () => {+ const f = swarm()+ f.lead('mate-mac')+ expect(f.state.starts).toEqual([expect.objectContaining({ machineOwnerId: 'mate',+ request: expect.objectContaining({ machineId: 'mate-team', cwd: `/team-swarm/${f.app.projectId}` }) })])+ expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'mate-team', machineName: 'MacBook Pro' })+ })++ it('is refused with the Team account\'s own reason, and records nothing', () => {+ const f = swarm()+ f.machine('mate-team').observation = reading('team', FAILED)+ expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'PRIVACY_CHECK_FAILED', status: 403,+ message: 'The Harness Team account on MacBook Pro is not private (gitconfig: it could read its owner\'s ~/.gitconfig), so it runs only its owner\'s projects.' })+ f.machine('mate-team').observation = { ...reading('team', PASSED), receivedAt: NOW - 10 * MINUTE }+ expect(refusal(() => f.lead('mate-mac'))?.code).toBe('MACHINE_OFFLINE')+ expect(f.state.starts ?? []).toEqual([])+ expect(f.project().lead).toBeUndefined()+ })++ it('needs a Team account on another person\'s machine even while the Swarm does not yet require one', () => {+ // A worker would still run as the Mac's owner here; a Product Manager holds people's private chats, so it never does.+ delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED+ const f = swarm()+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team')+ expect(refusal(() => f.lead('mate-mac'))?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ // With no GitHub App the Team account takes no work, so the Mac would run it itself: refused too.+ expect(refusal(() => swarm().lead('mate-mac', {}, owner, { teamAccountsIdle: true }))?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ expect(f.state.starts ?? []).toEqual([])+ })++ it('is refused on a machine whose Harness is too old to start a Product Manager', () => {+ const f = swarm()+ f.machine('mate-team').observation = reading('team', PASSED, false)+ expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'HOST_OUTDATED',+ message: 'Update Harness on MacBook Pro to run a Product Manager there.' })+ })++ it('is refused off the Swarm\'s Machines list', () => {+ expect(refusal(() => swarm().lead('elsewhere'))?.code).toBe('MACHINE_NOT_LISTED')+ })++ it('is the project owner\'s to start: not a teammate\'s, nor an agent\'s', () => {+ const f = swarm()+ expect(refusal(() => f.lead('owner-mac', {}, mate))?.code).toBe('NOT_FOUND')+ f.run({ type: 'project.sharing', projectId: f.app.projectId, visibility: 'public', memberIds: [] })+ expect(refusal(() => f.lead('owner-mac', {}, mate))?.code).toBe('PROJECT_OWNER_REQUIRED')+ expect(f.state.starts ?? []).toEqual([])+ })++ it('needs the repository when the project has none yet', () => {+ const f = swarm()+ expect(refusal(() => f.lead('owner-mac', { repositoryUrl: undefined }))?.code).toBe('REPOSITORY_REQUIRED')+ })++ it('starts one Product Manager at a time', () => {+ const f = swarm()+ f.lead('owner-mac')+ expect(refusal(() => f.lead('mate-mac'))?.code).toBe('LEAD_STARTING')+ })++ it('is the only way to mark a start as a Product Manager\'s: an agent.start naming it is refused', () => {+ const request = { conversationId: 'c', machineId: 'm', engine: 'claude', name: 'PM', cwd: '/x', worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ expect(commandSchema.safeParse({ type: 'agent.start', request }).success).toBe(true)+ expect(commandSchema.safeParse({ type: 'agent.start', request: { ...request, leadFor: { projectId: 'p', personId: 'owner', generation: 'g' } } }).success).toBe(false)+ })+})++describe('a Product Manager\'s start, once its host reports it', () => {+ /** The host of [machineId] acting for the start's requester, as the store's host route does (store.ts poolHostActor). */+ const hosted = (f: ReturnType<typeof swarm>, machineId: string) => ({ contribution: { machineOwnerId: f.machine(machineId).contributorId,+ contributorId: f.machine(machineId).contributorId, hostGrant: null } })+ const messages = (effects: ReturnType<ReturnType<typeof swarm>['run']>, conversationId: string) =>+ effects.messages.filter(m => m.conversationId === conversationId).map(m => m.text)++ it('running, becomes the project\'s Lead and says on which machine', () => {+ const f = swarm()+ const startId = f.lead('mate-mac').result.startId as string+ const joined = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, hosted(f, 'mate-team'))+ const agentId = joined.result.agentId as string+ const home = f.state.conversations.find(c => c.id === f.app.conversationId)!+ expect(home).toMatchObject({ leadId: agentId, agentIds: [agentId] })+ expect(f.state.agents.find(a => a.id === agentId)).toMatchObject({ machineId: 'mate-team', machineOwnerId: 'mate', projectId: f.app.projectId })+ expect(messages(joined, f.app.conversationId)).toEqual(['Product Manager started on MacBook Pro.'])+ expect(f.project().lead).toMatchObject({ status: 'started', machineId: 'mate-team', machineName: 'MacBook Pro' })+ // Settling it does not call the Product Manager ready for an assignment.+ const settled = f.run({ type: 'agent.startSettled', startId, warning: null }, owner, hosted(f, 'mate-team'))+ expect(messages(settled, f.app.conversationId)).toEqual([])+ })++ it('failed on the machine the person chose, says why and waits for them', () => {+ const f = swarm()+ const startId = f.lead('mate-mac').result.startId as string+ f.run({ type: 'agent.startFailed', startId, error: 'Could not clone the repository.' }, owner, hosted(f, 'mate-team'))+ // Every reader of the project reads it, so not the host's own words (startFailure.ts publicReason).+ expect(f.project().lead).toMatchObject({ status: 'failed', reason: 'Its machine could not prepare or launch it.' })+ // They can start it again.+ expect(f.lead('owner-mac').result.machineId).toBe('owner-mac')+ })++ it('refused for want of the owner\'s relay, says so plainly to the project', async () => {+ const f = swarm()+ const reason = 'The owner\'s subscription relay is not available on this machine, so a Codex Product Manager cannot sign in here.'+ const startId = f.lead('mate-mac').result.startId as string+ f.run({ type: 'agent.startFailed', startId, error: reason }, owner, hosted(f, 'mate-team'))+ expect(f.project().lead).toMatchObject({ status: 'failed', reason })+ })++ it('never taken by its machine, fails as a Buddy\'s does', async () => {+ const { sweepLiveness, BUDDY_PICKUP_MS } = await import('./liveness.js')+ const f = swarm()+ f.lead('mate-mac')+ f.machine('mate-team').observation = { ...f.machine('mate-team').observation!, receivedAt: NOW + BUDDY_PICKUP_MS + MINUTE }+ const said = sweepLiveness(f.state, NOW + BUDDY_PICKUP_MS + MINUTE)+ expect(f.project().lead).toMatchObject({ status: 'failed', reason: 'Its machine did not start it. Harness there may need an update.' })+ // Said once in its project's conversation, in the name of the person who asked for it.+ // A system row of its project's conversation, not the asker's own words.+ expect(said.map(m => [m.conversationId, m.source])).toEqual([[f.app.conversationId, { kind: 'system' }]])+ expect(said[0]!.text).toBe('Could not start Product Manager: its machine did not start it. Harness there may need an update.')+ expect(sweepLiveness(f.state, NOW + BUDDY_PICKUP_MS + 2 * MINUTE)).toEqual([])+ })+})++describe('a Product Manager waiting for a machine', () => {+ const full = (f: ReturnType<typeof swarm>, machineId: string) => { f.machine(machineId).maxAgents = 0 }+ const place = async (f: ReturnType<typeof swarm>, context: Partial<LeadContext> = {}) => {+ const { placeWaitingLeads } = await import('./leadStart.js')+ // Placed on a machine's reading: the machines report as of then.+ for (const m of f.state.machines!) if (m.observation) m.observation = { ...m.observation, receivedAt: context.now ?? NOW }+ const teamMachines = f.state.machines!.filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)+ return placeWaitingLeads(f.state, { now: NOW, teamMachines, ...context })+ }++ it('starts at once on a free machine, the project owner\'s own first', () => {+ const f = swarm()+ const asked = f.lead(null)+ expect(asked.result).toMatchObject({ machineId: 'owner-mac' })+ expect(f.project().lead).toMatchObject({ status: 'starting', chosen: null, machineId: 'owner-mac' })+ })++ it('then the free Team machine', () => {+ const f = swarm()+ full(f, 'owner-mac')+ expect(f.lead(null).result).toMatchObject({ machineId: 'mate-team' })+ })++ it('with none free, waits and says so, then starts on the first one that frees up', async () => {+ const f = swarm()+ full(f, 'owner-mac')+ f.machine('mate-team').observation = reading('team', FAILED)+ const asked = f.lead(null)+ expect(asked.result).toMatchObject({ waiting: true })+ expect(asked.result).not.toHaveProperty('startId')+ expect(f.state.starts ?? []).toEqual([])+ expect(f.project().lead).toMatchObject({ status: 'waiting', chosen: null })+ expect(asked.messages.map(m => m.text)).toEqual(['Waiting for a machine to start the Product Manager.'])+ // Nothing free yet: nothing changes.+ expect(await place(f)).toEqual([])+ expect(f.project().lead?.status).toBe('waiting')+ f.machine('owner-mac').maxAgents = 4+ expect(await place(f)).toEqual([f.app.projectId])+ expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'owner-mac', machineName: 'Owner Mac' })+ expect(f.state.starts).toEqual([expect.objectContaining({ actorKey: 'person:owner', request: expect.objectContaining({ machineId: 'owner-mac' }) })])+ })++ it('placed from the queue and failed there, waits for another machine and tries that one last', async () => {+ const f = swarm()+ const startId = f.lead(null).result.startId as string+ f.run({ type: 'agent.startFailed', startId, error: 'Out of disk.' }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null } })+ expect(f.project().lead).toMatchObject({ status: 'waiting', reason: 'Its machine could not prepare or launch it.', skipped: ['owner-mac'] })+ expect(await place(f, { now: NOW + MINUTE })).toEqual([f.app.projectId])+ expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'mate-team' })+ })++ // Security review 1 of #2089: a queued Product Manager that kept failing was placed again at every machine reading, each+ // failure a row in its conversation.+ it('failing again and again, waits longer each time, gives up after three, and says so once', async () => {+ const { LEAD_QUEUE_ATTEMPTS } = await import('./leadStart.js')+ expect(LEAD_QUEUE_ATTEMPTS).toBe(3)+ const f = swarm()+ const fail = (startId: string, now: number) => f.run({ type: 'agent.startFailed', startId, error: 'Out of disk.' }, owner,+ { now, contribution: { machineOwnerId: f.state.starts!.find(s => s.id === startId)!.machineOwnerId, contributorId: f.state.starts!.find(s => s.id === startId)!.contributorId, hostGrant: null } })+ const said = (effects: ReturnType<typeof f.run>) => effects.messages.filter(m => m.conversationId === f.app.conversationId).map(m => m.text)+ let startId = f.lead(null).result.startId as string+ expect(said(fail(startId, NOW))).toEqual([])+ expect(f.project().lead).toMatchObject({ status: 'waiting', failures: 1, retryAt: NOW + MINUTE })+ // Not before its time, then on the next free machine.+ expect(await place(f, { now: NOW + MINUTE - 1 })).toEqual([])+ expect(await place(f, { now: NOW + MINUTE })).toEqual([f.app.projectId])+ startId = f.project().lead!.startId!+ expect(said(fail(startId, NOW + MINUTE))).toEqual([])+ expect(f.project().lead).toMatchObject({ status: 'waiting', failures: 2, retryAt: NOW + 3 * MINUTE })+ expect(await place(f, { now: NOW + 3 * MINUTE })).toEqual([f.app.projectId])+ startId = f.project().lead!.startId!+ expect(said(fail(startId, NOW + 3 * MINUTE))).toEqual(['The Product Manager could not start after 3 tries. The last one: Its machine could not prepare or launch it. Start it again when a machine is ready.'])+ expect(f.project().lead).toMatchObject({ status: 'failed', failures: 3 })+ expect(await place(f, { now: NOW + 60 * MINUTE })).toEqual([])+ })++ it('is dropped when the person who asked left the Swarm, and waits while the Swarm is paused', async () => {+ const f = swarm()+ full(f, 'owner-mac'); full(f, 'mate-team')+ f.lead(null)+ f.machine('owner-mac').maxAgents = 4+ f.state.paused = true+ expect(await place(f)).toEqual([])+ f.state.paused = false+ f.state.people.find(p => p.id === 'owner')!.generation = 'rejoined'+ expect(await place(f)).toEqual([])+ expect(f.project().lead).toMatchObject({ status: 'failed', reason: 'The person who asked for it left the Swarm.' })+ })++ it('asked for again while waiting, takes the new request', () => {+ const f = swarm()+ full(f, 'owner-mac'); full(f, 'mate-team')+ f.lead(null, { model: 'sonnet' })+ f.lead(null, { model: 'opus' })+ expect(f.project().lead).toMatchObject({ status: 'waiting', request: expect.objectContaining({ model: 'opus' }) })+ })+})++// R2 (Lead, #895): a Team account runs every teammate's work as one macOS user, its folders holding other projects' clones.+// Typing in a Product Manager there is a shell that reads them, so nobody types in it through the Swarm; its project's owner+// may watch it, and the Mac's owner neither watches nor types. On the project owner's own machine nothing changes.+describe('the terminal of a Product Manager in a Team account', () => {+ async function running(machineId: string) {+ const f = swarm()+ // Public, so the Mac's owner reads the project as every member does.+ f.run({ type: 'project.sharing', projectId: f.app.projectId, visibility: 'public', memberIds: [] })+ const startId = f.lead(machineId).result.startId as string+ const pool = f.state.starts!.find(s => s.id === startId)!.request.machineId+ const contribution = { machineOwnerId: f.machine(pool).contributorId, contributorId: f.machine(pool).contributorId, hostGrant: null }+ const pm = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, { contribution }).result.agentId as string+ const { canWatchAgent } = await import('./projects.js')+ const watch = (actor: Actor) => canWatchAgent(f.state, actor, f.state.agents.find(a => a.id === pm)!)+ const screen = (actor: Actor) => refusal(() => f.run({ type: 'agent.screen', agentId: pm, scrollback: 50 }, actor))?.code ?? 'ok'+ const input = (actor: Actor) => refusal(() => f.run({ type: 'agent.input', agentId: pm, text: 'ls ~' }, actor))?.code ?? 'ok'+ return { f, pm, watch, screen, input }+ }++ it('its project\'s owner watches it but cannot type in it', async () => {+ const t = await running('mate-mac')+ expect(t.watch(owner)).toBe(true)+ expect(t.screen(owner)).toBe('ok')+ expect(t.input(owner)).toBe('TERMINAL_PRIVATE')+ })++ it('the Mac\'s owner neither watches it nor reads or types in it', async () => {+ const t = await running('mate-mac')+ expect(t.watch(mate)).toBe(false)+ expect(t.screen(mate)).toBe('TERMINAL_PRIVATE')+ expect(t.input(mate)).toBe('TERMINAL_PRIVATE')+ })++ it('is known by its machine, however it joined: a Lead added by hand in a Team account is held the same way', () => {+ const f = swarm()+ f.run({ type: 'project.sharing', projectId: f.app.projectId, visibility: 'public', memberIds: [] })+ const home = f.state.conversations.find(c => c.id === f.app.conversationId)!+ f.state.agents.push({ id: 'added-pm', machineId: 'mate-team', harnessId: 'h', projectId: f.app.projectId, machineOwnerId: 'mate', contributorId: 'mate',+ membershipGeneration: f.state.people.find(p => p.id === 'mate')!.generation, hostGrant: null, name: 'PM', configuration: config })+ home.agentIds.push('added-pm'); home.leadId = 'added-pm'+ const code = (actor: Actor, command: Command) => refusal(() => f.run(command, actor))?.code ?? 'ok'+ expect(code(owner, { type: 'agent.screen', agentId: 'added-pm', scrollback: 50 })).toBe('ok')+ expect(code(owner, { type: 'agent.input', agentId: 'added-pm', text: 'ls' })).toBe('TERMINAL_PRIVATE')+ expect(code(mate, { type: 'agent.screen', agentId: 'added-pm', scrollback: 50 })).toBe('TERMINAL_PRIVATE')+ })++ // Security review 2 of #2089: a sibling worker there is the same macOS user, and reads people's chats with it.+ it('while it holds the account, nobody types in any agent there: its project\'s workers neither', async () => {+ const t = await running('mate-mac')+ const group = t.f.run({ type: 'conversation.create', projectId: t.f.app.projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId as string+ t.f.run({ type: 'agent.add', conversationId: group, machineId: 'mate-team', harnessId: 'sibling', name: 'Sibling', configuration: config, lead: false }, owner,+ { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } })+ const sibling = t.f.state.agents.find(a => a.harnessId === 'sibling')!.id+ const code = (actor: Actor, command: Command) => refusal(() => t.f.run(command, actor))?.code ?? 'ok'+ expect(code(owner, { type: 'agent.input', agentId: sibling, text: 'cat ~/.claude/projects/*' })).toBe('TERMINAL_PRIVATE')+ expect(code(owner, { type: 'agent.screen', agentId: sibling, scrollback: 50 })).toBe('ok')+ })++ it('stays held when its machine row is gone: the rules never fall back to the old ones', async () => {+ const t = await running('mate-mac')+ expect(t.f.state.agents.find(a => a.id === t.pm)).toMatchObject({ teamAccount: true })+ t.f.state.machines = t.f.state.machines!.filter(m => m.machineId !== 'mate-team')+ expect(t.input(owner)).toBe('TERMINAL_PRIVATE')+ expect(t.screen(mate)).toBe('TERMINAL_PRIVATE')+ })++ it('on the project owner\'s own machine, its owner still reads and types in it', async () => {+ const t = await running('owner-mac')+ expect(t.screen(owner)).toBe('ok')+ expect(t.input(owner)).toBe('ok')+ expect(t.input(mate)).toBe('TERMINAL_PRIVATE')+ })+})++// Every agent in a Team account runs as one macOS user and can read the others' files, the Product Manager's saved+// sessions with people's private chats among them. So a Team account hosting a Product Manager serves only its project.+describe('a Team account hosting a Product Manager', () => {+ const other = (f: ReturnType<typeof swarm>) => {+ const web = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }+ const group = f.run({ type: 'conversation.create', projectId: web.projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId as string+ const request = { conversationId: group, machineId: 'mate-mac', engine: 'claude', name: 'Builder', cwd: `/swarm/${web.projectId}`, worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const pooled = { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } }+ return { start: () => f.run({ type: 'agent.start', request }, owner, pooled), web }+ }++ it('takes no other project\'s new work while the Product Manager starts or runs there', () => {+ const f = swarm(), web = other(f)+ f.lead('mate-mac')+ expect(refusal(() => web.start())).toMatchObject({ code: 'TEAM_ACCOUNT_HELD',+ message: 'The Harness Team account on MacBook Pro runs another project\'s Product Manager, so it takes only that project\'s work for now.' })+ })++ it('is not where a Product Manager goes while another project\'s agents run there', () => {+ const f = swarm(), web = other(f)+ web.start()+ expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'TEAM_ACCOUNT_BUSY',+ message: 'The Harness Team account on MacBook Pro runs other projects\' agents, so it cannot host this Product Manager now.' })+ // From the queue it goes to the next free machine instead.+ expect(f.lead(null).result).toMatchObject({ machineId: 'owner-mac' })+ })++ it('holds an agent added by hand as it holds a start', () => {+ const f = swarm()+ const web = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }+ const add = (conversationId: string, harnessId: string, lead: boolean) => f.run({ type: 'agent.add', conversationId, machineId: 'mate-team', harnessId,+ name: harnessId, configuration: config, lead }, mate, { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } })+ f.lead('mate-mac')+ expect(refusal(() => add(web.conversationId, 'web-worker', false))?.code).toBe('TEAM_ACCOUNT_HELD')+ // The other way round: another project's agent there first, a Product Manager added by hand is refused.+ const g = swarm()+ const web2 = g.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }+ const group = g.run({ type: 'conversation.create', projectId: web2.projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId as string+ const pooled = { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } }+ g.run({ type: 'agent.add', conversationId: group, machineId: 'mate-team', harnessId: 'web-worker', name: 'W', configuration: config, lead: false }, mate, pooled)+ expect(refusal(() => g.run({ type: 'agent.add', conversationId: g.app.conversationId, machineId: 'mate-team', harnessId: 'pm', name: 'PM',+ configuration: config, lead: true }, owner, pooled))?.code).toBe('TEAM_ACCOUNT_BUSY')+ // And one added by hand there is marked as in a Team account.+ expect(g.state.agents.find(a => a.harnessId === 'web-worker')).toMatchObject({ teamAccount: true })+ })++ // Security re-check 2 of #2089: the hold went the moment the Product Manager left the roster, before its host deleted its+ // saved session there. It stays until the host confirms the close, which it does only once that data is deleted.+ it('stays held after its Product Manager is removed, until its host confirms its data is gone, and says so if that lasts', async () => {+ const { sweepLiveness, PURGE_NOTICE_MS } = await import('./liveness.js')+ const f = swarm(), web = other(f)+ const startId = f.lead('mate-mac').result.startId as string+ const contribution = { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null }+ const pm = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, { contribution }).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null }, owner, { contribution })+ f.run({ type: 'project.delete', projectId: f.app.projectId })+ expect(f.state.agents.some(a => a.id === pm)).toBe(false)+ expect(refusal(() => web.start())?.code).toBe('TEAM_ACCOUNT_HELD')+ // Still not confirmed after a while: its project's conversation is gone with it, so the Swarm's Lead conversation hears.+ const later = sweepLiveness(f.state, NOW + PURGE_NOTICE_MS + MINUTE)+ expect(later.map(m => [m.conversationId, m.source])).toEqual([['lead', { kind: 'system' }]])+ expect(later[0]!.text).toBe('The saved session of a removed agent that held people\'s private chats, on MacBook Pro, is not deleted yet, so its Harness Team account takes no other project\'s work until it is.')+ expect(sweepLiveness(f.state, NOW + PURGE_NOTICE_MS + 2 * MINUTE)).toEqual([])+ f.run({ type: 'agent.sessionClosed', agentId: pm, harnessId: 'pm' }, mate)+ expect(web.start().result.startId).toBeTruthy()+ })++ it('leaves the project owner\'s own machine as it is', () => {+ const f = swarm()+ f.lead('owner-mac')+ const web = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string }+ const group = f.run({ type: 'conversation.create', projectId: web.projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId as string+ expect(f.run({ type: 'agent.start', request: { conversationId: group, machineId: 'owner-mac', engine: 'claude', name: 'Builder', cwd: `/swarm/${web.projectId}`,+ worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } }, owner,+ { contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null } }).result.startId).toBeTruthy()+ })+})diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.tsnew file mode 100644index 000000000..3b4d3ac1f--- /dev/null+++ b/backend/src/superTabs/leadStart.ts@@ -0,0 +1,190 @@+/** A project's Product Manager started by the Swarm on one of its machines (Dee, 10-29, option B), as a Buddy's start is+ * (buddies.ts): recorded on the machine's contribution and launched by its host. On another person's Mac it runs only in+ * that Mac's Harness Team account, never as the Mac's owner, whatever the Swarm's switch (machines.ts teamAccountRequired)+ * says for workers: a Product Manager reads people's private chats. With no machine named, it waits for the first free+ * one. Desktop's own-machine flow (project.create, a local start, agent.add) is unchanged. */+import { admitMachineStart, failTeamWork, machineContribution, machineSlots, projectFolder, projectsOnMachine, teamAccountPool, teamAccountSwarm, teamPoolOf, teamWorkRefusal,+ type ContributedMachine } from './machines.js'+import { actorKey, fail, person, stableId, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'+import { mutableProjects, projectsOf, type SwarmProject } from './projects.js'+import { failureNotice, publicReason } from './startFailure.js'++/** What a host reports it can launch: a Product Manager. A host from before it is never given one. */+export const LEAD_CAPABILITY = 'leadStart'+export const LEAD_NAME = 'Product Manager'+export const LEAD_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 85,+ tools: ['git'], devices: [], quotaRequired: false }++/** Where the project's Product Manager is: waiting for a machine, starting on one, started, or failed with the reason. */+export interface LeadPlacement {+ status: 'waiting' | 'starting' | 'started' | 'failed'+ requestedAt: number+ requestedBy: { personId: string; generation: string }+ request: LeadRequest+ /** The machine the person named, or null: the first free one. */+ chosen: string | null+ machineId?: string+ machineName?: string+ startId?: string+ reason?: string+ /** Machines a start from the queue already failed on, tried again only once no other is free. */+ skipped?: string[]+ /** How many starts from the queue failed, and when it is placed again: each wait twice the last (security review 1 of+ * #2089: one that kept failing was placed again at every machine reading, each failure a row in its conversation). */+ failures?: number+ retryAt?: number+}+/** A Product Manager from the queue gives up after this many failed starts, and says so once. */+export const LEAD_QUEUE_ATTEMPTS = 3+const RETRY_BASE_MS = 60_000, RETRY_MAX_MS = 15 * 60_000+/** `repositoryUrl`: the address its folder is cloned from, recorded for a project that has none yet. */+export interface LeadRequest { engine: string; model?: string; effort?: string; branchRef?: string; repositoryUrl?: string }++export interface LeadContext {+ now: number+ teamMachines?: readonly string[]+ otherWorkspaceMachines?: readonly string[]+ teamAccountsIdle?: boolean+}++/** The contribution [project]'s Product Manager runs in when placed on [machineId]: the machine itself for its own owner,+ * else the Mac's Harness Team account, refused with that account's reason. Never the Mac's owner's account. */+function leadPool(state: SuperTabState, project: SwarmProject, machineId: string, context: LeadContext): ContributedMachine {+ const named = machineContribution(state, machineId) ?? fail('MACHINE_NOT_LISTED', 'Add this machine to the Swarm first.', 403)+ if (named.contributorId === project.ownerId) return named+ const teamMachines = context.teamMachines ?? []+ // With no GitHub App, or outside the Swarms Team accounts are tried in, a Team account takes no work (machines.ts+ // teamMachineFor) and the Mac would run it itself: refused, where a worker would go ahead.+ if (context.teamAccountsIdle || !teamAccountSwarm(state)) {+ fail('TEAM_ACCOUNT_REQUIRED', `Harness Team accounts take no work in this Swarm yet, so ${named.name} runs only its owner's projects.`, 403)+ }+ const pool = named.hostMachineId ? named : teamPoolOf(state, named, teamMachines) ?? named+ const refusal = teamWorkRefusal(pool, context.now, teamMachines.includes(pool.machineId), true,+ (context.otherWorkspaceMachines ?? []).includes(pool.machineId))+ if (refusal) failTeamWork(refusal)+ return pool+}++/** Records the start of [project]'s Product Manager on [machineId] for [by], and marks the project starting. Refuses, and+ * changes nothing, when that machine cannot take it now. */+export function placeLead(state: SuperTabState, project: SwarmProject, by: Person, machineId: string, request: LeadRequest,+ startId: string, context: LeadContext): AgentStart {+ const pool = leadPool(state, project, machineId, context)+ const start: AgentStartRequest = { conversationId: project.leadConversationId, machineId: pool.machineId, engine: request.engine,+ ...(request.model ? { model: request.model } : {}), ...(request.effort ? { effort: request.effort } : {}), name: LEAD_NAME,+ cwd: projectFolder(pool, project), worktree: true, ...(request.branchRef ? { branchRef: request.branchRef } : {}),+ requirements: LEAD_REQUIREMENTS, leadFor: { projectId: project.id, personId: by.id, generation: by.generation } }+ admitMachineStart(state, start, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)+ // Its Team account will serve only this project (machines.ts productManagerOn), so not one running another's work now.+ if (teamAccountPool(pool) && [...projectsOnMachine(state, pool.machineId)].some(id => id !== project.id)) {+ fail('TEAM_ACCOUNT_BUSY', `The Harness Team account on ${pool.name} runs other projects' agents, so it cannot host this ${LEAD_NAME} now.`, 409)+ }+ if (!pool.observation?.capabilities?.includes(LEAD_CAPABILITY)) {+ fail('HOST_OUTDATED', `Update Harness on ${pool.name} to run a ${LEAD_NAME} there.`, 409)+ }+ state.starts ??= []+ if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')+ const contributor = person(state, pool.contributorId)+ const recorded: AgentStart = { poolGeneration: pool.generation, id: startId, creationId: `super-${startId}`,+ actorKey: actorKey({ kind: 'person', userId: by.id, email: by.email }), contributorId: contributor.id,+ membershipGeneration: contributor.generation, machineOwnerId: pool.contributorId, hostGrant: null, request: start,+ harnessId: null, dispatched: false, error: null, requestedAt: context.now }+ state.starts.push(recorded)+ project.repository ??= { machineId: pool.machineId, cwd: start.cwd, repositoryUrl: request.repositoryUrl ?? null }+ const { reason: _reason, ...placement } = project.lead!+ project.lead = { ...placement, status: 'starting', machineId: pool.machineId, machineName: pool.name, startId }+ return recorded+}++/** A start of [project]'s Product Manager not yet running or failed. */+export const leadStarting = (state: SuperTabState, projectId: string): AgentStart | undefined =>+ state.starts?.find(s => s.request.leadFor?.projectId === projectId && !s.harnessId && !s.error)++const placementOf = (state: SuperTabState, start: AgentStart): LeadPlacement | undefined => {+ const lead = start.request.leadFor && projectsOf(state).find(p => p.id === start.request.leadFor!.projectId)?.lead+ return lead?.startId === start.id ? lead : undefined+}++/** Its agent [agentId] joined the project's Lead conversation [home]: it leads it, unless a Lead was added there by hand+ * meanwhile, which stays. The line its conversation shows. */+export function leadJoined(state: SuperTabState, start: AgentStart, home: Conversation, agentId: string): string {+ if (!home.leadId || !home.agentIds.includes(home.leadId)) home.leadId = agentId+ const placement = placementOf(state, start)+ if (placement) placement.status = 'started'+ return `${LEAD_NAME} started on ${placement?.machineName ?? state.machines?.find(m => m.machineId === start.request.machineId)?.name ?? 'its machine'}.`+}++/** Its start failed with [reason] at [now]: on the machine its person chose, the project says why and waits for them; placed+ * from the queue, it waits for another machine, longer after each failure, and gives up after LEAD_QUEUE_ATTEMPTS. The line+ * its conversation shows, once, when it stops trying; null while it still waits. */+export function leadStartFailed(state: SuperTabState, start: AgentStart, reason: string, now: number): string | null {+ const placement = placementOf(state, start)+ if (!placement) return null+ delete placement.startId+ // Every reader of the project reads its placement: the reason a group member may read, never the host's own words, which+ // can name a folder on the machine or a token problem (startFailure.ts). Its asker reads those on the start.+ const shown = publicReason(reason)+ if (placement.chosen !== null) {+ Object.assign(placement, { status: 'failed', reason: shown })+ return failureNotice(start.request.name, reason)+ }+ const failures = (placement.failures ?? 0) + 1+ delete placement.machineId+ delete placement.machineName+ if (failures >= LEAD_QUEUE_ATTEMPTS) {+ delete placement.retryAt+ Object.assign(placement, { status: 'failed', reason: shown, failures })+ return `The ${LEAD_NAME} could not start after ${failures} tries. The last one: ${shown} Start it again when a machine is ready.`+ }+ Object.assign(placement, { status: 'waiting', reason: shown, failures, retryAt: now + Math.min(RETRY_BASE_MS * 2 ** (failures - 1), RETRY_MAX_MS),+ skipped: [...new Set([...placement.skipped ?? [], start.request.machineId])].slice(-16) })+ return null+}++export const WAITING_TEXT = `Waiting for a machine to start the ${LEAD_NAME}.`++/** lead.start: [project]'s Product Manager on [machineId], refused with the reason when it cannot run there now; or, with+ * none named, on the first free machine, else waiting for one (placeWaitingLeads). A request already waiting is replaced. */+export function requestLead(state: SuperTabState, project: SwarmProject, by: Person, machineId: string | null, request: LeadRequest,+ operationId: string, context: LeadContext): { startId: string; machineId: string } | { waiting: true } {+ project.lead = { status: 'waiting', requestedAt: context.now, requestedBy: { personId: by.id, generation: by.generation }, request, chosen: machineId }+ const start = machineId ? placeLead(state, project, by, machineId, request, operationId, context) : placeOnFree(state, project, by, operationId, context)+ return start ? { startId: start.id, machineId: start.request.machineId } : { waiting: true }+}++/** The machines a waiting Product Manager is tried on, in order: the project owner's own, then the most free agent slots, and+ * last those a start from the queue already failed on. A Mac's Harness Team account is reached through its Mac. */+function candidates(state: SuperTabState, project: SwarmProject): string[] {+ const skipped = project.lead?.skipped ?? []+ const rank = (m: ContributedMachine) => [skipped.includes(m.machineId) ? 1 : 0, m.contributorId === project.ownerId ? 0 : 1, machineSlots(state, m) - m.maxAgents] as const+ return (state.machines ?? []).filter(m => !m.hostMachineId).map(m => ({ m, r: rank(m) }))+ .sort((a, b) => a.r[0] - b.r[0] || a.r[1] - b.r[1] || a.r[2] - b.r[2]).map(({ m }) => m.machineId)+}++function placeOnFree(state: SuperTabState, project: SwarmProject, by: Person, startId: string, context: LeadContext): AgentStart | null {+ for (const machineId of candidates(state, project)) {+ try { return placeLead(state, project, by, machineId, project.lead!.request, startId, context) } catch (error) {+ // Each refusal comes before anything is written (placeLead), so the next machine sees the state unchanged.+ if (!(error instanceof SuperTabError)) throw error+ }+ }+ return null+}++/** On a machine's reading: each project whose Product Manager waits starts on the first free machine. The ids of those+ * placed. Nothing is read or written for a Swarm with none waiting. */+export function placeWaitingLeads(state: SuperTabState, context: LeadContext): string[] {+ const waiting = projectsOf(state).filter(p => p.lead?.status === 'waiting' && !(p.lead.retryAt !== undefined && p.lead.retryAt > context.now))+ if (!waiting.length || state.paused) return []+ const placed: string[] = []+ for (const { id } of waiting) {+ const project = mutableProjects(state).find(p => p.id === id)!, lead = project.lead!+ const by = state.people.find(p => p.id === lead.requestedBy.personId && p.generation === lead.requestedBy.generation)+ if (!by) {+ Object.assign(lead, { status: 'failed', reason: 'The person who asked for it left the Swarm.' })+ continue+ }+ if (placeOnFree(state, project, by, stableId('lead-start', project.id, String(lead.requestedAt), String(context.now)), context)) placed.push(project.id)+ }+ return placed+}diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 5b9f18fc7..aac672032 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -1,9 +1,10 @@import { activeWork, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,type SuperTabState, type TaskLiveness } from './model.js'import { agentDisplayName } from './agentNames.js'-import { failureNotice, STILL_PREPARING_SUFFIX, STOPPED_REPORTING_SUFFIX, TIMED_OUT_SUFFIX } from './startFailure.js'+import { failureNotice, LEAD_PICKUP_SUFFIX, STILL_PREPARING_SUFFIX, STOPPED_REPORTING_SUFFIX, TIMED_OUT_SUFFIX } from './startFailure.js'import { leadOf, toLead } from './terminal.js'import { MACHINE_FRESH_MS } from './machines.js'+import { leadStartFailed } from './leadStart.js'import { ledProject, projectsOf } from './projects.js'import { waitedOn } from './leaderboard/record.js'@@ -176,10 +177,42 @@ function buddyNotice(state: SuperTabState, start: AgentStart): MessageDraft[] {text: `Could not start ${start.request.name}: ${start.error!}`, source: { kind: 'start-timeout', startId: start.id } }]}+/** A Product Manager's start that stopped trying ([text], leadStart.ts), said once as a system row of its project's+ * conversation, written under the person who asked for it as a machine's removal is (machines.ts removalEnded). Nothing while+ * it still waits for a machine. */+function leadNotice(state: SuperTabState, start: AgentStart, text: string | null): MessageDraft[] {+ const asker = start.request.leadFor!+ const person = state.people.find(p => p.id === asker.personId && p.generation === asker.generation)+ if (!text || !person || !state.conversations.some(c => c.id === start.request.conversationId)) return []+ return [{ id: stableId('start-timeout', start.id), conversationId: start.request.conversationId, replyTo: null, recipients: [],+ author: { kind: 'person', id: person.id, name: person.email, membershipGeneration: person.generation },+ text, source: { kind: 'system' } }]+}+/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {- return [...loseTasks(state, now), ...failStalledStarts(state, now)]+ return [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now)]+}++/** How long a removed confidential session's data may take to be deleted in its Team account before the Swarm says so. */+export const PURGE_NOTICE_MS = 15 * 60_000++/** A removed confidential session whose host has not confirmed its data deleted (commands.ts removeAgent `heldFor`): its+ * Team account keeps serving only its project, and its project's conversation hears once, or the Swarm's first one when+ * its project went with it. Its host keeps trying (cli superTabs/host.ts endSession). */+function unpurged(state: SuperTabState, now: number): MessageDraft[] {+ const owner = state.people.find(p => p.id === state.ownerId)+ return (state.closingSessions ?? []).flatMap(closing => {+ if (!closing.heldFor || closing.noticed || closing.since === undefined || now - closing.since <= PURGE_NOTICE_MS || !owner) return []+ closing.noticed = true+ const project = projectsOf(state).find(p => p.id === closing.heldFor) ?? projectsOf(state)[0]+ if (!project || !state.conversations.some(c => c.id === project.leadConversationId)) return []+ return [{ id: stableId('unpurged', closing.agentId, closing.harnessId), conversationId: project.leadConversationId, replyTo: null, recipients: [],+ author: { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation },+ text: `The saved session of a removed agent that held people's private chats, on ${machineName(state, closing.machineId)}, is not deleted yet, so its Harness Team account takes no other project's work until it is.`,+ source: { kind: 'system' } }]+ })}/** The Lead's own time checks: those above, then each task's state, waking the Lead for those that just stalled. Only the@@ -309,10 +342,14 @@ export const BUDDY_PICKUP_MS = 5 * 60_000function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {return (state.starts ?? []).flatMap(start => {- if (start.request.buddyOf && !start.dispatched && !start.harnessId && !start.error && start.requestedAt !== undefined+ if ((start.request.buddyOf || start.request.leadFor) && !start.dispatched && !start.harnessId && !start.error && start.requestedAt !== undefined&& now - start.requestedAt > BUDDY_PICKUP_MS) {const report = state.machines?.find(m => m.machineId === start.request.machineId)?.observationif (!report || now - report.receivedAt > MACHINE_FRESH_MS) return []+ if (start.request.leadFor) {+ start.error = `${machineName(state, start.request.machineId)}${LEAD_PICKUP_SUFFIX}`+ return leadNotice(state, start, leadStartFailed(state, start, start.error, now))+ }start.error = `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`return buddyNotice(state, start)}@@ -324,6 +361,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {if (named && !silent && now - start.dispatchedAt <= START_PREPARE_MS) return []const machine = machineName(state, start.request.machineId)start.error = `${machine}${!named ? TIMED_OUT_SUFFIX : silent ? STOPPED_REPORTING_SUFFIX : STILL_PREPARING_SUFFIX}`+ if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error, now))// Never a lookup that throws: these checks run inside every machine's report.if (start.request.buddyOf) return buddyNotice(state, start)const group = state.conversations.find(c => c.id === start.request.conversationId)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex ceefda36d..27eae5abf 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -2,7 +2,8 @@ import { z } from 'zod'import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'import { activeWork, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'import { WORKSPACE_LABEL } from './workspaces.js'-import { agentProjectId, canReadProject, groupProject, ledProject, projectsOf, type SwarmProject } from './projects.js'+import { agentProjectId, canReadProject, groupProject, ledProject, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'+export { teamAccountPool } from './projects.js'import { conversation } from './model.js'/** An explicit grant for this tab and project. It never creates a MachineShare. */@@ -127,6 +128,9 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16* the engine), as of this report. Such a start waits past the 3 minutes while reports keep naming it (liveness.ts);* the store keeps only this machine's own launched starts. Absent from hosts before it, whose starts get 3 minutes. */preparingStartIds: z.array(z.string().min(1).max(160)).max(100).optional(),+ /** What this host can launch beyond workers: `leadStart`, a project's Product Manager (leadStart.ts). Absent from hosts+ * before it, which are never given one. */+ capabilities: z.array(z.string().regex(/^[a-zA-Z]{1,40}$/)).max(16).optional(),}).strict()export type MachineObservation = z.infer<typeof machineObservationSchema>@@ -293,6 +297,26 @@ export function machineTeamWork(state: SuperTabState, pool: ContributedMachine,return teamWorkRefusal(subject, now, teamMachines.includes(subject.machineId), teamAccountRequired(state), otherWorkspaceMachines.includes(subject.machineId))}+/** The projects with work on [machineId]: its agents' and its pending starts'. */+export function projectsOnMachine(state: SuperTabState, machineId: string): Set<string> {+ const pending = (state.starts ?? []).filter(s => s.request.machineId === machineId && !s.harnessId && !s.error)+ .map(s => s.request.leadFor?.projectId ?? groupProject(state, conversation(state, s.request.conversationId)).id)+ return new Set([...state.agents.filter(a => a.machineId === machineId).map(a => agentProjectId(state, a)), ...pending])+}++/** The project whose Product Manager runs, or is starting, on [machineId]; null when none does. In a Harness Team account it+ * serves only that project: every agent there is one macOS user, which reads the others' files, the Product Manager's+ * saved sessions with people's private chats among them (#895). */+export function productManagerOn(state: SuperTabState, machineId: string): string | null {+ const led = state.agents.find(a => a.machineId === machineId && ledProject(state, a.id))+ if (led) return ledProject(state, led.id)!.id+ // One removed whose host has not yet confirmed its data there is deleted (commands.ts removeAgent).+ const closing = state.closingSessions?.find(c => c.machineId === machineId && c.heldFor)+ if (closing) return closing.heldFor!+ return state.starts?.find(s => s.request.machineId === machineId && s.request.leadFor && !s.harnessId && !s.error)?.request.leadFor!.projectId ?? null+}++/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not* its contributor's own and the Mac has one in this Swarm, else the machine named. */export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[]): string {@@ -505,6 +529,10 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartRequeif (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')const project = groupProject(state, conversation(state, request.conversationId))if (!pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')+ const held = teamAccountPool(pool) ? productManagerOn(state, pool.machineId) : null+ if (held && held !== project.id) {+ fail('TEAM_ACCOUNT_HELD', `The Harness Team account on ${pool.name} runs another project's Product Manager, so it takes only that project's work for now.`, 403)+ }// Before the request's own fields: a machine that takes none of this project's work says so first. A Buddy is its owner's// own agent on their own machine (commands.ts buddy.create), as a Lead is: teammates' work rules do not apply to it.if (!request.buddyOf) requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex ffdcbd8dd..c516cd876 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -77,6 +77,9 @@ export interface Agent {/** A Buddy (buddies.ts): the person it brainstorms with, at the membership they added it in. Its role stays a builder's* for older readers; this is what makes it a Buddy, and what refuses it every command but its own chat and proposals. */buddyOf?: { personId: string; generation: string }+ /** Joined on a Harness Team account's machine: kept, so a machine row that went never brings back the rules of an+ * ordinary machine (projects.ts teamSessionAccess, security re-review of #2089). */+ teamAccount?: true}export type AgentRole = 'builder' | 'reviewer'export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'@@ -99,6 +102,9 @@ export interface AgentStartRequest {requirements: { memoryBytes: number; diskBytes: number; maxCpuPercent: number; tools: string[]; devices: string[]; quotaRequired: boolean }/** A Buddy's start (buddies.ts): written by buddy.create alone, never taken from an agent.start. */buddyOf?: { personId: string; generation: string }+ /** A project's Product Manager's start (leadStart.ts): written by lead.start alone, never taken from an agent.start. Its+ * agent becomes the Lead of the project's Lead conversation once it runs. */+ leadFor?: { projectId: string; personId: string; generation: string }}export interface AgentStart {poolGeneration?: string@@ -304,7 +310,10 @@ export interface SuperTabState {/** Native stop receipts survive late replaceable machine observations. */releasedHarnesses?: Array<{ machineId: string; harnessId: string }>/** Sessions of removed agents their host closes, listed to that host until it says they closed (agent.sessionClosed). */- closingSessions?: Array<{ agentId: string; machineId: string; harnessId: string; machineOwnerId: string }>+ /** `heldFor`: a confidential session in a Harness Team account, whose project the account keeps serving alone until its+ * host confirms the close, which it does once its saved session there is deleted (machines.ts productManagerOn); `since`+ * when it was removed, and `noticed` once the Swarm said it lasts (liveness.ts). */+ closingSessions?: Array<{ agentId: string; machineId: string; harnessId: string; machineOwnerId: string; heldFor?: string; since?: number; noticed?: true }>/** Removed machines whose host still has to clean up (machines.ts expireRemovals), listed only to that host. */machineCleanups?: import('./machines.js').MachineCleanup[]/** Conversations of a kind a later release added, set aside unchanged by a release that does not know it (parkLaterConversations). */diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 822ceca3f..3544b3aac 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -35,6 +35,8 @@ export interface SwarmProject {skillSet?: SkillSet/** The project's custom set, kept when the project switches away from it. */roles?: ProjectRole[]+ /** Its Product Manager started by the Swarm on one of its machines, or waiting for one (leadStart.ts). */+ lead?: import('./leadStart.js').LeadPlacement}export const skillModeOf = (project: SwarmProject): SkillMode => project.skillMode ?? 'orchestration'@@ -208,7 +210,34 @@ export const watchClosed = (state: SuperTabState, target: Agent, elsewhere = fal/** Who may watch an agent's terminal: observe it or hold a share of it. Reading or typing in it on request is closed by* `isConfidential` alone (terminal.ts mayDrive). Any other agent: every reader of its project, as before. */export function canWatchAgent(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false): boolean {- return canReadAgent(state, actor, target) && (!watchClosed(state, target, elsewhere) || ownSession(actor, target))+ if (!canReadAgent(state, actor, target)) return false+ const team = teamSessionAccess(state, actor, target, elsewhere)+ if (team) return team !== 'none'+ return !watchClosed(state, target, elsewhere) || ownSession(actor, target)+}++/** Whether [pool] is a Harness Team account: a Mac's (it names its Mac) or a machine used only for agents (its reading came+ * from a team session). */+export const teamAccountPool = (pool: import('./machines.js').ContributedMachine | null | undefined): boolean =>+ !!pool && (!!pool.hostMachineId || pool.observation?.sessionKind === 'team')++/** Whether [target] runs in a Harness Team account: read from its machine, whichever way it joined (security review 1 of+ * #2089), and kept from when it joined one, so a machine row that went never brings back the old rules (its re-review). */+export const onTeamAccount = (state: SuperTabState, target: Agent): boolean =>+ !!target.teamAccount || teamAccountPool(state.machines?.find(m => m.machineId === target.machineId))++/**+ * A confidential session in a Harness Team account (#895 R2): every teammate's work there runs as one macOS user whose+ * folders hold other projects' clones, so typing in it is a shell that reads them. Nobody drives it through the Swarm. Its+ * project's owner may watch it; its machine's owner neither watches nor drives it, as a member or as its machine's person.+ * Other members watch it as they watch any confidential session (watchClosed). Null for every other session, and for+ * agents, which keep their own rules (mayDrive).+ */+export function teamSessionAccess(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false): 'watch' | 'none' | 'member' | null {+ if (!onTeamAccount(state, target) || actor.kind !== 'person' || !isConfidential(state, target, elsewhere)) return null+ if (actor.userId === projectOf(state, agentProjectId(state, target)).ownerId) return 'watch'+ if (actor.userId === target.machineOwnerId) return 'none'+ return watchClosed(state, target, elsewhere) ? 'none' : 'member'}/** Who could watch an agent's terminal before a commit and cannot after it (canWatchAgent, by the session the observer relay@@ -222,7 +251,7 @@ export function watchersLost(before: SuperTabState, after: SuperTabState): Arrayconst watchers = (state: SuperTabState, target: Agent) => {const closed = watchClosed(state, target)return state.people.map(p => ({ kind: 'person' as const, userId: p.id, email: p.email }))- .filter(actor => canReadAgent(state, actor, target) && (!closed || ownSession(actor, target)))+ .filter(actor => canWatchAgent(state, actor, target))}return before.agents.flatMap(target => {const was = watchers(before, target)diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 813baaa16..69bde8160 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -229,11 +229,15 @@ export interface HostPool {starts: AgentStart[]/** Buddies' starts (buddies.ts), apart from `starts`: a host from before Buddies would launch one as a Builder. */buddyStarts?: AgentStart[]+ /** Product Managers' starts (leadStart.ts), apart from `starts` for the same reason. */+ leadStarts?: AgentStart[]projects?: Array<{ id: string; leadConversationId: string; repository?: unknown; conversationIds: string[] }>localGrid?: stringreservations: Array<{ harnessId: string; generation: string }>harnessIds: string[]githubApp?: true+ /** The host may say what it launches beyond workers in its readings (leadStart.ts). */+ capabilitiesWanted?: true}/** HTTP 426 on GET /api/super-tabs, /:tabId, /hosts/:m, /hosts/:m/pools and /hosts/:m/assignments. */diff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.tsindex 837fc4d4e..805733383 100644--- a/backend/src/superTabs/read/host.ts+++ b/backend/src/superTabs/read/host.ts@@ -10,7 +10,7 @@ import { machineAlive } from '../../lib/prisma.js'import { isTeamSession } from '../../lib/teamSession.js'import { machineBillingAllowsDataPlane } from '../../lib/billingState.js'import { fail, type AgentStart, type SuperTabState } from '../model.js'-import { GrantReads, type SuperTabStore } from '../store.js'+import { GrantReads, TEAM_HOST_ONLY, TEAM_HOST_ONLY_MESSAGE, teamByRecord, type SuperTabStore } from '../store.js'import type { CacheView } from '../cache.js'import { readLastChangedAts, readMachines } from '../cachedReads.js'import { retryTransient } from '../retry.js'@@ -53,8 +53,8 @@ export class HostReads {const from = request.cursor && !request.full ? readCursor(request.cursor, 0, t0) : { reload: true as const }// Outside any transaction: each Swarm's signature and state come through the read cache (cache.ts), at stamps read once.const tx = this.db- await this.store.hostFor(tx, user, machineId)const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })+ await this.store.hostFor(tx, user, machineId, owned)if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)// Every agent's grant check of this read shares one read of each machine, share, contributor and Workspace membership.const grants = new GrantReads(owned)@@ -80,6 +80,8 @@ export class HostReads {const inputs = await cached.get(tabId, 'host:inputs', 'main', () => this.inputs(tx, tabId))if (!full && held && inputs && held.slice(ROW_HASH) === inputs) { tabs.push({ tabId, lastChangedAt, etag: held, unchanged: true as const }); continue }const state = await this.tabState(tx, cached, tabId, machineId)+ // Its Team account alone hosts a machine this Swarm records as one, whatever its account row says now (store.ts).+ if (!isTeamSession(user) && teamByRecord(state, machineId)) fail(TEAM_HOST_ONLY, TEAM_HOST_ONLY_MESSAGE, 403)const rows = await hostTab(tabId, state, machineId, user, lastChangedAt, await this.lookups(tx, state, teams, grants))const etag = rows.etag + (inputs ?? '')// The host already holds these rows: say so instead of sending them again.diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.tsindex a0214c4e0..a4cab0a8c 100644--- a/backend/src/superTabs/read/hostRows.ts+++ b/backend/src/superTabs/read/hostRows.ts@@ -97,11 +97,13 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Authif (!contribution || contribution.contributorId !== user.sub) return nullconst pending = (state.starts ?? []).filter(s => s.request.machineId === machineId && s.poolGeneration === contribution.generation&& (!s.harnessId || !s.poolSettled) && !s.error)- // A host from before Buddies reads only `starts`, and would launch a Buddy as a Builder: it never sees one.- const starts = pending.filter(s => !s.request.buddyOf), buddyStarts = pending.filter(s => s.request.buddyOf)+ // A host from before Buddies reads only `starts`, and would launch a Buddy as a Builder: it never sees one. Nor a Product+ // Manager (leadStart.ts), which goes only to a host that said it starts one.+ const starts = pending.filter(s => !s.request.buddyOf && !s.request.leadFor), buddyStarts = pending.filter(s => s.request.buddyOf)+ const leadStarts = pending.filter(s => s.request.leadFor)const buddyChats = new Set(buddyStarts.map(s => s.request.conversationId))const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === machineId)- return { tabId, paused: state.paused, machine: contribution, starts, ...(buddyStarts.length ? { buddyStarts } : {}),+ return { tabId, paused: state.paused, machine: contribution, starts, ...(buddyStarts.length ? { buddyStarts } : {}), ...(leadStarts.length ? { leadStarts } : {}),...(contribution.scope === 'swarm' ? { projects: projectsOf(state).filter(p => pending.some(s =>groupProject(state, conversation(state, s.request.conversationId)).id === p.id)).map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,@@ -112,7 +114,10 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Authreservations: reservations.map(({ harnessId, generation }) => ({ harnessId, generation })),harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...reservations.map(r => r.harnessId),...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])],- ...(githubApp ? { githubApp: true as const } : {}) }+ ...(githubApp ? { githubApp: true as const } : {}),+ // Asks the host to say what it launches beyond workers (machines.ts `capabilities`): a host never sends a field this+ // server did not ask for, so an older server, which would refuse every reading with it, never sees it.+ capabilitiesWanted: true as const }}function assignments(tabId: string, state: SuperTabState, machineId: string, user: AuthUser) {diff --git a/backend/src/superTabs/startFailure.ts b/backend/src/superTabs/startFailure.tsindex 9245fb19a..49d5782db 100644--- a/backend/src/superTabs/startFailure.ts+++ b/backend/src/superTabs/startFailure.ts@@ -10,13 +10,19 @@ export const TIMED_OUT_SUFFIX = ' did not start it within 3 minutes'/** liveness.ts writes these after a machine named the start as preparing: past its limit, or with its reports stopped. */export const STILL_PREPARING_SUFFIX = ' was still preparing it after 15 minutes'export const STOPPED_REPORTING_SUFFIX = ' stopped reporting while preparing it'+/** liveness.ts writes this after a machine named a Product Manager's start that it never took (leadStart.ts). */+export const LEAD_PICKUP_SUFFIX = ' did not start this Product Manager. Update Harness on it, then start it again.'/** Each suffix the server writes after a machine name, with what a group member reads instead. */const TIMEOUTS: Array<[string, string]> = [[TIMED_OUT_SUFFIX, TIMED_OUT],[STILL_PREPARING_SUFFIX, 'Its machine was still preparing it after 15 minutes.'],- [STOPPED_REPORTING_SUFFIX, 'Its machine stopped reporting while preparing it.']]+ [STOPPED_REPORTING_SUFFIX, 'Its machine stopped reporting while preparing it.'],+ [LEAD_PICKUP_SUFFIX, 'Its machine did not start it. Harness there may need an update.']]/** Reasons the server writes itself, which name nothing (commands.ts removeMachine and machine.contribute). */export const MACHINE_REMOVED = 'Its machine was removed from the Swarm.'export const ABANDONED = 'Abandoned before it started.'+/** A Team account's host refusing a Codex Product Manager it cannot sign in (cli superTabs/start.ts): it names nothing of the+ * machine but its lack of the owner's relay, which its project reads (security re-check 3 of #2089). */+export const NO_PM_RELAY = 'The owner\'s subscription relay is not available on this machine, so a Codex Product Manager cannot sign in here.'/** A host's refusal for memory (cli superTabs/capacity.ts memoryShort): its numbers alone, which members already see in the* Machines view. Read only at the start of the reason, so nothing else a host wrote is ever told (Ken's MacBook Pro,@@ -24,7 +30,7 @@ export const ABANDONED = 'Abandoned before it started.'const MEMORY_SHORT = /^Not enough free memory: (\d+(?:\.\d)? GiB) free, (\d+(?:\.\d)? GiB) needed\./export function publicReason(error: string): string {- if (error === MACHINE_REMOVED || error === ABANDONED) return error+ if (error === MACHINE_REMOVED || error === ABANDONED || error === NO_PM_RELAY) return errorconst memory = MEMORY_SHORT.exec(error)if (memory) return `Its machine has only ${memory[1]} of memory free, and it needs ${memory[2]}.`return TIMEOUTS.find(([suffix]) => error.endsWith(suffix))?.[1] ?? MACHINE_FAILEDdiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 237e5bb6a..dbbed20d7 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -19,8 +19,9 @@ import { randomBytes } from 'node:crypto'import type { Readable } from 'node:stream'import { logger } from '../utils/logger.js'import { retryTransient } from './retry.js'+import { placeWaitingLeads } from './leadStart.js'import { buddyChatId } from './buddies.js'-import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'+import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'import { answersRequest, dirtyGroups, noteProjectReports, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'@@ -200,7 +201,8 @@ function grantsOf(state: SuperTabState, agentId: string, allowed: SuperTabDeliveconst grants: Record<string, AgentGrant> = {}for (const id of [agentId, ...allowed.filter(d => d.authorKind === 'agent').map(d => d.authorId)]) {const found = state.agents.find(a => a.id === id)- if (found) grants[id] = { contributorId: found.contributorId, machineId: found.machineId, machineOwnerId: found.machineOwnerId, hostGrant: found.hostGrant ?? null }+ if (found) grants[id] = { contributorId: found.contributorId, machineId: found.machineId, machineOwnerId: found.machineOwnerId, hostGrant: found.hostGrant ?? null,+ ...(onTeamAccount(state, found) ? { team: true as const } : {}) }}return { swarm: { workspaceId: state.workspaceId, environment: state.environment }, grants }}@@ -225,7 +227,7 @@ const POLLED_CAP = 5_000export const ABANDONED_START_MS = 15 * 60_000/** The commands that start, assign or route work, which read which of the tab's machines are Team machines. */-const TEAM_WORK_COMMANDS = new Set<Command['type']>(['agent.start', 'agent.startDispatch', 'work.assign', 'conversation.agent', 'route.record', 'route.override'])+const TEAM_WORK_COMMANDS = new Set<Command['type']>(['agent.start', 'lead.start', 'agent.startDispatch', 'work.assign', 'conversation.agent', 'route.record', 'route.override'])/** Starts on a not-yet-contributed machine that never dispatched, dated by their own operation receipt (starts carry no* time of their own). A dispatched start may have a native session coming, so it is never counted. */@@ -274,7 +276,8 @@ export interface DeliveriesWaiting { machineId: string; tabId: string; agentId:/** What of a Swarm an agent's grant is checked against (SuperTabStore.grantHolds). */export type SwarmGrant = Pick<SuperTabState, 'workspaceId' | 'environment'>/** What of an agent its grant is checked against: who lent which machine to whom, under which share grant. */-export type AgentGrant = Pick<Agent, 'contributorId' | 'machineId' | 'machineOwnerId' | 'hostGrant'>+/** `team`: the agent runs in a Harness Team account, by the Swarm's own record (projects.ts onTeamAccount). */+export type AgentGrant = Pick<Agent, 'contributorId' | 'machineId' | 'machineOwnerId' | 'hostGrant'> & { team?: true }/** A caller's last full delivery poll: when it succeeded and, when it found deliveries open, what it found. */export interface Polled {@@ -311,6 +314,14 @@ const routeDecisionOf = (command: Command): string | undefined => command.type =: 'decisionId' in command ? command.decisionId : 'routeDecisionId' in command ? command.routeDecisionId : undefinedconst machineKey = (environment: string, machineId: string, ownerId: string) => `machine:${environment}:${machineId}:${ownerId}`+/** Whether a Swarm's own record says [machineId] is a Harness Team account's: its pool names a Mac, or an agent there+ * joined as one (projects.ts onTeamAccount). An ordinary sign-in connecting as that computer resets its account row's mark,+ * never this (security re-check 2 of #2089). */+export const teamByRecord = (state: SuperTabState, machineId: string): boolean =>+ !!state.machines?.find(m => m.machineId === machineId)?.hostMachineId || state.agents.some(a => a.machineId === machineId && onTeamAccount(state, a))+/** A Team account's machine refused to its owner's own sign-in (notTeamMachine). */+export const TEAM_HOST_ONLY = 'TEAM_HOST_ONLY'+export const TEAM_HOST_ONLY_MESSAGE = 'Only this computer\'s Harness Team account runs its Swarm agents. Its owner\'s own sign-in cannot act for them.'/*** What agent grant checks read, kept for one request only. A host read checks every agent on its machine, mostly for the@@ -380,9 +391,29 @@ export class SuperTabStore {/** A host route of a team session must name its own machine. *//** Shared with the read API (superTabs/read, design section 7.2). */- async hostFor(tx: Transaction, user: AuthUser, machineId: string): Promise<void> {+ /** [owned]: the machine's account row for this sign-in, when the caller already read it (machineAlive), so it is read once.+ * [state]: a Swarm the request reads, whose own record of the machine counts too (teamByRecord). */+ async hostFor(tx: Transaction, user: AuthUser, machineId: string, owned?: Machine | null, state?: SuperTabState): Promise<void> {const team = await this.teamHost(tx, user)if (team !== null && team !== machineId) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ if (team === null) await this.notTeamMachine(user, async () => owned !== undefined ? owned+ : tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } }), !!state && teamByRecord(state, machineId))+ }++ /**+ * A Harness Team account's machine is hosted, and its agents spoken for, by its team session alone (security review 2 of+ * #2089). It is a machine of its Mac owner's account, so the owner's ordinary sign-in passed every host check, and could+ * read every chat its Product Manager can, claim its deliveries and post as it, past every rule the Swarm keeps for it.+ * [row]: the machine's account row, read once with the request's others; [flagged]: an agent that joined on one.+ */+ private async notTeamMachine(user: AuthUser, row: () => Promise<Pick<Machine, 'sessionKind' | 'hostMachineId'> | null>, flagged = false): Promise<void> {+ if (isTeamSession(user)) return+ // The row's own mark, which an ordinary sign-in connecting as that computer resets (lib/adapterWs.ts), and the Mac it+ // names, which it keeps; and what the Swarm itself recorded ([flagged], security re-check 2 of #2089).+ const machine = flagged ? null : await row()+ if (flagged || machine?.sessionKind === 'team' || !!machine?.hostMachineId) {+ fail(TEAM_HOST_ONLY, TEAM_HOST_ONLY_MESSAGE, 403)+ }}/** What only the person does: a team session has no person to be. */@@ -604,7 +635,11 @@ export class SuperTabStore {if (target.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)// ...and as an agent only one running on its own machine, never the person's agents elsewhere.if (team !== null && target.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)- await this.agentGrant(tx, state, target)+ const reads = new GrantReads()+ await this.agentGrant(tx, state, target, reads)+ // An agent of a Team account's machine is spoken for by that account alone, never its owner's own sign-in.+ await this.notTeamMachine(user, () => reads.once(machineKey(state.environment, target.machineId, target.machineOwnerId), () => tx.machine.findFirst({+ where: { machineId: target.machineId, userId: target.machineOwnerId, autonomousEnv: state.environment, ...machineAlive } })), onTeamAccount(state, target))return { kind: 'agent', agentId, machineOwnerId: user.sub }}@@ -1679,7 +1714,7 @@ export class SuperTabStore {}const refusal = now - row.createdAt.getTime() > TERMINAL_PICKUP_MS? 'The agent’s machine did not pick up the request within 10 seconds. It may be offline or asleep.'- : await this.terminalRefusal(tx, states.get(row.tabId)!, row)+ : await this.terminalRefusal(tx, states.get(row.tabId)!, row, isTeamSession(user))if (refusal) {const refused = await tx.superTabTerminalRequest.updateMany({ where: { id: row.id, status: 'pending' }, data: { status: 'done', ok: false, error: refusal } })if (refused.count) this.terminalAnswered(tx, row.id)@@ -1696,9 +1731,11 @@ export class SuperTabStore {}private async terminalRefusal(tx: Transaction, state: SuperTabState | null,- row: { agentId: string; machineId: string; machineOwnerId: string; harnessId: string; requesterKey: string }): Promise<string | null> {+ row: { agentId: string; machineId: string; machineOwnerId: string; harnessId: string; requesterKey: string }, team = true): Promise<string | null> {const target = state?.agents.find(a => a.id === row.agentId && a.machineId === row.machineId && a.machineOwnerId === row.machineOwnerId)if (!state || !target) return 'The agent is no longer in the Swarm.'+ // Only its Team account answers for an agent there, never its owner's own sign-in (security re-check 2 of #2089).+ if (!team && onTeamAccount(state, target)) return 'Only this computer\'s Harness Team account answers for its agents.'if (target.harnessId !== row.harnessId) return 'The agent’s terminal changed since the request. Read it again.'const [kind, id] = [row.requesterKey.slice(0, row.requesterKey.indexOf(':')), row.requesterKey.slice(row.requesterKey.indexOf(':') + 1)]const requester: Actor = kind === 'person' ? { kind: 'person', userId: id, email: '' }@@ -1921,13 +1958,13 @@ export class SuperTabStore {/** Narrow authority: the machine owner can finish a specific queued start,* never submit arbitrary commands as its initiating person or lead. */private async poolHostActor(tx: Transaction, user: AuthUser, state: SuperTabState, machineId: string, startId: string): Promise<Actor> {- await this.hostFor(tx, user, machineId)+ const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })+ await this.hostFor(tx, user, machineId, owned, state)const start = state.starts?.find(s => s.id === startId) ?? fail('NOT_FOUND', 'This start is unavailable.', 404)const pool = machineContribution(state, machineId)if (!pool || pool.contributorId !== user.sub || pool.generation !== start.poolGeneration || start.request.machineId !== machineId || start.machineOwnerId !== user.sub) {fail('FORBIDDEN', 'This start does not belong to this machine contribution.', 403)}- const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)let actor: Actorif (start.actorKey.startsWith('agent:')) {@@ -2011,12 +2048,13 @@ export class SuperTabStore {const observation = machineObservationSchema.parse(input)const sweep = this.sweepDue(tabId, this.now())return transaction(this.db, async tx => {- await this.hostFor(tx, user, machineId)+ const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })+ await this.hostFor(tx, user, machineId, owned)// Only the conversations its checks read (parts/load.ts loadObserved): the whole Swarm was ~1.1 MB a report (#876).const loaded = loadedFrom(await this.row(tx, user, tabId), await loadObserved(tx, tabId, machineId)), state = structuredClone(loaded.state)+ await this.hostFor(tx, user, machineId, owned, state)const pool = machineContribution(state, machineId)if (!pool || pool.contributorId !== user.sub || pool.generation !== observation.generation) fail('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403)- const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)const now = this.now()// A machine that went silent while cleaning takes the fallback before this fresh reading can bring it back: its records@@ -2068,7 +2106,14 @@ export class SuperTabStore {}// Its own agents lose their tasks at once (a stopped session); every 30 seconds it runs the Swarm's time checks too, so// they keep running when the Lead's own machine is the one that died.- return saved([...loseTasks(state, now, worker => worker.machineId === machineId), ...sweep ? sweepLiveness(state, now) : []])+ const checked = [...loseTasks(state, now, worker => worker.machineId === machineId), ...sweep ? sweepLiveness(state, now) : []]+ // A Product Manager waiting for a machine starts on the first free one (leadStart.ts). The Team machines are read only+ // while one waits.+ if (projectsOf(state).some(p => p.lead?.status === 'waiting')) {+ placeWaitingLeads(state, { now, teamMachines: await this.teamMachines(tx, state), otherWorkspaceMachines: await this.otherWorkspaceMachines(tx, state),+ ...(this.hooks.teamAccountsIdle ? { teamAccountsIdle: true } : {}) })+ }+ return saved(checked)})}@@ -2217,6 +2262,8 @@ export class SuperTabStore {const team = await this.teamHost(this.db, user)if (team !== null && target.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)await this.grantHolds(this.db, seen.swarm, target, inSwarm, reads)+ if (team === null) await this.notTeamMachine(user, () => reads.once(machineKey(seen.swarm.environment, target.machineId, target.machineOwnerId),+ () => this.db.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId, autonomousEnv: seen.swarm.environment, ...machineAlive } })), !!target.team)const senders = new Map<string, Promise<boolean>>()const sent = (id: string) => senders.get(id) ?? senders.set(id, this.grantHolds(this.db, seen.swarm, seen.grants[id]!, inSwarm, reads).then(() => true, error => { if (error instanceof SuperTabError) return false; throw error })).get(id)!diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.tsindex b8160ddda..6bde53c2f 100644--- a/backend/src/superTabs/terminal.ts+++ b/backend/src/superTabs/terminal.ts@@ -3,8 +3,8 @@ import type { PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'import { activeWork, actorKey, agent, author, conversation, fail, isLeads, stableId, type Actor, type Agent, type Author, type Conversation, type MessageDraft,type SuperTabState } from './model.js'-import { downSince } from './machines.js'-import { agentProjectId, isConfidential, ledProject, ownSession, projectOf, readAgent } from './projects.js'+import { downSince, productManagerOn } from './machines.js'+import { agentProjectId, isConfidential, ledProject, onTeamAccount, ownSession, projectOf, readAgent, teamSessionAccess } from './projects.js'import { redactCredentials } from './credentials.js'/** The Lead reads and types in an agent's terminal through the host of the agent's machine (spec/2026-10-23-lead-sees-agent-terminal.md).@@ -34,9 +34,20 @@ export interface TerminalRequest { id: string; agentId: string; harnessId: strin/** Only the Lead of the agent's project, or a person with write access who can see the agent, reads or types in its terminal. *//** `elsewhere`: the agent's session is confidential in another Swarm (confidential.ts). */-export function mayDrive(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false): void {+export function mayDrive(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false, kind: TerminalKind = 'input'): void {// For both kinds of requester: no person or agent reads a confidential session but its own (final review, Critical 1).const closed = () => {+ // A Team account holding a Product Manager: every agent there is one macOS user, which reads people's chats with it,+ // so no person types in any of them (security review 2 of #2089). They talk to them in their groups' chats.+ if (actor.kind === 'person' && kind === 'input' && onTeamAccount(state, target) && productManagerOn(state, target.machineId)) {+ fail('TERMINAL_PRIVATE', `${target.displayName ?? target.name} runs in a Harness Team account that holds a Product Manager, so nobody types in it through the Swarm. Talk to it in its group's chat.`, 403)+ }+ // In a Harness Team account: its project's owner reads its screen, and nobody types in it (projects.ts teamSessionAccess).+ const team = teamSessionAccess(state, actor, target, elsewhere)+ if (team === 'watch' && kind === 'screen') return+ if (team) {+ fail('TERMINAL_PRIVATE', `This ${ledProject(state, target.id) ? 'Product Manager' : 'agent'} runs in a Harness Team account: nobody types in it through the Swarm, and only its project's owner reads its screen. Talk to it in its project's chat.`, 403)+ }// Members may watch a Lead, but only its machine's owner drives it, whether or not its session counts as private (Ken, 2026-10-28).if (ledProject(state, target.id) && !ownSession(actor, target)) {fail('TERMINAL_PRIVATE', 'Only the person whose machine runs this agent can read or type in a Product Manager’s terminal.', 403)@@ -69,7 +80,7 @@ const nameOf = (target: Agent) => target.displayName ?? target.nameexport function terminalRequest(state: SuperTabState, actor: Actor, sender: Author, id: string, now: number,command: { type: 'agent.screen' | 'agent.input'; agentId: string; scrollback?: number; text?: string; keys?: string[] }, elsewhere = false) {const target = agent(state, command.agentId)- mayDrive(state, actor, target, elsewhere)+ mayDrive(state, actor, target, elsewhere, command.type === 'agent.screen' ? 'screen' : 'input')if (downSince(state, target, now)) fail('HOST_OFFLINE', `${nameOf(target)}’s terminal is not running or its machine is offline.`)const { type: _type, agentId: _agentId, ...detail } = commandconst effect: TerminalEffect = { op: 'request', id, kind: command.type === 'agent.screen' ? 'screen' : 'input', agentId: target.id,diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex 9bbf5fb88..6f13bc278 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -153,6 +153,8 @@ export const LAUNCH_ERROR_CODES = [// The engine itself: preparing it (engines/nativeLaunch.ts) and its start (core/agents/newPane.ts).'engine_cannot_run', 'engine_install_failed', 'engine_did_not_start', 'engine_not_installed', 'start_timeout','engine_launch_refused',+ // A Codex launch in a home of its own (a Swarm Product Manager's) the owner's relay cannot sign in (team/relay.ts).+ 'owner_relay_unavailable',// A Store harness (core/agents/dshThrough.ts, services/storeLaunch.ts).'dsh_not_installed', 'dsh_unavailable', 'dsh_runtime_failed',// A conversation Harness did not start, opened in it (core/agents/adopt.ts, externalResume.ts, lib/registry.ts).diff --git a/cli/src/backendSocket.teamApps.spec.ts b/cli/src/backendSocket.teamApps.spec.tsnew file mode 100644index 000000000..973132615--- /dev/null+++ b/cli/src/backendSocket.teamApps.spec.ts@@ -0,0 +1,135 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { BackendSocket } from './backendSocket.js'+import type { RemoteAppPolicy, RemoteClient } from './core/api.js'+import { dispatchDown, gatewayOf, relaySocket } from './testing/relaySocket.js'++// The account's own apps on a Harness Team daemon (#895, superTabs/inCore/teamApps.ts): the socket asks the policy+// before anything else answers, shows them its replies as the policy filters them, and withholds the events it withholds.+// Its rules are teamApps.spec.ts's; here, that the socket keeps to them on each path.+describe('the account\'s own apps under a remote app policy', () => {+ const sockets: BackendSocket[] = []+ afterEach(async () => { for (const s of sockets.splice(0)) await s.stop(); vi.restoreAllMocks() })++ /** A policy that hides the agent `pm` and refuses `message`. */+ const policy: RemoteAppPolicy = {+ refuse: (type, payload) => payload.agentId === 'pm' ? { error: 'SWARM_CONFIDENTIAL', message: 'hidden' }+ : type === 'message' ? { error: 'TEAM_READ_ONLY', message: 'read only' } : null,+ reply: (_type, payload) => Array.isArray(payload.agents) ? { ...payload, agents: (payload.agents as Array<{ id: string }>).filter(a => a.id !== 'pm') } : payload,+ event: (frame) => (frame.payload as { agentId?: unknown } | undefined)?.agentId === 'pm' ? null : frame,+ watchOnly: () => true,+ isConfidential: (id) => id === 'pm',+ }++ function session(guest?: string) {+ const socket = relaySocket('fixture')+ sockets.push(socket)+ socket.remoteAppPolicy = policy+ const gw = gatewayOf(socket)+ vi.spyOn(gw.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gw.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gw.e2ee, 'sessionIdentity').mockReturnValue('identity')+ vi.spyOn(gw.e2ee, 'pairedPeers').mockReturnValue([{ identityPub: 'identity', label: 'Mac · owner', pairedAt: 1, role: 'web',+ ...(guest !== undefined ? { shared: true as const, sharedWith: guest } : {}) }])+ const client: RemoteClient = { role: 'web', label: null, identity: 'identity', direct: false, accountOwner: guest === undefined, ...(guest !== undefined ? { guest } : {}) }+ ;(socket as unknown as { remoteClients: Map<string, RemoteClient> }).remoteClients.set('remote', client)+ const replies = vi.spyOn(gw, 'reply').mockImplementation(() => {})+ const ask = async (type: string, payload: Record<string, unknown> = {}) => {+ const clear = { type, payload: { requestId: 'one', ...payload } }+ vi.spyOn(gw.e2ee, 'unwrapDown').mockReturnValue(clear)+ await dispatchDown(socket, { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ }+ const answered = () => replies.mock.calls.map(([, type, , payload]) => ({ type, payload: payload as Record<string, unknown> }))+ return { socket, gw, ask, answered }+ }++ it('refuses what the policy refuses, before a service or a terminal stream hears it', async () => {+ const { socket, ask, answered } = session()+ const routed = vi.fn(() => true)+ socket.serviceRouter = routed+ const opened = vi.fn(async () => true)+ ;(socket as unknown as { terminalStreams: unknown }).terminalStreams = { handleFrame: opened, stop: vi.fn() }+ await ask('terminal_open', { agentId: 'pm' })+ await ask('message', { agentId: 'worker', text: 'cat ~/.claude' })+ expect(opened).not.toHaveBeenCalled()+ expect(routed).not.toHaveBeenCalled()+ expect(answered()).toEqual([+ { type: 'terminal_open', payload: { error: 'SWARM_CONFIDENTIAL', message: 'hidden' } },+ { type: 'message', payload: { error: 'TEAM_READ_ONLY', message: 'read only' } },+ ])+ await ask('terminal_open', { agentId: 'worker' })+ expect(opened).toHaveBeenCalledWith('remote', 'terminal_open', expect.objectContaining({ agentId: 'worker' }))+ })++ it('shows its replies as the policy filters them', async () => {+ const { socket, ask, answered } = session()+ socket.agentsProvider = async (_payload, _role, reply) => { reply({ agents: [{ id: 'pm' }, { id: 'worker' }] }) }+ await ask('agents_list')+ expect(answered()).toEqual([{ type: 'agents_list', payload: { agents: [{ id: 'worker' }] } }])+ })++ it('withholds from the apps the events the policy withholds, and still tells the windows here', async () => {+ const { socket, gw } = session()+ const broadcast = vi.spyOn(gw, 'broadcast').mockImplementation(() => {})+ socket.send({ type: 'text_delta', payload: { agentId: 'pm', text: 'private' } })+ socket.send({ type: 'text_delta', payload: { agentId: 'worker', text: 'hello' } })+ expect(broadcast.mock.calls.map(([frame]) => frame)).toEqual([{ type: 'text_delta', payload: { agentId: 'worker', text: 'hello' } }])+ })++ it('holds the account\'s own apps to watching their terminals, and no guest, window here or daemon without a policy', () => {+ const { socket } = session()+ expect(socket.appWatchOnly('remote')).toBe(true)+ expect(socket.appWatchOnly('')).toBe(false)+ // A remote connection with no client record fails closed.+ expect(socket.appWatchOnly('unknown-connection')).toBe(true)+ socket.remoteAppPolicy = null+ expect(socket.appWatchOnly('remote')).toBe(false)+ expect(session('[email protected]').socket.appWatchOnly('remote')).toBe(false)+ })++ // Security re-review of #2089: turn cards, agent questions and commander events go to the account's paired devices+ // through sendCommander, and a Team daemon seals them for the Mac owner's devices.+ it('withholds from the account\'s paired devices and its browsers what the policy withholds', () => {+ const { socket, gw } = session()+ const commander = vi.spyOn(gw, 'commander').mockImplementation(() => {})+ const user = vi.spyOn(gw, 'user').mockImplementation(() => {})+ socket.sendCommander({ type: 'question', payload: { agentId: 'pm', question: 'Approve the launch slip?' } })+ socket.sendCommander({ type: 'turn_card', payload: { agentId: 'worker', recap: 'Tests pass.' } })+ socket.sendUser({ type: 'notice', payload: { agentId: 'pm' } })+ socket.sendUser({ type: 'notice', payload: { agentId: 'worker' } })+ expect(commander.mock.calls.map(([frame]) => (frame as { payload: { agentId: string } }).payload.agentId)).toEqual(['worker'])+ expect(user.mock.calls.map(([frame]) => (frame as { payload: { agentId: string } }).payload.agentId)).toEqual(['worker'])+ })++ // Security re-check 2 of #2089: the relay seals the Wi-Fi device's frames before the socket sees them, its events name+ // their agent a level down, and its own doors (core/wifiAgents.ts) never ask the policy. On a Team daemon it is off.+ it('with the Wi-Fi device off, hands it none of the relay\'s sessions or requests, and sends it nothing', async () => {+ const { socket, gw } = session()+ const wifi = { session: vi.fn(), dropped: vi.fn(), request: vi.fn(), revoked: vi.fn() }+ socket.disableWifi()+ socket.useWifi(wifi as never)+ const device = vi.spyOn(gw, 'device').mockImplementation(() => true)+ // As the gateway hands them on: a device session, its sealed request opened, its revocation.+ socket.fromGateway.client('dial-1', { role: 'device', label: 'Wi-Fi device', identity: 'dial', direct: true, accountOwner: true })+ await socket.fromGateway.device?.('dial-1', { type: 'e2e', payload: {} }, { type: 'wifi_view', payload: { requestId: 'v1' } })+ socket.fromGateway.deviceRevoked?.('dial')+ await socket.fromGateway.disconnected('dial-1')+ socket.deviceFrame('dial-1', 'wifi_view_result', { agents: [{ agentId: 'worker' }] })+ expect([wifi.session, wifi.request, wifi.revoked, wifi.dropped].map(f => f.mock.calls.length)).toEqual([0, 0, 0, 0])+ expect(device).not.toHaveBeenCalled()+ })++ it('closes a confidential session\'s terminal to the account\'s own apps, unknown connections too, and to no guest or window here', () => {+ const { socket } = session()+ expect([socket.appClosedTo('remote', 'pm'), socket.appClosedTo('remote', 'worker'), socket.appClosedTo('unknown-connection', 'pm')]).toEqual([true, false, true])+ expect(socket.appClosedTo('', 'pm')).toBe(false)+ expect(session('[email protected]').socket.appClosedTo('remote', 'pm')).toBe(false)+ socket.remoteAppPolicy = null+ expect(socket.appClosedTo('remote', 'pm')).toBe(false)+ })++ it('leaves a guest to the guest policy, which refuses it first', async () => {+ const { ask, answered } = session('[email protected]')+ await ask('message', { agentId: 'worker' })+ expect(answered()).toEqual([{ type: 'message', payload: expect.objectContaining({ error: 'NOT_YOUR_HARNESS' }) }])+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 5e86c1217..1a20bf476 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -2,7 +2,7 @@ import { messageReceipt, productObservation, productUsageIntent, productUsageLauimport type { MessageReceipt } from './lib/sessionInput.js'import { isLocalOnly, withoutUpdate } from './lib/cardUpdate.js'import type { PurgeAgentService } from './lib/purgeAgentService.js'-import { MESSAGES_REQUESTS, SHARE_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport, type TabFrame } from './core/api.js'+import { MESSAGES_REQUESTS, SHARE_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteAppPolicy, type RemoteClient, type RemoteRole, type RemoteTransport, type TabFrame } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import { countWindows } from './lib/windowSurfaces.js'import type { ViewerStreams } from './core/viewerStreams.js'@@ -293,6 +293,26 @@ export class BackendSocket {/** The guest (email) an agent was started for, or null for the owner's own (registry `guest`): what a* guest session may act on (core/guestPolicy.ts). Null treats every agent as the owner's. */agentGuest: ((agentId: string) => string | null) | null = null+ /** On a Harness Team daemon, what the account's own apps may ask and hear (core/api.ts RemoteAppPolicy): another person's+ * Product Manager may run there, and the account is the Mac's owner's (#895). Null everywhere else. */+ remoteAppPolicy: RemoteAppPolicy | null = null++ /** The policy over [connId] when it is one of the account's own apps away from this desk: not a window here, nor a guest,+ * which has its own space (core/guestPolicy.ts). A remote connection with no client record fails closed: it is held. */+ private appPolicyFor(connId: string): RemoteAppPolicy | null {+ if (!this.remoteAppPolicy || !connId || this.localClients.has(connId) || isLocalClientId(connId)) return null+ return this.remoteClient(connId)?.guest !== undefined ? null : this.remoteAppPolicy+ }++ /** Whether [connId] is one of the account's own apps away from this desk, held to watching its terminals now. */+ appWatchOnly(connId: string): boolean {+ return this.appPolicyFor(connId)?.watchOnly() ?? false+ }++ /** Whether [agentId]'s terminal is closed to [connId] now: a confidential session, to the account's own apps. */+ appClosedTo(connId: string, agentId: string): boolean {+ return this.appPolicyFor(connId)?.isConfidential(agentId) ?? false+ }/** Answers `session_get` with the whole reply: a conversation's history, a page at a time (cli.ts binds* core/transcripts/history.ts). Null answers UNSUPPORTED. */historyProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null@@ -467,10 +487,16 @@ export class BackendSocket {/** The Wi-Fi device's sessions and requests, as the gateway hands them on, for its service with the* devices (core/wifi.ts, services/wifi.ts). */private wifi?: WifiCore['fromGateway']- useWifi(wifi: WifiCore['fromGateway']): void { this.wifi = wifi }+ /** Off on a Harness Team daemon (core/main.ts): the device's frames are sealed before anything here could filter them,+ * and its own doors (core/wifiAgents.ts) reach every agent, so it would reach a Swarm Product Manager there (security+ * re-check 2 of #2089). Nothing of it is wired, and nothing is sent to it. */+ private wifiOff = false+ disableWifi(): void { this.wifiOff = true; this.wifi = undefined }+ useWifi(wifi: WifiCore['fromGateway']): void { if (!this.wifiOff) this.wifi = wifi }/** The Wi-Fi device's answers and events, sealed to one session; and which identity's app said hello on* one. Through the gateway, guarded as every frame of the core's is. */deviceFrame(connId: string, type: string, payload: Record<string, unknown>): void {+ if (this.wifiOff) returnthis.throughGateway('device', (gateway) => gateway.device(connId, type, payload), false)}deviceClient(connId: string, identity: string | null): void { this.toGateway('device', (gateway) => gateway.deviceClient(connId, identity)) }@@ -579,8 +605,16 @@ export class BackendSocket {this.toRemoteApps(frame)}- private toRemoteApps(frame: Frame): void {+ /** An up-frame as the account's apps and devices away from this desk may have it (`remoteAppPolicy`), or null to withhold+ * it: every path to them asks, the paired devices' and the Wi-Fi device's too (security re-review of #2089). */+ private forApps(frame: Frame): Frame | null {+ return this.remoteAppPolicy ? this.remoteAppPolicy.event(frame) : frame+ }++ private toRemoteApps(given: Frame): void {if (this.thisComputerOnly) return+ const frame = this.forApps(given)+ if (!frame) returnconst guest = this.frameGuest(frame)this.toGateway('web', (gateway) => gateway.broadcast(frame, guest ?? undefined))}@@ -664,7 +698,8 @@ export class BackendSocket {/** Send a user-level notification to every logged-in browser that owns this machine. */sendUser(frame: Frame): void {- this.toGateway('user', (gateway) => gateway.user(frame))+ const shown = this.forApps(frame)+ if (shown) this.toGateway('user', (gateway) => gateway.user(shown))}/**@@ -685,9 +720,11 @@ export class BackendSocket {sendCommander(frame: Frame): void {this.onOutboundCommander?.(frame)if (isLocalOnly(frame)) return- if (env.LOG_FRAMES) logFrame('→', 'device', frame)+ const shown = this.forApps(frame)+ if (!shown) return+ if (env.LOG_FRAMES) logFrame('→', 'device', shown)// The sentence a processing card carries for the Pro's cable stays on this computer (onOutboundCommander).- this.toGateway('device', (gateway) => gateway.commander(withoutUpdate(frame)))+ this.toGateway('device', (gateway) => gateway.commander(withoutUpdate(shown)))}/** Attach one authenticated loopback desktop client to the same RPC and event plane as cloud web. */@@ -956,6 +993,8 @@ export class BackendSocket {productUsageIntent(type, (frame.payload as { usageIntent?: unknown } | undefined)?.usageIntent,(frame.payload as { agentId?: unknown } | undefined)?.agentId, usageSource,signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)))+ // A guest's own space is the guest policy's below; the account's own apps, away from this desk, answer to this one.+ const appPolicy = !local && connId && this.remoteClient(connId)?.guest === undefined ? this.remoteAppPolicy : nullconst reply = (t: string, rid: unknown, p: Record<string, unknown>): void => {if (t === type) {const failure = p.failure as { code?: unknown; reason?: unknown } | undefined@@ -963,7 +1002,8 @@ export class BackendSocket {// The agent frame itself: a created launch's agent is watched until it starts (gateway/productUsage.ts).launchMeasured(p.error ?? (p.failure as { code?: unknown } | undefined)?.code, p.state, p.agent, (p.held as { service?: unknown } | undefined)?.service)}- this.emitReply(connId, t, rid, p)+ // The account's own apps see a reply as its policy shows it (`remoteAppPolicy`); a window here sees it whole.+ this.emitReply(connId, t, rid, appPolicy ? appPolicy.reply(t, p) : p)}// A guest: a session trusted only because this machine is shared with its account (gateway/gateway.ts).const guest = local ? undefined : this.remoteClient(connId)?.guest@@ -989,6 +1029,14 @@ export class BackendSocket {return}}+ if (appPolicy) {+ const refused = appPolicy.refuse(type, payload)+ if (refused) {+ console.warn(`[team] refused ${logSafeType(type)} from conn:${sid(connId)} — ${refused.error}`)+ if (requestId !== undefined) reply(type, requestId, refused)+ return+ }+ }// A paired owner can run the machine's orchestrator; observers and device sessions cannot.// Both requests and replies are encrypted, including project artifacts.diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 6222a2295..c094fee54 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -244,6 +244,15 @@ describe('creating an agent', () => {ownerRelay.mockClear()await setup({ ownerRelay }).create(request({ cwd: folder(), grid: { baseUrl: 'https://grid.example/relay/v1', networkName: 'g', model: 'm' } }))expect(ownerRelay).not.toHaveBeenCalled()+ // A Codex launch in a home of its own (a Swarm Product Manager's): the relay readies, and asks about, that home.+ await setup({ ownerRelay }).create(request({ engine: 'codex', cwd: folder(), codexHome: '/fixture/pm-home/codex' }))+ expect(ownerRelay).toHaveBeenCalledWith('codex', '/fixture/pm-home/codex')+ // A relay that cannot sign that home in refuses the launch with why: no pane is made.+ vi.mocked(createAndRegisterPane).mockClear()+ const refused = vi.fn(async () => ({ refused: 'No relay here.' }))+ expect(await setup({ ownerRelay: refused }).create(request({ engine: 'codex', cwd: folder(), codexHome: '/fixture/pm-home/codex' })))+ .toEqual({ ok: false, error: 'OWNER_RELAY_UNAVAILABLE', detail: 'No relay here.' })+ expect(createAndRegisterPane).not.toHaveBeenCalled()})it('launches as before where the GitHub App does not apply, and without a role never asks', async () => {diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 2774fd051..31eeda5f4 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -97,7 +97,8 @@ export interface CreateAgentDeps {dshLaunch: Pick<DshThrough, 'materialize' | 'launch'>/** In the Harness Team account, for an engine it has not signed in itself: the owner's subscription through the* owner's relay (team/relay.ts `teamRelayLaunch`), null otherwise. Absent ⇒ never. */- ownerRelay?: (engine: AgentEngine) => Promise<{ env: Record<string, string>; args: string[] } | null>+ /** [codexHome]: the launch's own Codex home, whose sign-in and model list are its own (a Swarm Product Manager's). */+ ownerRelay?: (engine: AgentEngine, codexHome?: string) => Promise<{ env: Record<string, string>; args: string[] } | { refused: string } | null>/** The Swarm's part of a start with a Swarm role (superTabs/inCore/launch.ts); absent while the Swarm is off. */swarmLaunch?: SwarmLaunch}@@ -291,7 +292,10 @@ export function createAgentCreator({}// In the Harness Team account, an engine it has not signed in itself spends the owner's subscription through the// owner's relay (team/relay.ts), where a grid would otherwise sit: a grid launch is its own provider.- const relay = !grid && ownerRelay ? await ownerRelay(engine) : null+ const offered = !grid && ownerRelay ? await (engine === 'codex' && codexHome ? ownerRelay(engine, codexHome) : ownerRelay(engine)) : null+ // A Codex home of its own the relay cannot sign in: refused with why, never launched signed out (team/relay.ts).+ if (offered && 'refused' in offered) return { ok: false, error: 'OWNER_RELAY_UNAVAILABLE', detail: offered.refused }+ const relay = offeredif (!current()) return stale()// The Swarm starts its agents in full mode, so a machine that never accepted full mode's warning stops each one there// before its first turn (Claude Code's "Yes, I accept", the Mac Studio, 2026-10-26). The Swarm's owner chose that modediff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex b553cc3bc..60068d9c0 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1491,6 +1491,26 @@ export const WIFI_FALLBACKS: PortFallbacks<WifiPort> = {/** What a remote client proved with its E2EE session: an owner's app or browser, or a device. */export type RemoteRole = 'web' | 'device'+/**+ * What the account's own apps away from this desk may ask of this machine and hear from it, beyond what an owner may+ * (backendSocket.ts `remoteAppPolicy`). Set only on a Harness Team daemon, by the Swarm (superTabs/inCore/teamApps.ts):+ * there the account is the Mac's owner's, and another person's Product Manager may run, holding people's private chats.+ */+export interface RemoteAppPolicy {+ /** Why a request is refused, or null to answer it as for any owner. */+ refuse(type: string, payload: Record<string, unknown>): { error: string; message: string } | null+ /** A reply's payload as the apps may see it. */+ reply(type: string, payload: Record<string, unknown>): Record<string, unknown>+ /** An up-frame as the apps may hear it, or null to withhold it. */+ event<F extends { agentId?: unknown; payload?: unknown }>(frame: F): F | null+ /** Whether the apps' terminal streams only watch now: no input, paste or resize reaches a terminal, binary frames included+ * (lib/terminalStreamManager.ts `watchOnly`). */+ watchOnly(): boolean+ /** Whether a session, by its agent id or its engine's session id, is closed to the apps: its open terminal streams close+ * (lib/terminalStreamManager.ts `closedTo`). */+ isConfidential(id: string): boolean+}+/** A remote client the gateway holds a session with, as the core may know it: its role, the label its* identity was paired under (null for none) for naming it to the person, its identity's public key (the* Wi-Fi device's requests are kept apart by it), and whether it is on a device's direct link rather thandiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex d06f5da26..7078e61c0 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -365,7 +365,10 @@ function startMasterHere(): void {const coreLink = connectToMaster()/** When the devices' process starts: once there is a device, a dial's port, a Wi-Fi device or a request for one* (core/devicesWake.ts). Asked of the master through the channel above. */-const devicesWake = createDevicesWake({ want: (service) => coreLink.want(service), dataDir: env.ADAPTER_DATA_DIR, cableDisabled: env.CABLE_DISABLE, testDialPort: harnessdEnv().HARNESSD_TEST_DIAL_PORT })+/** A Harness Team daemon runs no devices, the Wi-Fi device's service or the dials' (security re-check 1 of #2089): set as+ * it decides it is one (runForeground), before anything is wired to them. */+let devicesOff = false+const devicesWake = createDevicesWake({ want: (service) => { if (!devicesOff) coreLink.want(service) }, dataDir: env.ADAPTER_DATA_DIR, cableDisabled: env.CABLE_DISABLE, testDialPort: harnessdEnv().HARNESSD_TEST_DIAL_PORT })const daemonBoot: {/** Stops the updater this core runs beside itself under a master too old to run it (core/updaterBeside.ts). */@@ -700,6 +703,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The Swarm switch (harnessd/services.ts `HARNESS_SWARM`, on unless set off): its code in this process comes from one// entry, loaded only while it is on (superTabs/inCore.ts), and its service is left off with it.const swarm = swarmOn(harnessd) ? await import('../superTabs/inCore.js') : null+ // Decided once, as it starts: whether this daemon is a Harness Team account's (superTabs/inCore/teamApps.ts isTeamDaemon).+ const teamDaemon = !!swarm?.isTeamDaemon()+ devicesOff = teamDaemonconst knownServices = servicesOn(harnessd, KNOWN_SERVICES)const outOfProcess = servicesTheMasterRuns(harnessd, knownServices)// The viewers' process (the viewers and the Store) runs once something needs it (core/viewersWake.ts).@@ -881,6 +887,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The prompt of each agent's last turn start: what the one-line summary of a working agent says (turns/summaries.ts).const turnPrompts = new Map<string, string>()const nativeTurns = createNativeTurnObservations({ resolve: id => nativeTurnBinding(registry.byAgent(id)) })+ /** A Team daemon's purge of an ended confidential member's session data (superTabs/inCore/teamApps.ts); null elsewhere. */+ let teamPurge: ((agentId: string) => Promise<Record<string, unknown>>) | null = nullconst coreApi = createCoreApi({nativeTurns: async (agentId, cursor) => nativeTurns.read(agentId, cursor),cloud: cloudDoors,@@ -1005,7 +1013,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {resumeAgent: async (agentId) => lifecycle.resumeAgent(agentId),// What it may close and reopen is decided in this process, on what its host retains (superTabs/inCore/agents.ts)....(swarm ? { swarmAgents: (agentDeps) => swarm.createSwarmAgents({ ...agentDeps,- members: { leads: () => swarm.retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR) } }) } : {}),+ members: { leads: () => swarm.retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR) },+ // On a Team daemon, an ended confidential member's session data goes (set below, with the Team daemon's policy).+ purgeEnded: async (agentId) => teamPurge ? teamPurge(agentId) : { skipped: true } }) } : {}),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 },@@ -1132,6 +1142,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {machines: ({ body }) => ports.models?.machines(body, computerId()),})backend.useGateway(gateway.port)+ // A Harness Team daemon serves no Wi-Fi device: its frames are sealed past the Team guard and its doors reach every agent,+ // a Swarm Product Manager's included (security re-check 2 of #2089).+ if (teamDaemon) backend.disableWifi()backend.useWifi(wifiCore.fromGateway)const gatewayOps = gateway.opsdaemonBoot.openRequests = () => backend.openRequests()@@ -1190,6 +1203,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {sendTarget: (connId, type, payload) => backend.sendTerminalTo(connId, type, payload),sendBinaryTarget: (connId, frame) => backend.sendTerminalBinaryTo(connId, frame),isLoopback: isLocalClientId,+ // The Mac owner's apps on a Team daemon running a Swarm Product Manager only watch (superTabs/inCore/teamApps.ts).+ watchOnly: (connId) => backend.appWatchOnly(connId),+ closedTo: (connId, agentId) => backend.appClosedTo(connId, agentId),// For a client that did not introduce itself on `terminal_open` (an older build). A loopback// window can only be this computer's desktop; a paired peer is named by its pairing label unless// that label is one of the placeholders pairing hands out — those name nothing.@@ -1425,6 +1441,18 @@ async function runForeground(session: AuthSession | null): Promise<void> {cloudFrames: () => cloud.frames(),}).agentsListbackend.agentGuest = (agentId) => registry.resolve(agentId)?.guest ?? null+ // On a Harness Team daemon the account is the Mac's owner's, and another person's Product Manager may run here: the+ // owner's own apps never reach the Swarm's confidential sessions, and only watch the rest while one runs (#895).+ // Decided once, as it starts: only a Team daemon has it (security review 1 of #2089), and it reads the stopped sessions too.+ if (swarm && teamDaemon) {+ // The purges still to finish, kept across restarts: the account stays held until each has (superTabs/inCore/teamPurge.ts).+ const purges = swarm.purgeRecord(join(env.ADAPTER_DATA_DIR, 'super-tabs', 'team-purges.json'))+ const policy = swarm.teamAppPolicyFor(env.ADAPTER_DATA_DIR, () => coreApi.daemon.machineId(), () => registry.list(), () => stoppedAgents.list(), purges)+ backend.remoteAppPolicy = policy+ teamPurge = swarm.createConfidentialPurge({ confidential: (agentId) => policy.isConfidential(agentId), home: homedir(), record: purges,+ session: (agentId) => registry.byAgent(agentId) ?? stoppedAgents.get(agentId),+ purge: async (request) => backend.purgeAgentService ? await backend.purgeAgentService.request(request as never) : { error: 'UNSUPPORTED' } })+ }const questionWatcher = asking.questionWatcher@@ -2080,6 +2108,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Until the pieces below are built; after, a piece that could not be is refused by the requests// that need it, and the rest (list, status, revoke) answer from the pairings.if (!devicePartsBuilt) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }+ // A Harness Team daemon pairs no Wi-Fi device and serves none (backendSocket.ts disableWifi).+ if (teamDaemon) return { status: 403, body: { error: { code: 'TEAM_ACCOUNT', message: 'A Harness Team account does not serve a Wi-Fi device.' } } }// The Wi-Fi device's pairings and direct links are the gateway's (gateway/start.ts); its receipts its// service's, with the dials (services/wifi.ts).const viaGateway = async (request: Parameters<GatewayOps['wifi']>[0]): Promise<Record<string, unknown>> => {@@ -3179,7 +3209,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// In their own process they are told everything the windows said as they connect (core/devicesLink.ts):// said here too, it reached a dial still opening its port, before its greeting.// The Swarm cards the Super Tab service sent before this line had no devices to reach: they are shown now.- if (outOfProcess.has('devices')) { ports.devices = devicesLink.port; swarmDoors?.cards.replay() }+ // A Harness Team daemon runs neither the dials nor the Wi-Fi device: every card goes to them before the Team guard could+ // filter it (security re-check 1 of #2089).+ if (teamDaemon) { /* no devices */ } else if (outOfProcess.has('devices')) { ports.devices = devicesLink.port; swarmDoors?.cards.replay() }else {serviceHost.start('devices', (core, started) => inline!.startDevices(core, started, {logsDir: env.HARNESS_LOGS_DIR, testDialPort: harnessd.HARNESSD_TEST_DIAL_PORT,@@ -3192,7 +3224,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The Wi-Fi device (services/wifi.ts), with the dials: in their process by default (core/wifiLink.ts,// resumed there as its link connects), or here.- if (!outOfProcess.has('wifi')) {+ if (!teamDaemon && !outOfProcess.has('wifi')) {serviceHost.start('wifi', inline!.startWifi, coreApi, WIFI_FALLBACKS)if (ports.wifi) wifiCore.started(appVoiceFocus ?? null)}@@ -3210,7 +3242,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// site: a new kind of card reaches the dial the day it reaches the socket. The tee runs before the frame// is queued for the Wi-Fi device (BackendSocket.sendCommander): a device fault here must cost neither// that frame nor whoever is sending it, which the guards and the devices' port see to.- backend.onOutboundCommander = (frame) => {+ // Not on a Harness Team daemon: there it would hand every card to the dials and the Wi-Fi device past the Team guard.+ if (!teamDaemon) backend.onOutboundCommander = (frame) => {const card = frame as Record<string, unknown>// The Pro's extras ride to the devices alone: the Wi-Fi device gets the card as it always did, and a// summary reaches the dial with the turn's whole answer, as it does the Wi-Fi device.diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 21084a792..b2bbe4cdf 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -225,6 +225,12 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (.toMatchObject({ ok: true, overrides: { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9/claude', ANTHROPIC_AUTH_TOKEN: 't' }, extraArgs: [] } })expect(await buildLaunchOverrides(deps({ ownerRelay }).d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'a')).toMatchObject({ ok: true, overrides: { env: { CODEX_HOME: '/home/u/.codex-work', HARNESS_RELAY_TOKEN: 't' }, extraArgs: relay.args } })+ // The relay readies, and asks about, that home: a Swarm Product Manager's own, whose sign-in and models are its own.+ expect(ownerRelay).toHaveBeenLastCalledWith('codex', '/home/u/.codex-work')+ // A relaunch (restart, resume, restore) the relay cannot sign in is held with why, as a launch that waits is: after a+ // reboot the Team daemon may restore before the owner's relay is there.+ expect(await buildLaunchOverrides(deps({ ownerRelay: vi.fn(async () => ({ refused: 'No relay here.' })) }).d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'a'))+ .toEqual({ ok: false, error: 'OWNER_RELAY_UNAVAILABLE', unavailable: 'native', detail: 'No relay here.' })// A grid is its own provider: the relay is not asked.ownerRelay.mockClear()await buildLaunchOverrides(deps({ ownerRelay }).d, 'codex', { gridLaunch: GRID }, 'a')diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 22e5ae5fc..16db16025 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -106,7 +106,8 @@ export interface LaunchOverridesDeps {readCodexConfig?: (path: string) => string | null/** In the Harness Team account, for an engine it has not signed in itself: the owner's subscription through the* owner's relay (team/relay.ts `teamRelayLaunch`), null otherwise. Absent ⇒ never. */- ownerRelay?: (engine: AgentEngine) => Promise<{ env: Record<string, string>; args: string[] } | null>+ /** [codexHome]: the launch's own Codex home, whose sign-in and model list are its own (a Swarm Product Manager's). */+ ownerRelay?: (engine: AgentEngine, codexHome?: string) => Promise<{ env: Record<string, string>; args: string[] } | { refused: string } | null>/** Prepare the saved harness context before restarting. Missing or broken packages refuse the* relaunch: starting a plain agent would silently change the user's chosen harness. */dshLaunch?: (dsh: string, workspace: string, engine: AgentEngine, runtimeKey: string) => Promise<DshLaunchAnswer>@@ -349,7 +350,11 @@ async function prepareBaseLaunchOverrides(// In the Harness Team account, an engine it has not signed in itself spends the owner's subscription through the// owner's relay, on every relaunch as on its first: Codex keeps the relay's provider per thread, so it is named again// here in place of its own login's (two `-c model_provider` would leave Codex to pick one).- const relay = await deps.ownerRelay?.(engine) ?? null+ const offered = await (engine === 'codex' && source.codexHome ? deps.ownerRelay?.(engine, source.codexHome) : deps.ownerRelay?.(engine)) ?? null+ // A Codex home of its own the relay cannot sign in (a Product Manager's, its relay not yet published after a reboot): held+ // with why, as a launch that waits is, never relaunched signed out (team/relay.ts).+ if (offered && 'refused' in offered) return { ok: false, error: 'OWNER_RELAY_UNAVAILABLE', unavailable: 'native', detail: offered.refused }+ const relay = offered// Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the// model against the provider it has been given.const provider = relay ? relay.args : ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex 9bbf5fb88..6f13bc278 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -153,6 +153,8 @@ export const LAUNCH_ERROR_CODES = [// The engine itself: preparing it (engines/nativeLaunch.ts) and its start (core/agents/newPane.ts).'engine_cannot_run', 'engine_install_failed', 'engine_did_not_start', 'engine_not_installed', 'start_timeout','engine_launch_refused',+ // A Codex launch in a home of its own (a Swarm Product Manager's) the owner's relay cannot sign in (team/relay.ts).+ 'owner_relay_unavailable',// A Store harness (core/agents/dshThrough.ts, services/storeLaunch.ts).'dsh_not_installed', 'dsh_unavailable', 'dsh_runtime_failed',// A conversation Harness did not start, opened in it (core/agents/adopt.ts, externalResume.ts, lib/registry.ts).diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex 0cbc92a3e..db8604cb4 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -1171,6 +1171,86 @@ describe('TerminalStreamManager', () => {// hn with no terminal (its server, kept for the sessions a closed window left) reads every pane of the desk. On// 2026-10-14 it reopened first after each daemon restart, took the terminals at its 80x24 layout and left the// window the person was using watching a shrunken agent until they typed. It opens with `watch: true` now.+ // A Harness Team daemon running a Swarm Product Manager (#895, superTabs/inCore/teamApps.ts): the Mac owner's apps only+ // watch, and keystrokes arrive as binary frames that no request gate sees (security review 1 of #2089).+ describe('a connection held to watching', () => {+ let held: boolean+ beforeEach(() => {+ held = true+ manager = newManager({ watchOnly: (connId) => held && connId === 'owner-app' })+ })+ const ready = (connId: string) => sent.findLast((frame) => frame.connId === connId && frame.type === 'terminal_ready')!+ const type = (streamId: string, text: string) => manager.handleBinary('owner-app', { kind: TerminalBinaryKind.input, streamId, seq: 0,+ bytes: Buffer.from(text), compressed: false })++ it('opens as a watcher though it asks to take the terminal, and its keystrokes, pastes and resizes reach nothing', async () => {+ await manager.handleFrame('owner-app', 'terminal_open', { requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24 })+ expect(ready('owner-app').payload.readOnly).toBe(true)+ const streamId = ready('owner-app').payload.streamId as string+ await type(streamId, 'cat ~/.claude/projects/*\r')+ await manager.handleBinary('owner-app', { kind: TerminalBinaryKind.paste, streamId, seq: 0, bytes: Buffer.from('ls'), compressed: false })+ await manager.handleFrame('owner-app', 'terminal_resize', { streamId, resizeSeq: 1, cols: 30, rows: 10 })+ expect(sent.at(-1)?.payload.code).toBe('VIEW_ONLY')+ expect([stream.writes, stream.sizes]).toEqual([[], []])+ })++ it('drops the input of a stream it opened before it was held, from then on', async () => {+ held = false+ await manager.handleFrame('owner-app', 'terminal_open', { requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24 })+ expect(ready('owner-app').payload.readOnly).toBe(false)+ const streamId = ready('owner-app').payload.streamId as string+ await type(streamId, 'a')+ await vi.waitFor(() => expect(stream.writes).toHaveLength(1))+ held = true+ await type(streamId, 'b')+ await manager.handleFrame('owner-app', 'terminal_resize', { streamId, resizeSeq: 1, cols: 30, rows: 10 })+ expect(sent.at(-1)?.payload.code).toBe('VIEW_ONLY')+ expect(stream.writes).toHaveLength(1)+ expect(stream.sizes).toEqual([])+ })++ it('leaves every other connection as it was', async () => {+ await manager.handleFrame('desktop-1', 'terminal_open', { requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24 })+ expect(ready('desktop-1').payload.readOnly).toBe(false)+ })+ })++ // Security review 2 of #2089: a session that turned confidential (a Swarm Product Manager, superTabs/inCore/teamApps.ts)+ // after the Mac owner's app opened it went on streaming people's chats to that app.+ describe('a stream on a session that turned confidential', () => {+ let closed: boolean+ beforeEach(() => {+ closed = false+ manager = newManager({ closedTo: (connId, agentId) => closed && connId === 'owner-app' && agentId === 'agent-1' })+ })+ const output = () => binarySent.filter(({ connId, frame }) => connId === 'owner-app' && frame.kind === TerminalBinaryKind.output)++ it('opened before, is closed and sent nothing more, its resync included', async () => {+ await manager.handleFrame('owner-app', 'terminal_open', { requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24 })+ const streamId = sent.findLast(f => f.type === 'terminal_ready')!.payload.streamId as string+ sink!.onData(Buffer.from('before'))+ await vi.advanceTimersByTimeAsync(8)+ const before = output().length+ expect(before).toBeGreaterThan(0)+ closed = true+ sink!.onData(Buffer.from('Only for the PM: the launch slips a week.'))+ await vi.advanceTimersByTimeAsync(2_000)+ expect(output()).toHaveLength(before)+ expect(sent.find(f => f.connId === 'owner-app' && f.type === 'terminal_closed')?.payload).toMatchObject({ code: 'SWARM_CONFIDENTIAL', streamId })+ const sentBefore = binarySent.length+ await manager.handleFrame('owner-app', 'terminal_resync', { streamId })+ await vi.advanceTimersByTimeAsync(100)+ expect(binarySent).toHaveLength(sentBefore)+ })++ it('is not opened again', async () => {+ closed = true+ await manager.handleFrame('owner-app', 'terminal_open', { requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24 })+ expect(sent.at(-1)).toMatchObject({ connId: 'owner-app', payload: expect.objectContaining({ code: 'SWARM_CONFIDENTIAL' }) })+ expect(sent.some(f => f.type === 'terminal_ready')).toBe(false)+ })+ })+describe('a watch-only open', () => {let readOnlyOpens: boolean[]beforeEach(() => {diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex 3f742923d..5e480b1bb 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -206,6 +206,14 @@ interface ActiveStream {export interface TerminalStreamManagerDeps {/** An independent observer manager never acquires the owner control lease. */readOnly?: boolean+ /** A connection held to watching now, whatever it asks (core/api.ts RemoteAppPolicy `watchOnly`): the Mac owner's apps on a+ * Harness Team daemon running a Swarm Product Manager (#895). Asked at each open and each frame, binary input included,+ * so a stream opened before the hold began is held too. */+ watchOnly?: (connId: string) => boolean+ /** Whether [agentId]'s terminal is closed to [connId] now (core/api.ts RemoteAppPolicy): a session that turned confidential+ * on a Harness Team daemon. Asked before anything more is sent on a stream, at each frame its client sends, and at open,+ * so a stream opened before the mark closes (security review 2 of #2089). */+ closedTo?: (connId: string, agentId: string) => booleanterminals: TerminalBackendCoordinatorresolveAgent: (agentId: string) => RegisteredSession | undefinedsendTarget: (connId: string, type: string, payload: FramePayload) => boolean@@ -330,7 +338,17 @@ export class TerminalStreamManager {return state?.connId === connId && state.watching}+ /** Closes [state] when its session is closed to its client now (`closedTo`), and says whether it did. */+ private closedNow(state: ActiveStream): boolean {+ if (state.closing) return true+ if (!this.deps.closedTo?.(state.connId, state.agentId)) return false+ void this.closeStream(state, 'session became confidential', true, 'SWARM_CONFIDENTIAL')+ return true+ }+async handleFrame(connId: string, type: string, payload: FramePayload): Promise<boolean> {+ const named = typeof payload.streamId === 'string' ? this.streams.get(payload.streamId) : undefined+ if (named && named.connId === connId && this.closedNow(named)) return trueif (this.deps.readOnly && !TerminalStreamManager.WATCH_SAFE_TYPES.includes(type)) {this.sendError(connId, 'VIEW_ONLY', { requestId: payload.requestId })return true@@ -339,7 +357,7 @@ export class TerminalStreamManager {// controller, so anything that reaches tmux — input, resize, paste, scroll, an upload — has to// be stopped, and stopping them one by one is how the next write path added gets forgotten.// Same allow-list a read-only deployment uses, for the same reason.- if (!TerminalStreamManager.WATCH_SAFE_TYPES.includes(type) && this.isWatching(connId, payload)) {+ if (!TerminalStreamManager.WATCH_SAFE_TYPES.includes(type) && (this.isWatching(connId, payload) || this.deps.watchOnly?.(connId) === true)) {this.sendError(connId, 'VIEW_ONLY', {requestId: payload.requestId,streamId: typeof payload.streamId === 'string' ? payload.streamId : undefined,@@ -399,11 +417,11 @@ export class TerminalStreamManager {// Every binary kind below writes to the terminal, so a watcher's are dropped outright — see the// gate in `handleFrame`. Silent, like the other drops here: the client already knows it is// read-only (`terminal_ready`) and withholds input itself; this is the backstop.- if (this.isWatching(connId, { streamId: frame.streamId })) return+ if (this.isWatching(connId, { streamId: frame.streamId }) || this.deps.watchOnly?.(connId) === true) returnif (frame.kind !== TerminalBinaryKind.input && frame.kind !== TerminalBinaryKind.paste&& frame.kind !== TerminalBinaryKind.imagePaste && frame.kind !== TerminalBinaryKind.pasteFile) returnconst state = this.streams.get(frame.streamId)- if (!state || state.connId !== connId || state.closing) return+ if (!state || state.connId !== connId || this.closedNow(state)) returnif (frame.kind === TerminalBinaryKind.imagePaste || frame.kind === TerminalBinaryKind.pasteFile) {await this.receiveUploadChunk(state, frame.kind, frame.seq, frame.bytes)return@@ -492,6 +510,10 @@ export class TerminalStreamManager {this.sendError(connId, 'TERMINAL_OPEN_INVALID', { requestId })return}+ if (this.deps.closedTo?.(connId, agentId)) {+ this.sendError(connId, 'SWARM_CONFIDENTIAL', { requestId })+ return+ }if (!this.deps.streamingAvailable) {this.sendError(connId, 'TERMINAL_RUNTIME_UNAVAILABLE', { requestId })return@@ -550,7 +572,7 @@ export class TerminalStreamManager {// A watch-only stream is not anyone holding it: a window reconnecting politely beside one is// answered as it would be alone, not made to watch a terminal nobody drives.const holders = incumbents.filter((state) => !state.watchOnly)- const watching = !this.deps.readOnly && (watchOnly || (!takeover && holders.length > 0))+ const watching = !this.deps.readOnly && (watchOnly || this.deps.watchOnly?.(connId) === true || (!takeover && holders.length > 0))// Who a watcher is watching, named on its banner — "MacBook Pro is using this terminal" — as// `takenBy` names the winner on the incumbent's. Read now, before any stream below moves.const heldBy = watching ? this.holderOf(holders, reservedPlacement) : undefined@@ -1321,7 +1343,7 @@ export class TerminalStreamManager {private flushOutput(state: ActiveStream): void {if (state.flushTimer) { clearTimeout(state.flushTimer); state.flushTimer = null }- if (state.closing || state.snapshotting || state.outputBytes === 0) return+ if (state.closing || state.snapshotting || state.outputBytes === 0 || this.closedNow(state)) returnstate.lastFlushAt = this.now()const all = Buffer.concat(state.output, state.outputBytes)state.output = []@@ -1490,6 +1512,7 @@ export class TerminalStreamManager {await this.closeStream(state, 'terminal snapshot exceeds safe envelope size', false)return}+ if (this.closedNow(state)) returnconst bytes = Buffer.from(snapshot.value.bytes)state.pending = []state.pendingBytes = 0@@ -1540,7 +1563,7 @@ export class TerminalStreamManager {}private sendSync(state: ActiveStream, now: number): void {- if (state.closing || state.snapshotting || state.resyncing || state.outputPaused) return+ if (state.closing || state.snapshotting || state.resyncing || state.outputPaused || this.closedNow(state)) returnthis.flushOutput(state)if (state.closing || state.outputPaused) returnconst seq = state.nextSeq++diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.tsindex 57bb0cae6..fa287aba5 100644--- a/cli/src/superTabs/inCore.ts+++ b/cli/src/superTabs/inCore.ts@@ -17,6 +17,7 @@ export { swarmRoleThrough } from './inCore/role.js'export { createSwarmSkillAdoption } from './inCore/adoption.js'export { createSwarmAgents } from './inCore/agents.js'export { SWARM_LAUNCH } from './inCore/launch.js'+export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor } from './inCore/teamApps.js'export { typesWhileBusy } from './inCore/deliveries.js'export { mayBeLead, retainedHarnesses, retainedLeads } from './retention.js'export { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'diff --git a/cli/src/superTabs/inCore/agents.spec.ts b/cli/src/superTabs/inCore/agents.spec.tsindex c9721d19d..06a27da0f 100644--- a/cli/src/superTabs/inCore/agents.spec.ts+++ b/cli/src/superTabs/inCore/agents.spec.ts@@ -84,6 +84,60 @@ describe('the Swarm\'s agents, as the core lets it close and reopen them', () =>expect(await createSwarmAgents({ ...deps(), members: { leads, harnesses: () => new Set() } }).keepLeadAlive('stopped')).toEqual({ ok: false, error: 'UNSUPPORTED' })})+ // A Product Manager removed or replaced for good on a Team daemon: the Swarm keeps its chats, and its session files go+ // (superTabs/inCore/teamApps.ts createConfidentialPurge). A purge that fails fails the close, so its host tries again with+ // backoff and its Team account stays held (security re-check 1 and 2 of #2089).+ it('deletes, once it closed a member or found it gone, what the Team daemon purges, and fails the close until it has', async () => {+ const closeAgent = vi.fn(async () => ({ closed: true as const }))+ const byAgent = (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined+ const purgeEnded = vi.fn(async (_agentId: string) => ({ ok: true }))+ const harnesses = vi.fn(() => new Set(['live']))+ const swarm = createSwarmAgents({ ...deps({ byAgent, closeAgent }), members: { leads: () => new Set(), harnesses }, purgeEnded })+ expect(await swarm.closeMember('live')).toEqual({ closed: true })+ expect(await swarm.closeMember('absent')).toEqual({ closed: true })+ expect(purgeEnded.mock.calls.map(([id]) => id)).toEqual(['live', 'absent'])+ harnesses.mockReturnValue(new Set())+ expect(await swarm.closeMember('live')).toEqual({ error: 'NOT_A_MEMBER' })+ expect(purgeEnded).toHaveBeenCalledTimes(2)+ purgeEnded.mockRejectedValueOnce(new Error('EIO'))+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'EIO' })+ purgeEnded.mockResolvedValueOnce({ error: 'SCRUB_INCOMPLETE', detail: 'Something still names the session: /x' } as never)+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'Something still names the session: /x' })+ purgeEnded.mockRejectedValueOnce('disk full')+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'disk full' })+ purgeEnded.mockResolvedValueOnce({ error: 'NOT_FOUND' } as never)+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'NOT_FOUND' })+ // A close that failed deletes nothing: the session is still there.+ harnesses.mockReturnValue(new Set(['live']))+ closeAgent.mockResolvedValueOnce({ error: 'AGENT_CHANGED' } as never)+ purgeEnded.mockClear()+ expect(await swarm.closeMember('live')).toEqual({ error: 'AGENT_CHANGED' })+ expect(purgeEnded).not.toHaveBeenCalled()+ })++ // A worker in a private chat ends through the stop path, which never purged (security re-check 1 of #2089).+ it('purges on the Swarm\'s stop too, closed now or already gone, and fails the stop until it has', 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 }+ let present = true+ const byAgent = vi.fn(() => present ? session as RegisteredSession : undefined)+ const closeAgent = vi.fn(async () => ({ closed: true as const }))+ const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))+ const purgeEnded = vi.fn(async (_agentId: string) => ({ ok: true }))+ const swarm = createSwarmAgents({ ...deps({ byAgent, closeAgent, creationStatus }), members: NO_MEMBERS, purgeEnded })+ expect(await swarm.closeSwarm(request)).toEqual({ closed: true })+ expect(purgeEnded).toHaveBeenCalledWith('worker')+ // A stop that failed deletes nothing.+ closeAgent.mockResolvedValueOnce({ error: 'AGENT_CHANGED' } as never)+ purgeEnded.mockClear()+ expect(await swarm.closeSwarm(request)).toEqual({ error: 'AGENT_CHANGED' })+ expect(purgeEnded).not.toHaveBeenCalled()+ present = false+ purgeEnded.mockResolvedValueOnce({ error: 'SCRUB_INCOMPLETE', detail: 'left' } as never)+ expect(await swarm.closeSwarm(request)).toEqual({ error: 'PURGE_FAILED', detail: 'left' })+ expect(await swarm.closeSwarm(request)).toEqual({ closed: true })+ })+it('closes now only a Super Tab member the host retains, and treats an absent one as closed', async () => {const closeAgent = vi.fn(async () => ({ closed: true as const }))const byAgent = (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefineddiff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.tsindex 5c392118f..df72f3654 100644--- a/cli/src/superTabs/inCore/agents.ts+++ b/cli/src/superTabs/inCore/agents.ts@@ -6,15 +6,28 @@*/import type { SwarmAgentDeps, SwarmAgents } from '../../core/api.js'-export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members }: SwarmAgentDeps & {+export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members, purgeEnded }: SwarmAgentDeps & {/** The Leads and members this machine's Super Tab host keeps (superTabs/retention.ts). */members: { leads(): Set<string>; harnesses(): Set<string> }+ /** On a Team daemon, deletes the session data of a confidential member the Swarm ended (inCore/teamApps.ts); absent elsewhere. */+ purgeEnded?: (agentId: string) => Promise<Record<string, unknown>>}): SwarmAgents {+ /** A member the Swarm ended for good, closed or already gone: its data goes where the Team daemon says so. Until it has,+ * the close fails, so its host tries again with backoff (superTabs/host.ts endSession) and its Team account stays held+ * (security re-check 1 and 2 of #2089). The close's own answer when there is nothing to delete or it went. */+ const ended = async <T>(agentId: string, closed: T): Promise<T | { error: 'PURGE_FAILED'; detail: string }> => {+ if (!purgeEnded) return closed+ const said = await purgeEnded(agentId).catch((error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }))+ if (typeof said.error !== 'string') return closed+ const detail = typeof (said as Record<string, unknown>).detail === 'string' ? (said as Record<string, unknown>).detail as string : said.error+ console.warn(`[super-tabs] could not delete the session data of ${agentId}: ${detail}`)+ return { error: 'PURGE_FAILED', detail }+ }return {closeSwarm: async request => {const session = 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) return ended(request.agentId, { closed: true as const })// 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' }@@ -25,7 +38,9 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgentconst latest = byAgent(request.agentId)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' }+ if (!closeAgent) return { error: 'UNSUPPORTED' }+ const closed = await closeAgent({ agentId: request.agentId, sessionId: request.sessionId, createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt })+ return 'closed' in closed && closed.closed ? ended(request.agentId, closed) : closed},keepLeadAlive: async agentId => {if (!resumeAgent) return { ok: false, error: 'UNSUPPORTED' }@@ -39,7 +54,7 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgentcloseMember: async (agentId, creationId) => {if (!closeAgent) return { error: 'UNSUPPORTED' }const session = byAgent(agentId)- if (!session) return { closed: true }+ if (!session) return ended(agentId, { closed: true as const })let member = falsetry { member = members.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).@@ -49,7 +64,8 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent}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' })+ const closed = await closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'now' })+ return 'closed' in closed && closed.closed ? ended(agentId, closed) : closed},}}diff --git a/cli/src/superTabs/inCore/teamApps.spec.ts b/cli/src/superTabs/inCore/teamApps.spec.tsnew file mode 100644index 000000000..75186eaa8--- /dev/null+++ b/cli/src/superTabs/inCore/teamApps.spec.ts@@ -0,0 +1,331 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir, userInfo } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'++// Never this Mac's own Team config or sign-in: a throwaway path, and a sign-in the test sets.+const fixtures = vi.hoisted(() => ({ configFile: '', signedIn: null as null | { kind: string } }))+vi.mock('../../team/layout.js', async (original) => ({ ...await original<object>(), get TEAM_CONFIG_FILE() { return fixtures.configFile } }))+vi.mock('../../lib/authSession.js', async (original) => ({ ...await original<object>(), readAuthSession: () => fixtures.signedIn }))+import { CONFIDENTIAL_RECORD_MAX, confidentialRecord, confidentialRecordFile, createTeamAppPolicy, isTeamDaemon,+ pmEngineHome, purgeRecord, readConfidentialMarks, teamAppPolicyFor, type HeldSession, type TeamAppDeps } from './teamApps.js'++// A Harness Team daemon's own account's apps: the Mac owner's (#895). The Swarm's Product Manager there reads people's+// private chats, so those apps never reach a confidential session, and while one runs there they only watch the others:+// every agent there is one macOS user, and typing in any of them, or starting one, is a shell that reads its files.++const dir = () => mkdtempSync(join(tmpdir(), 'team-apps-'))++/** A Team daemon holding [sessions], running or stopped, whose Swarm marked [marks] confidential (null: the+ * marks could not be read), with [recorded] kept from before. */+function policy(marks: string[] | null, sessions: Array<Partial<HeldSession> & { agentId: string }>, recorded: string[] = []) {+ const kept = [...recorded]+ const record = vi.fn((ids: string[]) => { kept.push(...ids) })+ // A fresh reading for every call: these tests change nothing between calls, and the cache has its own test below.+ let clock = 0+ const p = createTeamAppPolicy({ marks: () => marks, live: () => sessions.map(s => ({ lead: false, ...s })), stopped: () => [],+ recorded: () => kept, record, now: () => (clock += 10_000) })+ return Object.assign(p, { record, kept })+}++describe('the Mac owner\'s apps on a Team daemon running a Product Manager', () => {+ const running = () => policy(['pm'], [{ agentId: 'pm', sessionId: 'pm-session' }, { agentId: 'worker', sessionId: 'worker-session' }])++ it('reach nothing of the Product Manager, by any field that names it: its agent id or its engine\'s session id', () => {+ const p = running()+ for (const type of ['terminal_open', 'terminal_info', 'message', 'question_response', 'sessions_list', 'agent_recent',+ 'agent_read_file', 'agent_update', 'agent_close', 'agent_fork', 'agent_restart', 'agent_resume']) {+ expect(p.refuse(type, { agentId: 'pm' }), type).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ }+ // `session_get` names it by `sessionId`, which the history reader also matches to an agent's id.+ expect(p.refuse('session_get', { sessionId: 'pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.refuse('session_get', { sessionId: 'pm-session' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ for (const payload of [{ id: 'pm' }, { harnessId: 'pm' }, { parentAgentId: 'pm' }, { resumeSessionId: 'pm-session' }, { expectedSessionId: 'pm-session' },+ { agentIds: ['worker', 'pm'] }, { sessionIds: ['pm-session'] }, { agents: [{ id: 'pm' }] }, { sessions: [{ sessionId: 'pm-session' }] }]) {+ expect(p.refuse('agents_cleanup', payload), JSON.stringify(payload)).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ }+ })++ it('watch the other agents there, but type in none and start none', () => {+ const p = running()+ for (const type of ['terminal_open', 'terminal_info', 'sessions_list', 'agent_recent']) expect(p.refuse(type, { agentId: 'worker' }), type).toBeNull()+ expect(p.refuse('session_get', { sessionId: 'worker-session' })).toBeNull()+ expect(p.refuse('agents_list', {})).toBeNull()+ for (const [type, payload] of [['terminal_input', { streamId: 's' }], ['terminal_resize', { streamId: 's' }], ['terminal_scroll', { streamId: 's' }],+ ['message', { agentId: 'worker' }], ['agent_create', { engine: 'claude' }], ['agent_fork', { agentId: 'worker' }], ['shell', { op: 'open' }],+ ['fs_list_dir', { path: '/' }]] as const) {+ expect(p.refuse(type, payload), type).toMatchObject({ error: 'TEAM_READ_ONLY' })+ }+ expect(p.watchOnly()).toBe(true)+ })++ it('never hear of the Product Manager: its events are withheld and it is left out of lists', () => {+ const p = running()+ expect(p.event({ type: 'agent_synced', payload: { agent: { id: 'pm' } } })).toBeNull()+ expect(p.event({ type: 'text_delta', payload: { agentId: 'pm', text: 'private' } })).toBeNull()+ expect(p.event({ type: 'turn', agentId: 'pm', payload: {} })).toBeNull()+ expect(p.event({ type: 'agent_synced', payload: { agent: { id: 'worker' } } })).toEqual({ type: 'agent_synced', payload: { agent: { id: 'worker' } } })+ expect(p.event({ type: 'agents_list', payload: { agents: [{ id: 'pm' }, { id: 'worker' }] } }))+ .toEqual({ type: 'agents_list', payload: { agents: [{ id: 'worker' }] } })+ expect(p.event({ type: 'ping', payload: [1] })).toEqual({ type: 'ping', payload: [1] })+ // Only plain objects and lists are walked: a Date, a Buffer or a class instance in an answer is left as it is.+ const at = new Date(5), bytes = Buffer.from('x')+ class Row { constructor(readonly agentId: string) {} }+ const row = new Row('pm')+ const kept = p.reply('agents_list', { at, bytes, row, agents: [{ id: 'worker', at }] })+ expect(kept.at).toBe(at)+ expect(kept.bytes).toBe(bytes)+ expect(kept.row).toBe(row)+ expect((kept.agents as Array<{ at: Date }>)[0]!.at).toBe(at)+ // Rows that name no session, or a session no one holds, are kept; list items that are neither ids nor rows name nothing.+ expect(p.reply('agents_list', { agents: [null, 'row', { id: 'elsewhere' }] })).toEqual({ agents: [null, 'row', { id: 'elsewhere' }] })+ expect(p.refuse('agents_cleanup', { agentIds: [7, null, 'worker'] })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ expect(p.reply('agents_list', { agents: [{ id: 'pm' }, { id: 'worker' }] })).toEqual({ agents: [{ id: 'worker' }] })+ expect(p.reply('sessions_list', { sessions: [{ sessionId: 'pm-session' }, { sessionId: 'worker-session' }] }))+ .toEqual({ sessions: [{ sessionId: 'worker-session' }] })+ })++ it('treat a Product Manager as confidential from its launch, before any roster marks it, and keep a record of it', () => {+ const p = policy([], [{ agentId: 'pm', lead: true }, { agentId: 'worker' }])+ expect(p.refuse('terminal_open', { agentId: 'pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ expect(p.record).toHaveBeenCalledWith(['pm'])+ p.refuse('terminal_open', { agentId: 'worker' })+ expect(p.record).toHaveBeenCalledOnce()+ })+})++describe('a Product Manager that stopped', () => {+ it('stays closed to the owner\'s apps by its record, and keeps the account held while it may resume', () => {+ const p = policy([], [{ agentId: 'pm', sessionId: 'pm-session' }, { agentId: 'worker' }], ['pm'])+ expect(p.refuse('session_get', { sessionId: 'pm-session' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.refuse('agent_resume', { agentId: 'pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.reply('agents_list', { agents: [{ id: 'pm' }, { id: 'worker' }] })).toEqual({ agents: [{ id: 'worker' }] })+ // Stopped (a crash, a restart, a limit), it may resume: the others are still only watched, and no new agent starts+ // there to read its saved session (security review 2 of #2089).+ expect(p.watchOnly()).toBe(true)+ expect(p.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ expect(p.refuse('agent_create', { engine: 'claude', cwd: '/team' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ // Search finds nothing of it: its hits and catalog rows, by agent or by session, at any depth of the answer.+ expect(p.reply('session_search', { hits: [{ agentId: 'pm', text: 'launch slips' }, { sessionId: 'pm-session' }, { agentId: 'worker', text: 'ok' }],+ catalog: { rows: [{ agentId: 'pm' }, { agentId: 'worker' }] }, total: 3 }))+ .toEqual({ hits: [{ agentId: 'worker', text: 'ok' }], catalog: { rows: [{ agentId: 'worker' }] }, total: 3 })+ expect(p.event({ type: 'search_results', payload: { results: [{ hit: { sessionId: 'pm-session' } }, { hit: { agentId: 'worker' } }] } }))+ .toEqual({ type: 'search_results', payload: { results: [{ hit: { agentId: 'worker' } }] } })+ })++ it('once its session data is deleted, leaves the account as today, still closed by its record', () => {+ const p = policy([], [{ agentId: 'worker' }], ['pm'])+ expect(p.watchOnly()).toBe(false)+ expect(p.refuse('message', { agentId: 'worker' })).toBeNull()+ expect(p.refuse('agent_resume', { agentId: 'pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })++ it('kept under a new agent id, is still found by its engine session, which the record keeps too', () => {+ const p = policy(['pm'], [{ agentId: 'pm', sessionId: 'pm-session' }])+ p.refuse('agents_list', {})+ expect(p.kept).toEqual(['pm', 'pm-session'])+ // The roster's mark went with the old agent id; the same conversation, registered again, is still closed.+ const later = policy([], [{ agentId: 'pm-again', sessionId: 'pm-session' }], p.kept)+ expect(later.refuse('session_get', { sessionId: 'pm-session' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(later.refuse('terminal_open', { agentId: 'pm-again' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })+})++// Security re-review of #2089: the guard runs inside the daemon's broadcast. One that throws broke that frame and every later+// one, so it fails closed instead, and reads what it needs once per burst of frames, not once per frame.+describe('the policy when what it reads fails', () => {+ const failing = (what: keyof TeamAppDeps) => {+ const deps: TeamAppDeps = { marks: () => [], live: () => [{ agentId: 'worker', lead: false }], stopped: () => [], recorded: () => [], record: () => {} }+ deps[what] = (() => { throw new Error('EIO: disk') }) as never+ if (what === 'record') deps.marks = () => ['pm']+ return createTeamAppPolicy(deps)+ }+ it.each(['marks', 'live', 'stopped', 'recorded', 'record'] as const)('fails closed, without throwing, when %s fails', what => {+ const p = failing(what)+ expect(p.event({ type: 'agent_synced', payload: { agent: { id: 'worker' } } })).toBeNull()+ expect(p.refuse('agents_list', {})).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.reply('agents_list', { agents: [{ id: 'worker' }], ok: true })).toEqual({ agents: [], ok: true })+ expect(p.watchOnly()).toBe(true)+ })+ it('lists the stopped sessions on disk once for frames close together, and again after', () => {+ let clock = 1_000+ const stopped = vi.fn(() => [{ agentId: 'old', lead: false }])+ const p = createTeamAppPolicy({ marks: () => [], live: () => [{ agentId: 'worker', lead: false }], stopped, recorded: () => [], record: () => {}, now: () => clock })+ for (let i = 0; i < 5; i++) p.event({ type: 'text_delta', payload: { agentId: 'worker' } })+ expect(stopped).toHaveBeenCalledOnce()+ clock += 1_000+ p.event({ type: 'text_delta', payload: { agentId: 'worker' } })+ expect(stopped).toHaveBeenCalledTimes(2)+ })+ // Security re-check 1 of #2089: a cached reading let a Product Manager registered in the next half second, or a worker the+ // roster just marked, leak its launch and take input. What is in memory, and the marks, are read every time.+ it('refuses at once a Product Manager registered, or a session marked, right after a reading', () => {+ const live = [{ agentId: 'worker', lead: false }]+ let marks: string[] = []+ const p = createTeamAppPolicy({ marks: () => marks, live: () => live, stopped: () => [], recorded: () => [], record: () => {}, now: () => 1_000 })+ expect(p.refuse('message', { agentId: 'worker' })).toBeNull()+ live.push({ agentId: 'pm', lead: true })+ expect(p.event({ type: 'agent_synced', payload: { agent: { id: 'pm' } } })).toBeNull()+ expect(p.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ live.pop()+ expect(p.refuse('message', { agentId: 'worker' })).toBeNull()+ marks = ['worker']+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })+})++// Security re-check 3 of #2089: a purge still to finish (inCore/teamPurge.ts) keeps the account held, its session closed.+describe('a Codex Product Manager\'s engine home', () => {+ it('is its own on a Team daemon, under one root, and none for anyone else', () => {+ expect(pmEngineHome('codex', 'super-start-1', true, '/Users/team')).toBe('/Users/team/.harness-pm-homes/super-start-1/codex')+ expect(pmEngineHome('claude', 'super-start-1', true, '/Users/team')).toBeNull()+ expect(pmEngineHome('codex', 'super-start-1', false, '/Users/team')).toBeNull()+ expect(pmEngineHome('codex', '../escape', true, '/Users/team')).toBeNull()+ })+})++describe('a Team daemon with a purge still to finish', () => {+ it('keeps the account held and the session closed until it finishes, and when its record cannot be read', () => {+ let purging: { ids: string[]; unknown: boolean } = { ids: ['pm'], unknown: false }+ const p = createTeamAppPolicy({ marks: () => [], live: () => [{ agentId: 'worker', lead: false }], stopped: () => [], recorded: () => [], record: () => {},+ purging: () => purging })+ expect(p.refuse('terminal_open', { agentId: 'pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ expect(p.watchOnly()).toBe(true)+ purging = { ids: [], unknown: true }+ expect(p.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ purging = { ids: [], unknown: false }+ expect(p.refuse('message', { agentId: 'worker' })).toBeNull()+ })+})++describe('the Mac owner\'s apps on a Team daemon whose marks cannot be read', () => {+ it('reach no session, and type in or start nothing, and are told it waits for its Swarm, not that it holds private chats', () => {+ const p = policy(null, [{ agentId: 'worker' }])+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toEqual({ error: 'SWARM_CONFIDENTIAL',+ message: 'This computer\'s Harness Team account has not heard from its Swarm yet, so its agents are not shown here until it does.' })+ // A start is told the same: no Product Manager is known to run there (security re-check 2 of #2089).+ expect(p.refuse('agent_create', { engine: 'claude' })).toEqual({ error: 'TEAM_READ_ONLY',+ message: 'This computer\'s Harness Team account has not heard from its Swarm yet, so its agents can be watched here but not typed in, and no agent can be started in it until it does.' })+ expect(p.event({ type: 'agent_synced', payload: { agent: { id: 'worker' } } })).toBeNull()+ expect(p.watchOnly()).toBe(true)+ })+})++// Security re-check 3 of #2089: a reading that failed, or marks that are there but cannot be read, said the account had not+// heard from its Swarm yet. They say it could not read them.+describe('the Mac owner\'s apps when what the guard reads cannot be read', () => {+ const COULD_NOT = { error: 'SWARM_CONFIDENTIAL', message: 'This computer\'s Harness Team account could not read its Swarm\'s settings, so its agents are not shown here.' }+ const COULD_NOT_START = { error: 'TEAM_READ_ONLY', message: 'This computer\'s Harness Team account could not read its Swarm\'s settings, so its agents can be watched here but not typed in, and no agent can be started in it.' }+ it('say they could not be read, when the marks are there but unreadable', () => {+ const p = createTeamAppPolicy({ marks: () => null, heard: () => true, live: () => [{ agentId: 'worker', lead: false }], stopped: () => [], recorded: () => [], record: () => {} })+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toEqual(COULD_NOT)+ expect(p.refuse('agent_create', { engine: 'claude' })).toEqual(COULD_NOT_START)+ })+ it('say they could not be read, when a reading failed', () => {+ const p = createTeamAppPolicy({ marks: () => { throw new Error('EIO') }, live: () => [], stopped: () => [], recorded: () => [], record: () => {} })+ expect(p.refuse('agents_list', {})).toEqual(COULD_NOT)+ })+})++describe('the Mac owner\'s apps on a Team daemon running only workers', () => {+ it('behave as today', () => {+ const p = policy([], [{ agentId: 'worker' }])+ expect(p.refuse('message', { agentId: 'worker' })).toBeNull()+ expect(p.refuse('agent_create', { engine: 'claude' })).toBeNull()+ expect(p.event({ type: 'text_delta', payload: { agentId: 'worker' } })).not.toBeNull()+ expect(p.watchOnly()).toBe(false)+ })+})++describe('whether a daemon is a Team account\'s, decided at startup', () => {+ const config = (user: string) => ({ user }) as never+ it('is, when the Team config names this macOS user, or the config cannot be read, or it is signed in as a Team account', () => {+ expect(isTeamDaemon({ configExists: () => true, config: () => config('_harness-team'), user: () => '_harness-team', signedInAsTeam: () => false })).toBe(true)+ expect(isTeamDaemon({ configExists: () => true, config: () => null, user: () => 'owner', signedInAsTeam: () => false })).toBe(true)+ expect(isTeamDaemon({ configExists: () => false, signedInAsTeam: () => true })).toBe(true)+ })+ it('reads this computer\'s Team config, user and sign-in when nothing else is given', () => {+ const d = dir()+ fixtures.configFile = join(d, 'team.json')+ fixtures.signedIn = null+ expect(isTeamDaemon()).toBe(false)+ writeFileSync(fixtures.configFile, 'not json')+ expect(isTeamDaemon()).toBe(true)+ fixtures.signedIn = { kind: 'team' }+ rmSync(fixtures.configFile)+ expect(isTeamDaemon()).toBe(true)+ expect(userInfo().username).toBeTruthy()+ })+ it('is not, for the Mac owner\'s own daemon beside a Team account, or a Mac without one', () => {+ expect(isTeamDaemon({ configExists: () => true, config: () => config('_harness-team'), user: () => 'owner', signedInAsTeam: () => false })).toBe(false)+ expect(isTeamDaemon({ configExists: () => false, signedInAsTeam: () => false })).toBe(false)+ })+})++describe('the Swarm\'s confidential marks, read for the guard', () => {+ it('are the snapshot\'s, for this machine', () => {+ const file = join(dir(), 'observers.json')+ writeFileSync(file, JSON.stringify({ machineId: 'team-mac', confidential: ['pm', 7] }))+ expect(readConfidentialMarks(file, 'team-mac')).toEqual(['pm'])+ })+ it('are unknown when the snapshot is missing, unreadable, or another machine\'s', () => {+ const d = dir()+ expect(readConfidentialMarks(join(d, 'missing.json'), 'team-mac')).toBeNull()+ writeFileSync(join(d, 'bad.json'), '{')+ expect(readConfidentialMarks(join(d, 'bad.json'), 'team-mac')).toBeNull()+ writeFileSync(join(d, 'null.json'), 'null')+ expect(readConfidentialMarks(join(d, 'null.json'), 'team-mac')).toBeNull()+ writeFileSync(join(d, 'other.json'), JSON.stringify({ machineId: 'other', confidential: [] }))+ expect(readConfidentialMarks(join(d, 'other.json'), 'team-mac')).toBeNull()+ })+})++describe('the record of confidential sessions', () => {+ it('keeps what it is given across restarts, newest last, and at most its bound', () => {+ const file = confidentialRecordFile(dir())+ const first = confidentialRecord(file)+ expect([first.ids(), first.unknown()]).toEqual([[], false])+ first.add(['a', 'b'])+ first.add(['a'])+ expect(confidentialRecord(file).ids()).toEqual(['b', 'a'])+ const many = Array.from({ length: CONFIDENTIAL_RECORD_MAX + 1 }, (_, i) => `s${i}`)+ first.add(many)+ expect(JSON.parse(readFileSync(file, 'utf8'))).toHaveLength(CONFIDENTIAL_RECORD_MAX)+ })+ it('with no marks snapshot yet, counts every session confidential', () => {+ const p = teamAppPolicyFor(dir(), () => 'team-mac', () => [{ agentId: 'worker' }], () => [])+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })+ it('read but unreadable, is unknown: every session then counts as confidential', () => {+ const d = dir(), file = confidentialRecordFile(d)+ confidentialRecord(file).add(['pm'])+ writeFileSync(file, '{')+ expect(confidentialRecord(file).unknown()).toBe(true)+ writeFileSync(file, '{"not":"a list"}')+ expect(confidentialRecord(file).unknown()).toBe(true)+ const p = teamAppPolicyFor(d, () => 'team-mac', () => [{ agentId: 'worker' }], () => [])+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })+})++describe('the policy as the core runs it', () => {+ it('reads the Swarm\'s marks and keeps a launched Product Manager in its record', () => {+ const d = dir()+ const snapshot = join(d, 'super-tabs', 'observers-team-mac.json')+ confidentialRecord(confidentialRecordFile(d)).add([])+ writeFileSync(snapshot, JSON.stringify({ machineId: 'team-mac', confidential: ['marked'] }))+ const p = teamAppPolicyFor(d, () => 'team-mac', () => [{ agentId: 'pm', sessionId: null, swarmSkill: { role: 'lead' } }, { agentId: 'marked' }, { agentId: 'worker' }], () => [])+ expect(p.refuse('terminal_open', { agentId: 'marked' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ expect(p.refuse('terminal_open', { agentId: 'worker' })).toBeNull()+ expect(confidentialRecord(confidentialRecordFile(d)).ids()).toEqual(['marked', 'pm'])+ expect(p.isConfidential('marked')).toBe(true)+ // With a purge still to finish in its record, the account is held and that session closed.+ const purges = purgeRecord(join(d, 'super-tabs', 'team-purges.json'))+ purges.put({ agentId: 'gone-pm', sessionId: null, cwd: null, engine: 'claude', codexHome: null })+ const held = teamAppPolicyFor(d, () => 'team-mac', () => [{ agentId: 'worker' }], () => [], purges)+ expect(held.refuse('message', { agentId: 'worker' })).toMatchObject({ error: 'TEAM_READ_ONLY' })+ expect(held.refuse('agent_resume', { agentId: 'gone-pm' })).toMatchObject({ error: 'SWARM_CONFIDENTIAL' })+ })+})diff --git a/cli/src/superTabs/inCore/teamApps.ts b/cli/src/superTabs/inCore/teamApps.tsnew file mode 100644index 000000000..e5f374982--- /dev/null+++ b/cli/src/superTabs/inCore/teamApps.ts@@ -0,0 +1,234 @@+/**+ * What a Harness Team daemon's own account's apps may ask of it and hear from it (#895). The Team account is a machine in+ * the Mac owner's own Harness account, and the owner's apps select it like any of theirs (backend lib/teamSession.ts). Once+ * the Swarm runs another person's Product Manager there, that would let the Mac's owner attach to it and read or type in+ * people's private chats with it, past every rule the Swarm keeps (backend projects.ts teamSessionAccess). So, from the+ * owner's apps (backendSocket.ts `remoteAppPolicy`), on a Team daemon only, decided once at startup (`isTeamDaemon`):+ *+ * - A confidential session is never reached, listed or heard of: one the Swarm's roster marked (a Product Manager, or an+ * agent in a private chat), one launched here as a Product Manager before any roster marks it, and either of those after+ * it stopped (the record kept in `confidentialRecordFile`). Every field of a request that can name a session, an agent's+ * id or its engine's session id, is resolved to the agent first (security review 1 of #2089: `session_get` names a+ * session by `sessionId`, which also finds an agent by its id).+ * - While one is here, running or stopped (it may resume), the others are watched only: every agent of a Team account is one macOS user, so typing in any of+ * them, or starting one, is a shell that reads the confidential session's files. Only requests that read are answered,+ * and the owner's terminal streams are watch-only, their binary input and resizes dropped (terminalStreamManager.ts+ * `watchOnly`), streams opened before it started included.+ * - A record or marks that cannot be read count as every session confidential.+ */+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import type { RemoteAppPolicy } from '../../core/api.js'+import { eventAgentId } from '../../core/guestPolicy.js'+import { observerSnapshotFile } from '../../sharing/swarmMarks.js'+import type { PurgeRecord } from './teamPurge.js'+export { isTeamDaemon, pmEngineHome, PM_HOMES } from '../teamDaemon.js'+export { createConfidentialPurge, purgeRecord } from './teamPurge.js'++/** Answered while a confidential session runs here: each only reads, and those naming a session only a non-confidential one.+ * A terminal stream's frames are its own (terminalStreamManager.ts): it is watch-only, and only these reach it. */+const READS: ReadonlySet<string> = new Set([+ 'agents_list', 'sessions_list', 'session_get', 'agent_recent', 'engines_probe', 'theme_set', 'usage_read',+ 'terminal_capabilities', 'terminal_open', 'terminal_info', 'terminal_alive', 'terminal_ack', 'terminal_resync', 'terminal_close',+])+/** The fields of a request that can name a session: an agent's id, or its engine's session id. */+const SESSION_FIELDS = ['agentId', 'sessionId', 'id', 'harnessId', 'parentAgentId', 'resumeSessionId', 'expectedSessionId'] as const+const SESSION_LISTS = ['agentIds', 'sessionIds', 'agents', 'sessions'] as const++const CONFIDENTIAL = { error: 'SWARM_CONFIDENTIAL',+ message: 'This agent runs in this computer\'s Harness Team account and holds people\'s private chats in a Swarm, so it is not shown here.' }+/** Its marks, or its record, are there but could not be read, or a reading failed (security re-check 3 of #2089). */+const COULD_NOT_READ = { error: 'SWARM_CONFIDENTIAL',+ message: 'This computer\'s Harness Team account could not read its Swarm\'s settings, so its agents are not shown here.' }+const COULD_NOT_READ_ONLY = { error: 'TEAM_READ_ONLY',+ message: 'This computer\'s Harness Team account could not read its Swarm\'s settings, so its agents can be watched here but not typed in, and no agent can be started in it.' }+/** A Team daemon whose Swarm has not yet sent it any marks. */+const UNKNOWN = { error: 'SWARM_CONFIDENTIAL',+ message: 'This computer\'s Harness Team account has not heard from its Swarm yet, so its agents are not shown here until it does.' }+const UNKNOWN_READ_ONLY = { error: 'TEAM_READ_ONLY',+ message: 'This computer\'s Harness Team account has not heard from its Swarm yet, so its agents can be watched here but not typed in, and no agent can be started in it until it does.' }+const READ_ONLY = { error: 'TEAM_READ_ONLY',+ message: 'This computer\'s Harness Team account runs a Swarm Product Manager, so its agents can be watched here but not typed in, and no agent can be started in it.' }++/** A session this daemon holds, running or stopped. */+export interface HeldSession { agentId: string; sessionId?: string | null; lead: boolean }++export interface TeamAppDeps {+ /** The sessions the Swarm's roster marked confidential here, or null when they cannot be read (readConfidentialMarks).+ * Read every time: teamAppPolicyFor reads the file again only when it changed. */+ marks: () => readonly string[] | null+ /** Whether the Swarm has sent any marks here: null marks then could not be read, rather than not come yet. */+ heard?: () => boolean+ /** The sessions this daemon runs, from memory, read every time, and whether each was launched as a Product Manager. */+ live: () => readonly HeldSession[]+ /** The sessions it keeps stopped, listed from disk: the one read kept for READING_MS. */+ stopped: () => readonly HeldSession[]+ /** The sessions ever found confidential here, by agent id and engine session id, kept after they stop+ * (confidentialRecord), and their keeping. */+ recorded: () => readonly string[]+ record: (ids: string[]) => void+ /** The purges still to finish (inCore/teamPurge.ts), and whether their record could not be read: each keeps the account+ * held, its session closed, until it finishes (security re-check 3 of #2089). */+ purging?: () => { ids: readonly string[]; unknown: boolean }+ now?: () => number+}++/** How long one listing of the stopped sessions on disk serves: every frame of a burst (a turn's deltas) asks (security+ * re-review of #2089). Only that listing: what runs, the record and the marks are read every time, so a Product Manager+ * registered, or a session marked, is closed at once (its re-check 1). A stopped session ran first, and was read then. */+export const READING_MS = 500+/** How deep the rows of an answer are looked for: an answer's lists, and the lists inside its objects and rows. */+const ROW_DEPTH = 4++/** The sessions a request or a row names, by every field and list that can name one. */+function named(payload: Record<string, unknown>): string[] {+ const ids: string[] = []+ const add = (value: unknown) => { if (typeof value === 'string' && value) ids.push(value) }+ for (const field of SESSION_FIELDS) add(payload[field])+ for (const field of SESSION_LISTS) {+ const items = payload[field]+ if (!Array.isArray(items)) continue+ for (const item of items) {+ if (typeof item === 'string') add(item)+ else if (item && typeof item === 'object') for (const key of SESSION_FIELDS) add((item as Record<string, unknown>)[key])+ }+ }+ return ids+}++/** The policy of a Team daemon. Installed only there (core/main.ts, `isTeamDaemon`). */+export function createTeamAppPolicy(deps: TeamAppDeps): RemoteAppPolicy & { isConfidential(id: string): boolean } {+ const now = deps.now ?? Date.now+ /** Every session confidential, and the account held: what anything that fails reads as. */+ const closed = { failed: true, unknown: true, heard: true, confidential: (_id: string) => true, hosting: true }+ let stoppedAt = -Infinity, stoppedHeld: readonly HeldSession[] = []+ const stopped = () => {+ const at = now()+ if (at - stoppedAt >= READING_MS || at < stoppedAt) { stoppedHeld = deps.stopped(); stoppedAt = at }+ return stoppedHeld+ }+ /** One reading of who is confidential. It runs inside the daemon's broadcast, so it never throws: a reading that fails,+ * its record's write included, is the closed one (security re-review of #2089). */+ const read = (): typeof closed => {+ try {+ const marks = deps.marks(), sessions = [...deps.live(), ...stopped()], recorded = new Set(deps.recorded())+ const purging = deps.purging?.() ?? { ids: [], unknown: false }+ const known = new Set([...marks ?? [], ...sessions.filter(s => s.lead).map(s => s.agentId), ...purging.ids])+ // Its engine's session id too: the same conversation registered again under a new agent id stays closed.+ const keep = [...known, ...sessions.flatMap(s => known.has(s.agentId) && s.sessionId ? [s.sessionId] : [])]+ const fresh = [...new Set(keep)].filter(id => !recorded.has(id))+ if (fresh.length) deps.record(fresh)+ const confidential = (id: string) => {+ if (marks === null || recorded.has(id) || known.has(id)) return true+ const held = sessions.find(s => s.agentId === id || s.sessionId === id)+ return !!held && (known.has(held.agentId) || recorded.has(held.agentId) || (!!held.sessionId && recorded.has(held.sessionId)))+ }+ // Held while any confidential session is here, running or stopped: a stopped one may resume (a crash, a restart, a+ // limit). Its data deleted once the Swarm ends it for good (createConfidentialPurge), the account is released.+ return { failed: false, unknown: marks === null, heard: marks !== null || !!deps.heard?.(), confidential,+ hosting: marks === null || purging.unknown || purging.ids.length > 0 || sessions.some(s => confidential(s.agentId)) }+ } catch {+ stoppedAt = -Infinity+ return closed+ }+ }+ const withoutConfidential = (payload: Record<string, unknown>, confidential: (id: string) => boolean) => {+ const names = (row: Record<string, unknown>) => named(row).some(confidential)+ || Object.values(row).some(v => !!v && typeof v === 'object' && !Array.isArray(v) && named(v as Record<string, unknown>).some(confidential))+ const walk = (value: unknown, depth: number): unknown => {+ if (depth > ROW_DEPTH || !value || typeof value !== 'object') return value+ // Only plain objects and lists: a Date, a Buffer or a class instance is left as it is (security re-check 2 of #2089).+ const plain = Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null+ if (!Array.isArray(value) && !plain) return value+ if (Array.isArray(value)) {+ return value.filter(item => !(item && typeof item === 'object' && !Array.isArray(item) && names(item as Record<string, unknown>)))+ .map(item => walk(item, depth + 1))+ }+ return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, walk(v, depth + 1)]))+ }+ return walk(payload, 0) as Record<string, unknown>+ }+ return {+ refuse(type, payload) {+ const r = read()+ if (r.failed || named(payload).some(r.confidential)) return !r.unknown ? CONFIDENTIAL : r.heard ? COULD_NOT_READ : UNKNOWN+ return !READS.has(type) && r.hosting ? (!r.unknown ? READ_ONLY : r.heard ? COULD_NOT_READ_ONLY : UNKNOWN_READ_ONLY) : null+ },+ reply(_type, payload) {+ return withoutConfidential(payload, read().confidential)+ },+ event(frame) {+ const r = read()+ const about = eventAgentId(frame)+ if (r.failed || (about && r.confidential(about))) return null+ const payload = frame.payload+ return payload && typeof payload === 'object' && !Array.isArray(payload)+ ? { ...frame, payload: withoutConfidential(payload as Record<string, unknown>, r.confidential) } : frame+ },+ watchOnly: () => read().hosting,+ isConfidential: (id) => read().confidential(id),+ }+}++/** The sessions the Swarm's last roster marked confidential on [machineId] (superTabs/observers.ts writes them), or null+ * when the snapshot is missing, unreadable or another machine's: the guard then counts every session confidential. */+export function readConfidentialMarks(file: string, machineId: string): string[] | null {+ try {+ const saved = JSON.parse(readFileSync(file, 'utf8')) as { machineId?: unknown; confidential?: unknown } | null+ if (!saved || saved.machineId !== machineId || !Array.isArray(saved.confidential)) return null+ return saved.confidential.filter((id): id is string => typeof id === 'string')+ } catch { return null }+}++/** Where a Team daemon keeps every session it found confidential, so a stopped one stays closed to the owner's apps. */+export const confidentialRecordFile = (dataDir: string): string => join(dataDir, 'super-tabs', 'team-confidential.json')+/** The most it keeps: far more Product Managers than one Team account runs in its life; the oldest go first. */+export const CONFIDENTIAL_RECORD_MAX = 2_000++/** The record at [file], and its keeping: written whole through a temporary file, newest last. A record there but unreadable+ * stays unknown (`unknown`), and the policy then counts every session confidential. */+export function confidentialRecord(file: string) {+ const load = (): { ids: string[]; unknown: boolean } => {+ if (!existsSync(file)) return { ids: [], unknown: false }+ try {+ const saved = JSON.parse(readFileSync(file, 'utf8')) as unknown+ if (!Array.isArray(saved)) return { ids: [], unknown: true }+ return { ids: saved.filter((id): id is string => typeof id === 'string'), unknown: false }+ } catch { return { ids: [], unknown: true } }+ }+ let held = load()+ return {+ ids: (): readonly string[] => held.ids,+ unknown: (): boolean => held.unknown,+ add(ids: string[]): void {+ const next = [...held.ids.filter(id => !ids.includes(id)), ...ids].slice(-CONFIDENTIAL_RECORD_MAX)+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })+ writeFileSync(`${file}.next`, JSON.stringify(next), { mode: 0o600 })+ renameSync(`${file}.next`, file)+ held = { ids: next, unknown: held.unknown }+ },+ }+}++/** The policy as the core's process runs it (core/main.ts), on a Team daemon: its Swarm marks and its record in [dataDir],+ * the sessions it runs and those it keeps stopped, a Product Manager's by the Swarm role it was launched with. The marks+ * file is read again only when its size or time changed: one stat a reading. */+export function teamAppPolicyFor(dataDir: string, machineId: () => string,+ live: () => ReadonlyArray<{ agentId: string; sessionId?: string | null; swarmSkill?: { role?: string } }>,+ stopped: () => ReadonlyArray<{ agentId: string; sessionId?: string | null; swarmSkill?: { role?: string } }>, purges?: PurgeRecord) {+ const record = confidentialRecord(confidentialRecordFile(dataDir))+ const held = (rows: ReadonlyArray<{ agentId: string; sessionId?: string | null; swarmSkill?: { role?: string } }>) =>+ rows.map(s => ({ agentId: s.agentId, sessionId: s.sessionId ?? null, lead: s.swarmSkill?.role === 'lead' }))+ let seen: { key: string; marks: string[] | null } | null = null+ const marks = () => {+ if (record.unknown()) return null+ const file = observerSnapshotFile(dataDir, machineId())+ let key: string+ try { const info = statSync(file); key = `${file}\n${info.size}\n${info.mtimeMs}\n${machineId()}` } catch { return null }+ if (seen?.key !== key) seen = { key, marks: readConfidentialMarks(file, machineId()) }+ return seen.marks+ }+ return createTeamAppPolicy({ marks, heard: () => existsSync(observerSnapshotFile(dataDir, machineId())), live: () => held(live()), stopped: () => held(stopped()),+ recorded: record.ids, record: ids => record.add(ids),+ ...(purges ? { purging: () => ({ ids: purges.pending().map(t => t.agentId), unknown: purges.unknown() }) } : {}) })+}diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.tsnew file mode 100644index 000000000..ec140c58f--- /dev/null+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts@@ -0,0 +1,282 @@+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'+import { createConfidentialPurge, purgeRecord, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'++// A confidential session the Swarm ended for good in a Harness Team account (#895): its data in the Team user's shared+// engine homes goes, and the account stays held until a sweep finds nothing of it (security re-checks of #2089).++const dir = () => mkdtempSync(join(tmpdir(), 'team-purge-'))+const CWD = '/Users/team/swarm/app/.worktrees/pm'+const SLUG = CWD.replace(/[^A-Za-z0-9]/g, '-')+const target = (over: Partial<PurgeTarget> = {}): PurgeTarget => ({ agentId: 'pm', sessionId: 'pm-session', cwd: CWD, engine: 'claude', codexHome: null, ...over })++/** The Team user's home as Claude Code 2.1 leaves it: the PM's traces among another session's, which names the PM too. */+function teamHome() {+ const home = dir(), claude = join(home, '.claude')+ for (const sub of ['paste-cache', `projects/${SLUG}/memory`, 'projects/-other', 'file-history/pm-session', 'session-env/pm-session', 'todos', 'debug', 'backups'])+ mkdirSync(join(claude, sub), { recursive: true })+ mkdirSync(join(home, '.codex'), { recursive: true })+ writeFileSync(join(claude, 'history.jsonl'), [+ JSON.stringify({ display: 'the launch slips a week', pastedContents: { 1: { id: 1, type: 'text', contentHash: 'abc123' } }, project: CWD, sessionId: 'pm-session' }),+ JSON.stringify({ display: 'other work', pastedContents: {}, project: '/Users/team/swarm/web', sessionId: 'other' }), ''].join('\n'))+ writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'pasted secret')+ writeFileSync(join(claude, 'paste-cache', 'keep.txt'), 'other paste')+ writeFileSync(join(claude, 'projects', SLUG, 'pm-session.jsonl'), 'transcript')+ writeFileSync(join(claude, 'projects', SLUG, 'memory', 'MEMORY.md'), 'remembered')+ // Another agent's own transcript reads the PM's status: it names the PM's session and folder, and is not the PM's to delete.+ writeFileSync(join(claude, 'projects', '-other', 'other.jsonl'), `{"tool":"harness super-tab status","out":"pm-session ${CWD}"}`)+ writeFileSync(join(claude, 'todos', 'pm-session-agent-pm-session.json'), '[]')+ writeFileSync(join(claude, 'todos', 'other-agent-other.json'), '[]')+ writeFileSync(join(claude, 'debug', 'pm-session.txt'), 'debug')+ const config = { numStartups: 3, projects: { [CWD]: { history: ['secret'], allowedTools: [] }, [`${CWD}2`]: { allowedTools: [] }, '/Users/team/swarm/web': { allowedTools: [] } },+ githubRepoPaths: { 'example/app': [CWD, '/Users/team/swarm/app'], 'example/pm-only': [CWD] } }+ writeFileSync(join(home, '.claude.json'), JSON.stringify(config, null, 2))+ writeFileSync(join(claude, 'backups', '.claude.json.backup.1793236000000'), JSON.stringify(config))+ return { home, claude }+}++describe('scrubbing a Claude Code session from the Team user\'s shared home', () => {+ it('removes every file and entry its session or folder names, and keeps every other session\'s', async () => {+ const { home, claude } = teamHome()+ expect(await scrubClaudeSession(home, target())).toEqual(['abc123'])+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toBe(`${JSON.stringify({ display: 'other work', pastedContents: {}, project: '/Users/team/swarm/web', sessionId: 'other' })}\n`)+ expect([existsSync(join(claude, 'paste-cache', 'abc123.txt')), existsSync(join(claude, 'paste-cache', 'keep.txt'))]).toEqual([false, true])+ for (const gone of [`projects/${SLUG}`, 'file-history/pm-session', 'session-env/pm-session', 'todos/pm-session-agent-pm-session.json', 'debug/pm-session.txt']) {+ expect(existsSync(join(claude, gone)), gone).toBe(false)+ }+ expect(existsSync(join(claude, 'projects', '-other', 'other.jsonl'))).toBe(true)+ expect(existsSync(join(claude, 'todos', 'other-agent-other.json'))).toBe(true)+ // The config and its backups: its folder's entry and its repository paths go, the rest stays as it was.+ const scrubbed = { numStartups: 3, projects: { [`${CWD}2`]: { allowedTools: [] }, '/Users/team/swarm/web': { allowedTools: [] } },+ githubRepoPaths: { 'example/app': ['/Users/team/swarm/app'] } }+ expect(JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8'))).toEqual(scrubbed)+ expect(JSON.parse(readFileSync(join(claude, 'backups', '.claude.json.backup.1793236000000'), 'utf8'))).toEqual(scrubbed)+ // Its sweep then finds nothing, though another session's transcript, and a folder whose name only starts with its own, name it.+ expect(await sweepForSession(home, target(), ['abc123'])).toBeNull()+ })++ it('keeps what does not name it, whatever shape, and never takes another session\'s project folder for a missing one', async () => {+ const home = dir(), claude = join(home, '.claude')+ mkdirSync(join(claude, 'projects', '-other'), { recursive: true })+ writeFileSync(join(claude, 'projects', '-other', 'other.jsonl'), 'other')+ writeFileSync(join(claude, 'history.jsonl'), ['not json, other work', 'not json, pm-session', `not json, ${CWD}`,+ JSON.stringify({ sessionId: 'pm-session', pastedContents: { 1: { contentHash: '../keep' }, 2: null } }), ''].join('\n'))+ writeFileSync(join(home, '.claude.json'), '{ not json')+ expect(await scrubClaudeSession(home, target())).toEqual([])+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toBe('not json, other work\n')+ expect(readFileSync(join(home, '.claude.json'), 'utf8')).toBe('{ not json')+ expect(await scrubClaudeSession(home, target({ cwd: null }))).toEqual([])+ expect(await scrubClaudeSession(home, target({ sessionId: '../x', cwd: '/' }))).toEqual([])+ // A paste name from an earlier record that is no file name is never followed out of the paste cache.+ writeFileSync(join(home, 'keep.txt'), 'kept')+ await scrubClaudeSession(home, target(), ['../../keep'])+ expect(existsSync(join(home, 'keep.txt'))).toBe(true)+ expect(existsSync(join(claude, 'projects', '-other', 'other.jsonl'))).toBe(true)+ // Every line its own: the history is left empty; a home where Claude Code never ran has nothing to scrub.+ writeFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ sessionId: 'pm-session' })}\n`)+ await scrubClaudeSession(home, target())+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toBe('')+ expect(await scrubClaudeSession(dir(), target())).toEqual([])+ })+})++describe('the sweep for what a scrub left', () => {+ it('finds the session or folder where Claude Code and Codex write its own data, and nowhere else', async () => {+ const { home, claude } = teamHome()+ await scrubClaudeSession(home, target())+ appendFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ display: 'late', project: CWD, sessionId: 'pm-session' })}\n`)+ expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'history.jsonl'))+ await scrubClaudeSession(home, target())+ writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'written again')+ expect(await sweepForSession(home, target(), ['abc123'])).toBe(join(claude, 'paste-cache', 'abc123.txt'))+ writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), '')+ await scrubClaudeSession(home, target(), ['abc123'])+ mkdirSync(join(claude, 'new-feature', 'pm-session'), { recursive: true })+ expect(await sweepForSession(home, target(), ['abc123'])).toBe(join(claude, 'new-feature', 'pm-session'))+ mkdirSync(join(claude, 'later', SLUG), { recursive: true })+ expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'later', SLUG))+ writeFileSync(join(home, '.codex', 'history.jsonl'), '{"session_id":"pm-session"}')+ expect(await sweepForSession(home, target({ cwd: null }), [])).toBe(join(home, '.codex', 'history.jsonl'))+ expect(await sweepForSession(dir(), target(), [])).toBeNull()+ })+})++describe('a scrub and sweep with part of a session unknown', () => {+ it('scrubs by folder alone, by session alone, leaves a config that is no object, and finds its folder left in a backup', async () => {+ const home = dir(), claude = join(home, '.claude')+ mkdirSync(join(claude, 'backups'), { recursive: true })+ writeFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ project: CWD })}\n`)+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: { [CWD]: {} } }))+ await scrubClaudeSession(home, target({ sessionId: null }))+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toBe('')+ expect(JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8'))).toEqual({ projects: {} })+ writeFileSync(join(home, '.claude.json'), 'null')+ await scrubClaudeSession(home, target())+ expect(readFileSync(join(home, '.claude.json'), 'utf8')).toBe('null')+ writeFileSync(join(claude, 'backups', '.claude.json.backup.1'), 'a copy that is no JSON, naming "' + CWD + '"')+ expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'backups', '.claude.json.backup.1'))+ expect(await sweepForSession(home, target({ sessionId: '../x' }), [])).toBe(join(claude, 'backups', '.claude.json.backup.1'))+ // With no folder, nothing of the config is its; with neither, nothing is.+ expect(await sweepForSession(home, target({ cwd: null }), ['../bad'])).toBeNull()+ expect(await sweepForSession(home, target({ cwd: null, sessionId: null }), [])).toBeNull()+ })++ it('records a session whose engine gave no session id or Codex home', async () => {+ const home = dir()+ const record = purgeRecord(join(home, 'super-tabs', 'team-purges.json'))+ let held = true+ const purge = vi.fn(async (request: Record<string, unknown>) => { if (request.mode === 'delete') held = false; return request.mode === 'inspect' ? { reviewId: 'r' } : { ok: true } })+ const ended = createConfidentialPurge({ confidential: () => true, home, record, purge,+ session: id => held ? { agentId: id, registeredAt: 5, engine: 'claude', cwd: CWD } : null })+ expect(await ended('pm')).toEqual({ ok: true })+ expect(purge.mock.calls[0]![0]).toEqual({ agentId: 'pm', sessionId: null, createdAt: 5, mode: 'inspect' })+ record.drop('none')+ expect(record.pending()).toEqual([])+ })+})++describe('rewriting a file other agents of the account write too', () => {+ it('writes it again from what is there when it changed while it was being rewritten, so no write is lost', async () => {+ const file = join(dir(), 'history.jsonl')+ writeFileSync(file, 'ours\nother\n')+ let raced = false+ const transform = vi.fn((text: string) => {+ // Another agent writes while the first attempt is being made.+ if (!raced) { raced = true; appendFileSync(file, 'theirs\n') }+ return text.split('\n').filter(line => line !== 'ours').join('\n')+ })+ expect(await rewriteIfUnchanged(file, transform)).toBe(true)+ expect(readFileSync(file, 'utf8')).toBe('other\ntheirs\n')+ expect(transform).toHaveBeenCalledTimes(2)+ // Unchanged by the rewrite: nothing is written. Missing: nothing to do.+ expect(await rewriteIfUnchanged(file, text => text)).toBe(true)+ expect(await rewriteIfUnchanged(join(dir(), 'none'), text => text)).toBe(true)+ })++ it('gives up, writing nothing, when it keeps changing', async () => {+ const file = join(dir(), 'busy.jsonl')+ writeFileSync(file, 'ours\n')+ expect(await rewriteIfUnchanged(file, text => { appendFileSync(file, 'x\n'); return '' })).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe('ours\nx\nx\nx\nx\nx\n')+ })+})++describe('the purge of a confidential session the Swarm ended', () => {+ /** The reviewed purge as lib/purgeAgentService.ts is: a delete drops the session from its stopped catalog. */+ function service(home: string, codexHome: string | null = null) {+ let held = true+ const calls: Array<Record<string, unknown>> = []+ const purge = vi.fn(async (request: Record<string, unknown>) => {+ calls.push(request)+ if (request.mode === 'inspect') return { reviewId: 'review-1' }+ held = false+ return { ok: true }+ })+ const session = (id: string) => held ? { agentId: id, sessionId: 'pm-session', registeredAt: 5, engine: codexHome ? 'codex' : 'claude', cwd: CWD, codexHome } : null+ const record = purgeRecord(join(home, 'super-tabs', 'team-purges.json'))+ return { purge, session, record, calls }+ }++ it('deletes through the reviewed purge, scrubs, sweeps, and keeps the session in its record until the sweep passes', async () => {+ const { home, claude } = teamHome()+ const s = service(home)+ const ended = createConfidentialPurge({ confidential: id => id === 'pm', home, session: s.session, purge: s.purge, record: s.record })+ // Something the scrub does not know of still names the session: the purge fails and the session stays in its record.+ mkdirSync(join(claude, 'new-feature', 'pm-session'), { recursive: true })+ expect(await ended('pm')).toEqual({ error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${join(claude, 'new-feature', 'pm-session')}` })+ expect(s.calls.map(c => c.mode)).toEqual(['inspect', 'delete'])+ expect(s.record.pending()).toEqual([{ agentId: 'pm', sessionId: 'pm-session', cwd: CWD, engine: 'claude', codexHome: null, pastes: ['abc123'] }])+ // The retry, its stopped entry gone: it scrubs and sweeps again from the record (a history line written since included).+ appendFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ display: 'late', sessionId: 'pm-session' })}\n`)+ expect(await ended('pm')).toMatchObject({ error: 'SCRUB_INCOMPLETE' })+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).not.toContain('pm-session')+ writeFileSync(join(claude, 'stray'), '')+ const { rmSync } = await import('node:fs')+ rmSync(join(claude, 'new-feature'), { recursive: true })+ expect(await ended('pm')).toEqual({ ok: true })+ expect(s.calls.map(c => c.mode)).toEqual(['inspect', 'delete'])+ expect(s.record.pending()).toEqual([])+ expect(purgeRecord(join(home, 'super-tabs', 'team-purges.json')).pending()).toEqual([])+ })++ // Security re-check 2 of 9e49723b8: the paste names reached the record only after the history lines naming them were gone,+ // so a scrub that died between the two lost them, and a paste left behind passed the sweep.+ it('saves the pastes its history names before rewriting it, so a scrub that dies after the rewrite still finds them', async () => {+ const { home, claude } = teamHome()+ const s = service(home)+ // A paste the scrub cannot remove (a folder in its place) fails it right after the history was rewritten.+ const { rmSync: remove } = await import('node:fs')+ remove(join(claude, 'paste-cache', 'abc123.txt'))+ mkdirSync(join(claude, 'paste-cache', 'abc123.txt'))+ const ended = createConfidentialPurge({ confidential: () => true, home, session: s.session, purge: s.purge, record: s.record })+ await expect(ended('pm')).rejects.toThrow()+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).not.toContain('pm-session')+ expect(s.record.get('pm')?.pastes).toEqual(['abc123'])+ // The retry, the history no longer naming it: the record's paste is still swept for, and fails it until it is gone.+ const { rmSync } = await import('node:fs')+ rmSync(join(claude, 'paste-cache', 'abc123.txt'), { recursive: true })+ writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'left behind')+ const sweep = await sweepForSession(home, s.record.get('pm')!, s.record.get('pm')!.pastes!)+ expect(sweep).toBe(join(claude, 'paste-cache', 'abc123.txt'))+ expect(await ended('pm')).toEqual({ ok: true })+ })++ it('of a Codex session in its own engine home, deletes that home whole', async () => {+ const home = dir(), codexHome = join(home, '.harness-pm-homes', 'super-start-1', 'codex')+ mkdirSync(join(codexHome, 'sessions'), { recursive: true })+ writeFileSync(join(codexHome, 'history.jsonl'), 'the launch slips a week')+ const s = service(home, codexHome)+ const ended = createConfidentialPurge({ confidential: () => true, home, session: s.session, purge: s.purge, record: s.record })+ expect(await ended('pm')).toEqual({ ok: true })+ expect(existsSync(join(home, '.harness-pm-homes', 'super-start-1'))).toBe(false)+ })++ it('leaves any other session alone; a refused review or delete stops it, the session kept in its record', async () => {+ const home = dir()+ const record = purgeRecord(join(home, 'super-tabs', 'team-purges.json'))+ const refused = vi.fn(async () => ({ error: 'NOT_FOUND' }))+ const session = (id: string) => ({ agentId: id, sessionId: 'pm-session', registeredAt: 5, engine: 'claude', cwd: CWD, codexHome: null })+ const ended = createConfidentialPurge({ confidential: id => id === 'pm', home, session, purge: refused, record })+ expect(await ended('worker')).toEqual({ skipped: true })+ expect(await createConfidentialPurge({ confidential: () => true, home, session: () => null, purge: refused, record })('gone')).toEqual({ skipped: true })+ expect(await ended('pm')).toEqual({ error: 'NOT_FOUND' })+ expect(record.pending().map(t => t.agentId)).toEqual(['pm'])+ const refusedDelete = vi.fn(async (request: Record<string, unknown>) => request.mode === 'inspect' ? { reviewId: 'r' } : { error: 'DELETE_IN_PROGRESS' })+ expect(await createConfidentialPurge({ confidential: () => true, home, session, purge: refusedDelete, record })('pm')).toEqual({ error: 'DELETE_IN_PROGRESS' })+ })+})++describe('the record of purges still to finish', () => {+ it('keeps them across restarts, and says when it cannot be read, so the account stays held (teamApps.ts)', async () => {+ const file = join(dir(), 'team-purges.json')+ const record = purgeRecord(file)+ record.put(target())+ record.put(target({ pastes: ['abc'] }))+ expect(purgeRecord(file).pending()).toEqual([target({ pastes: ['abc'] })])+ expect(purgeRecord(file).get('pm')).toEqual(target({ pastes: ['abc'] }))+ record.drop('pm')+ expect(purgeRecord(file).pending()).toEqual([])+ expect(purgeRecord(file).unknown()).toBe(false)+ // Unreadable, it is never written over (re-check 2 of 9e49723b8): kept aside, the purges it names unforgotten, and the+ // account held until a person clears it, whatever is recorded after.+ writeFileSync(file, '{')+ const later = purgeRecord(file)+ expect([later.pending(), later.unknown()]).toEqual([[], true])+ expect(readFileSync(`${file}.unreadable`, 'utf8')).toBe('{')+ later.put(target())+ expect([purgeRecord(file).pending(), purgeRecord(file).unknown(), readFileSync(`${file}.unreadable`, 'utf8')]).toEqual([[target()], true, '{'])+ // Unreadable again with one already aside: kept aside too, under a name of its own.+ writeFileSync(file, '[')+ expect(purgeRecord(file).unknown()).toBe(true)+ expect(readFileSync(`${file}.unreadable.1`, 'utf8')).toBe('[')+ const { rmSync } = await import('node:fs')+ rmSync(`${file}.unreadable`)+ expect(purgeRecord(file).unknown()).toBe(true)+ rmSync(`${file}.unreadable.1`)+ expect(purgeRecord(file).unknown()).toBe(false)+ writeFileSync(file, '{"pm": 3}')+ expect([purgeRecord(file).get('pm'), purgeRecord(file).unknown()]).toEqual([undefined, false])+ })+})diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.tsnew file mode 100644index 000000000..203bf7a74--- /dev/null+++ b/cli/src/superTabs/inCore/teamPurge.ts@@ -0,0 +1,244 @@+/**+ * The data of a confidential session the Swarm ended for good in a Harness Team account (#895): a Product Manager removed+ * or replaced, a private chat's worker stopped (inCore/agents.ts closeMember and closeSwarm). The Swarm keeps its chats; its+ * files in the account, which the account's next agent could read, go. The account stays held until they have+ * (inCore/teamApps.ts, and the backend's `heldFor`).+ *+ * Through the reviewed purge (lib/purgeAgentService.ts), its worktree kept; then a Codex one's own engine home goes whole+ * (superTabs/teamDaemon.ts pmEngineHome), and a Claude Code one's traces are scrubbed from the Team user's shared home, whose+ * transcripts core reads only there. A sweep then looks where Claude Code and Codex write a session's own data, never at+ * other sessions' transcripts, which name the Product Manager when they read its status (security re-check 3 of #2089).+ *+ * The session is kept in a durable record before anything is deleted, and leaves it only once the sweep finds nothing: the+ * reviewed purge drops the session from the stopped catalog, so a retry after a failed sweep had nothing left to scrub from.+ * Everything here reads and writes asynchronously: a Team home holds gigabytes of transcripts, and this runs in the core.+ */+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'+import { basename, dirname, join } from 'node:path'+import { PM_HOMES } from '../teamDaemon.js'++/** What a purge needs of a session, kept until it finishes. `pastes`: the paste cache files its history lines kept. */+export interface PurgeTarget {+ agentId: string+ sessionId: string | null+ cwd: string | null+ engine: string+ codexHome: string | null+ pastes?: string[]+}++/** The purges still to finish, by agent id, kept in [file] across restarts. One that cannot be read is never written over,+ * which would forget the purges it names: it is kept aside at `<file>.unreadable` (`.1`, `.2`… when one already is), and while any is there the record is+ * `unknown` and the account stays held, as it fails closed (inCore/teamApps.ts), until a person clears it (security+ * re-check 2 of 9e49723b8). */+export function purgeRecord(file: string) {+ const aside = `${file}.unreadable`+ const load = (): Map<string, PurgeTarget> => {+ if (!existsSync(file)) return new Map()+ try {+ const saved = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>+ const held = new Map<string, PurgeTarget>()+ for (const [id, entry] of Object.entries(saved)) if (entry && typeof entry === 'object' && (entry as PurgeTarget).agentId === id) held.set(id, entry as PurgeTarget)+ return held+ } catch {+ let free = aside+ for (let n = 1; existsSync(free); n++) free = `${aside}.${n}`+ renameSync(file, free)+ return new Map()+ }+ }+ const state = { held: load() }+ const save = () => {+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })+ writeFileSync(`${file}.next`, JSON.stringify(Object.fromEntries(state.held)), { mode: 0o600 })+ renameSync(`${file}.next`, file)+ }+ return {+ pending: (): PurgeTarget[] => [...state.held.values()],+ get: (agentId: string): PurgeTarget | undefined => state.held.get(agentId),+ unknown: (): boolean => existsSync(aside) || readdirSync(dirname(file)).some(name => name.startsWith(`${basename(aside)}.`)),+ put(target: PurgeTarget): void { state.held.set(target.agentId, target); save() },+ drop(agentId: string): void { if (state.held.delete(agentId)) save() },+ }+}+export type PurgeRecord = ReturnType<typeof purgeRecord>++/** Claude Code's folder name for a project folder: every character but a letter or digit made a dash. */+const claudeSlug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')+const SESSION = /^[A-Za-z0-9_-]{1,160}$/+/** Its folder, when it names one that is no root: an empty or root key would match every other session's. */+const folderOf = (target: PurgeTarget) => target.cwd && target.cwd.startsWith('/') && target.cwd.length > 1 ? target.cwd : null++/**+ * Rewrites [path] through [transform], unless it changed while being rewritten: another agent of the account may write the+ * same file (Claude Code's history, its config) at any moment, and a rewrite from an older copy would lose that write. Then+ * it reads it again and tries again; false when it never stood still. A missing file has nothing to rewrite.+ *+ * What it cannot close without a lock the engines do not take: a write landing between its last check and the rename, one+ * system call wide, is lost to that other agent. It leaves nothing of the session behind: the sweep reads the file again+ * afterwards and fails the purge, closed, while anything still names it.+ */+export async function rewriteIfUnchanged(path: string, transform: (text: string) => string, tries = 5): Promise<boolean> {+ for (let attempt = 0; attempt < tries; attempt++) {+ let before+ try { before = await stat(path) } catch { return true }+ const text = await readFile(path, 'utf8')+ const next = transform(text)+ if (next === text) return true+ const temporary = `${path}.harness-${process.pid}`+ await writeFile(temporary, next, { mode: 0o600 })+ const now = await stat(path)+ if (now.mtimeMs !== before.mtimeMs || now.size !== before.size) { await unlink(temporary); continue }+ await rename(temporary, path)+ return true+ }+ return false+}++/** [config] (Claude Code's `.claude.json`, or a backup of it) without [folder]: its project entry and its repository paths. */+function withoutFolder(text: string, folder: string): string {+ let config: { projects?: Record<string, unknown>; githubRepoPaths?: Record<string, unknown> }+ try { config = JSON.parse(text) } catch { return text }+ if (!config || typeof config !== 'object') return text+ let changed = false+ if (config.projects && folder in config.projects) { delete config.projects[folder]; changed = true }+ for (const [repository, paths] of Object.entries(config.githubRepoPaths ?? {})) {+ if (!Array.isArray(paths) || !paths.includes(folder)) continue+ const kept = paths.filter(path => path !== folder)+ if (kept.length) config.githubRepoPaths![repository] = kept+ else delete config.githubRepoPaths![repository]+ changed = true+ }+ return changed ? JSON.stringify(config, null, 2) : text+}++/**+ * Removes from the Team user's shared Claude Code home ([home]/.claude, [home]/.claude.json and its backups) what Claude+ * Code keeps of the session: its prompt history lines and the pastes they kept ([pastes] from an earlier attempt too), its+ * project folder with its transcripts and memory, its file history, todos, session environment and debug log, and its+ * folder's entry and repository paths in the config and in every backup of it. The pastes its history named, for the record.+ */+export async function scrubClaudeSession(home: string, target: PurgeTarget, pastes: readonly string[] = [],+ onPastes?: (pastes: string[]) => void): Promise<string[]> {+ const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : null+ const folder = folderOf(target)+ if (!sessionId && !folder) return []+ const claude = join(home, '.claude'), history = join(claude, 'history.jsonl')+ /** Its history's lines kept, and the pastes its own lines named. */+ const split = (text: string) => {+ const named: string[] = []+ const kept = text.split('\n').filter(line => {+ if (!line.trim()) return false+ let row: { sessionId?: unknown; project?: unknown; pastedContents?: Record<string, { contentHash?: unknown } | null> }+ try { row = JSON.parse(line) } catch { return !(sessionId && line.includes(sessionId)) && !(folder && line.includes(folder)) }+ const ours = (!!sessionId && row.sessionId === sessionId) || (!!folder && row.project === folder)+ if (ours) for (const paste of Object.values(row.pastedContents ?? {})) if (typeof paste?.contentHash === 'string' && SESSION.test(paste.contentHash)) named.push(paste.contentHash)+ return !ours+ })+ return { kept, named }+ }+ // Its pastes are handed on before the lines naming them go: a scrub that dies after the rewrite would otherwise lose them,+ // and a paste left behind would pass the sweep (security re-check 2 of 9e49723b8).+ const found = split(await readFile(history, 'utf8').catch(() => '')).named+ if (found.length) onPastes?.([...new Set(found)])+ await rewriteIfUnchanged(history, text => {+ const { kept, named } = split(text)+ found.push(...named)+ return kept.length ? `${kept.join('\n')}\n` : ''+ })+ for (const hash of new Set([...pastes, ...found])) if (SESSION.test(hash)) await rm(join(claude, 'paste-cache', `${hash}.txt`), { force: true })+ if (folder) await rm(join(claude, 'projects', claudeSlug(folder)), { recursive: true, force: true })+ if (sessionId) {+ for (const sub of ['file-history', 'session-env']) await rm(join(claude, sub, sessionId), { recursive: true, force: true })+ await rm(join(claude, 'debug', `${sessionId}.txt`), { force: true })+ const todos = await readdir(join(claude, 'todos')).catch(() => [] as string[])+ for (const name of todos) if (name.startsWith(sessionId)) await rm(join(claude, 'todos', name), { force: true })+ }+ if (folder) {+ await rewriteIfUnchanged(join(home, '.claude.json'), text => withoutFolder(text, folder))+ const backups = await readdir(join(claude, 'backups')).catch(() => [] as string[])+ for (const name of backups) await rewriteIfUnchanged(join(claude, 'backups', name), text => withoutFolder(text, folder))+ }+ return [...new Set(found)]+}++/**+ * What still names the session where Claude Code and Codex write its own data, or null: a line of the shared prompt history+ * (Claude Code's or Codex's) naming its session or folder; a paste it kept; its folder in the config or a backup of it; and+ * anywhere under their homes, a file or folder named for its session or its folder. Never the contents of other sessions'+ * transcripts: another agent that read the Product Manager's status names both there, and is not its to delete.+ */+export async function sweepForSession(home: string, target: PurgeTarget, pastes: readonly string[]): Promise<string | null> {+ const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : null+ const folder = folderOf(target)+ const claude = join(home, '.claude'), codex = join(home, '.codex')+ const quoted = [...sessionId ? [`"${sessionId}"`] : [], ...folder ? [`"${folder}"`, `"${folder}/`] : []]+ const names = (path: string) => quoted.some(q => path.includes(q))+ for (const history of [join(claude, 'history.jsonl'), join(codex, 'history.jsonl')]) {+ const text = await readFile(history, 'utf8').catch(() => '')+ if (names(text)) return history+ }+ for (const hash of pastes) if (SESSION.test(hash) && existsSync(join(claude, 'paste-cache', `${hash}.txt`))) return join(claude, 'paste-cache', `${hash}.txt`)+ if (folder) {+ const configs = [join(home, '.claude.json'), ...(await readdir(join(claude, 'backups')).catch(() => [] as string[])).map(name => join(claude, 'backups', name))]+ for (const config of configs) if ((await readFile(config, 'utf8').catch(() => '')).includes(`"${folder}"`)) return config+ }+ const slug = folder ? claudeSlug(folder) : null+ const named = (name: string) => (!!sessionId && name.includes(sessionId)) || (!!slug && name === slug)+ const walk = async (path: string): Promise<string | null> => {+ const entries = await readdir(path, { withFileTypes: true }).catch(() => [])+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {+ const child = join(path, entry.name)+ if (named(entry.name)) return child+ if (entry.isDirectory()) { const found = await walk(child); if (found) return found }+ }+ return null+ }+ for (const root of [claude, codex]) { const found = await walk(root); if (found) return found }+ return null+}++/**+ * The purge of [agentId]'s data, once the Swarm ended it for good, when it was confidential: kept in [record] before the+ * first deletion and dropped once the sweep finds nothing. A retry finishes from the record, the session gone or not.+ */+export function createConfidentialPurge(deps: {+ confidential: (agentId: string) => boolean+ session: (agentId: string) => { agentId: string; sessionId?: string | null; registeredAt: number; engine: string; cwd: string | null; codexHome?: string | null } | null+ purge: (request: Record<string, unknown>) => Promise<Record<string, unknown>>+ /** The Team user's home. */+ home: string+ record: PurgeRecord+}): (agentId: string) => Promise<Record<string, unknown>> {+ return async agentId => {+ const session = deps.session(agentId)+ let target = deps.record.get(agentId)+ if (!target) {+ if (!session || !deps.confidential(agentId)) return { skipped: true }+ target = { agentId: session.agentId, sessionId: session.sessionId ?? null, cwd: session.cwd, engine: session.engine, codexHome: session.codexHome ?? null }+ deps.record.put(target)+ }+ if (session) {+ const reference = { agentId: session.agentId, sessionId: session.sessionId ?? null, createdAt: session.registeredAt }+ const review = await deps.purge({ ...reference, mode: 'inspect' })+ if (typeof review.reviewId !== 'string') return review+ const deleted = await deps.purge({ ...reference, mode: 'delete', reviewId: review.reviewId, choices: { sessionData: true, worktreeData: false } })+ if (typeof deleted.error === 'string') return deleted+ }+ const homes = join(deps.home, PM_HOMES)+ if (target.codexHome && target.codexHome.startsWith(`${homes}/`)) await rm(dirname(target.codexHome), { recursive: true, force: true })+ if (target.engine === 'claude') {+ const keep = (found: readonly string[]) => {+ const pastes = [...new Set([...target!.pastes ?? [], ...found])]+ if (pastes.length !== (target!.pastes ?? []).length) { target = { ...target!, pastes }; deps.record.put(target) }+ }+ keep(await scrubClaudeSession(deps.home, target, target.pastes, keep))+ }+ const left = await sweepForSession(deps.home, target, target.pastes ?? [])+ if (left) return { error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${left}` }+ deps.record.drop(agentId)+ return { ok: true }+ }+}+diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex f7143e5d8..4aff15125 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -238,6 +238,23 @@ describe('contributed machine executor', () => {await f.machine.tick()expect((f.start.mock.calls as unknown[][]).map(call => call[0])).toEqual([{ tabId: 'tab', startId: 'buddy-start', hostDispatch: true }])})+ it('launches a Product Manager\'s start, which the backend lists apart so that a host from before them never does', async () => {+ const f = fixture()+ Object.assign(f.pool, { starts: [], leadStarts: [{ id: 'lead-start', dispatched: false }] })+ await f.machine.tick()+ expect((f.start.mock.calls as unknown[][]).map(call => call[0])).toEqual([{ tabId: 'tab', startId: 'lead-start', hostDispatch: true }])+ })+ it('says in its reading that it starts Product Managers, to a backend that asks, and to no other', async () => {+ const f = fixture()+ Object.assign(f.pool, { capabilitiesWanted: true })+ await f.machine.tick()+ const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart'] })+ // A backend from before them does not ask, and would refuse the field.+ const older = fixture()+ await older.machine.tick()+ expect(posted(older)[0]).not.toHaveProperty('capabilities')+ })it('probes common tools plus pending-start requirements and publishes failures without calling them missing', async () => {const f = fixture()Object.assign(f.pool.starts[0]!, { request: { requirements: { tools: ['docker'] } } })diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex cfae2922c..0b8be8f3c 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -135,7 +135,11 @@ const CLEANING_WAIT = 'Waiting for this machine to finish cleaning up this Swarm* hold up a delivery lease. Only a tab's explicit owner grant wakes this queue. *//** A pool's starts this host launches: its agents', and its Buddies', which the backend lists apart so that a host from before* Buddies never launches one as a Builder (backend read/hostRows.ts). */-const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts)]+/** A host's starts: its workers', and its Buddies' and Product Managers', which the backend lists apart so that a host from+ * before them never launches one as a worker. */+const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts), ...list(row.leadStarts)]+/** What this host launches beyond workers, said in its reading (backend leadStart.ts): a project's Product Manager. */+const CAPABILITIES = ['leadStart']/** The backend's answer that this machine may no longer act in the Swarm: signed out, its contribution revoked or its host* unavailable (backend store.ts observeMachine), or the Swarm gone. */const lostAccess = (error: unknown) => error instanceof SuperTabHostError && [401, 403, 404].includes(error.status)@@ -426,7 +430,10 @@ export class ContributedMachines {const progress = Object.fromEntries(running.flatMap(id => typeof shown[id] === 'number' ? [[id, shown[id]]] : []))const uncommitted = began >= this.uncommittedRefusedUntil ? this.uncommitted(running, began, shown) : {}const tokens = began >= this.tokensRefusedUntil ? await this.tokensOf(running) : {}+ // Only to a backend that asks for them (backend read/hostRows.ts): an older one refuses the field, and would refuse+ // every reading with it.const observation = { generation: pool.generation, tools: reportedTools, ...(Object.keys(tokens).length ? { harnessTokens: tokens } : {}),+ ...(row.capabilitiesWanted === true ? { capabilities: CAPABILITIES } : {}),...(preparing.length ? { preparingStartIds: preparing } : {}),...(Object.keys(uncommitted).length ? { harnessUncommitted: uncommitted } : {}),...(Object.keys(progress).length ? { harnessProgress: progress } : {}), ...(localModels ? { localModels } : {}),diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex 0f0d89b9d..6c7d4b4e1 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -1,6 +1,12 @@import { describe, expect, it, vi } from 'vitest'+import { join } from 'node:path'+import { existsSync } from 'node:fs'+import { homedir } from 'node:os'import { inspectCapacity, startAgent } from './start.js'import { buildEngineCommandArgv } from '../lib/engineLaunch.js'+const teamDaemon = vi.hoisted(() => ({ value: false, relayed: true }))+vi.mock('./teamDaemon.js', async (original) => ({ ...await original<object>(), isTeamDaemon: () => teamDaemon.value }))+vi.mock('../team/relay.js', async (original) => ({ ...await original<object>(), teamRelayed: () => teamDaemon.relayed }))const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }/** A queued start is watched before the Lead moves on (startAgent); these tests read the queued answer at once. */const noPause = async () => {}@@ -268,6 +274,63 @@ it('starts no Buddy with full permissions or the GitHub App\'s token: Claude ref}})+it('starts a project\'s Product Manager with the swarm-lead skill, as the Lead of its project\'s conversation, with the GitHub App\'s token', async () => {+ const f = fixture()+ f.start.request = { ...f.start.request, leadFor: { projectId: 'p', personId: 'owner', generation: 'g' } } as typeof f.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'lead-prompt', request: f.start.request, hostDispatch: true, github: { requester: 'owner' } } as never,+ f.scoped, where, f.open)+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!+ expect(payload.swarmRole).toBe('lead')+ expect(payload.swarmGitHub).toBe(true)+ expect(payload.prompt).toContain('swarm-lead skill')+ expect(payload.prompt).toContain(`You are the Product Manager of the project whose conversation is ${f.start.request.conversationId}, started by the Swarm`)+ expect(payload.prompt).toContain(`harness super-tab --tab tab messages ${f.start.request.conversationId}`)+ expect(payload.prompt).not.toContain('Your lead will assign')+ expect(payload.prompt).not.toContain('swarm-dev')+})++// Security re-check 2 of #2089 (the Lead's option A): a Codex Product Manager in a Team account runs in an engine home of+// its own, deleted whole when the Swarm ends it; a Claude Code one in the shared home, scrubbed then (inCore/teamApps.ts).+it('starts a Codex Product Manager on a Team daemon in an engine home of its own, and no other agent or daemon so', async () => {+ const launch = async (engine: string, lead: boolean, team: boolean) => {+ teamDaemon.value = team+ const f = fixture()+ f.start.request = { ...f.start.request, engine, ...(lead ? { leadFor: { projectId: 'p', personId: 'owner', generation: 'g' } } : {}) } as typeof f.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: `home-${engine}-${lead}-${team}`, request: f.start.request }, f.scoped, where, f.open)+ return f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!.codexHome+ }+ expect(await launch('codex', true, true)).toBe(join(homedir(), '.harness-pm-homes', 'super-native-receipt', 'codex'))+ // Made before the launch: Codex refuses a CODEX_HOME that is not there.+ expect(existsSync(join(homedir(), '.harness-pm-homes', 'super-native-receipt', 'codex'))).toBe(true)+ expect(await launch('claude', true, true)).toBeUndefined()+ expect(await launch('codex', false, true)).toBeUndefined()+ expect(await launch('codex', true, false)).toBeUndefined()+ teamDaemon.value = false+})++// Security re-check 3 of #2089: a Codex Product Manager in a Team account starts signed in on the owner's relay, or is+// refused with why. Its own engine home holds no sign-in, so with no relay it started signed out.+it('refuses a Codex Product Manager on a Team daemon with no owner relay before anything launches, saying why', async () => {+ teamDaemon.value = true+ teamDaemon.relayed = false+ try {+ const f = fixture()+ f.start.request = { ...f.start.request, engine: 'codex', leadFor: { projectId: 'p', personId: 'owner', generation: 'g' } } as typeof f.start.request+ const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'no-relay', request: f.start.request }, f.scoped, where, f.open)+ const reason = 'The owner\'s subscription relay is not available on this machine, so a Codex Product Manager cannot sign in here.'+ expect(result).toMatchObject({ error: 'START_FAILED', detail: reason })+ expect(f.request.mock.calls.map(call => call[0])).not.toContain('agent_create')+ expect(f.scoped.mock.calls.map(([input]) => (input as { command?: { type?: string; error?: string } }).command)).toContainEqual({ type: 'agent.startFailed', startId: expect.any(String), error: reason })+ // A Claude Code one, and a Codex worker, are not this check's.+ for (const request of [{ engine: 'claude', leadFor: { projectId: 'p', personId: 'owner', generation: 'g' } }, { engine: 'codex' }]) {+ const g = fixture()+ g.start.request = { ...g.start.request, ...request } as typeof g.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: `other-${request.engine}`, request: g.start.request }, g.scoped, where, g.open)+ expect(g.request.mock.calls.map(call => call[0])).toContain('agent_create')+ }+ } finally { teamDaemon.value = false; teamDaemon.relayed = true }+})+describe('the skills of the project the agent joins', () => {const projects = (skillMode?: string) => ({ conversations: [{ id: 'other', projectId: 'p1' }, { id: 'group', projectId: 'p2' }],projects: [{ id: 'p1', skillMode: 'default' }, { id: 'p2', ...(skillMode ? { skillMode } : {}) }] })diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 421840992..f428d3b3b 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -1,4 +1,6 @@import { encodeRuntimeProfile } from '../engines/kit/runtime.js'+import { mkdirSync } from 'node:fs'+import { homedir } from 'node:os'import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'import { createHash, randomUUID } from 'node:crypto'import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'@@ -7,6 +9,8 @@ import { groupSkillMode, identifier, object } from './host.js'import { permissionModeFlags } from '../lib/engineLaunch.js'import type { AgentEngine } from '../engines/types.js'import { isSwarmSkillMode, swarmSkillUse, type SwarmSkillMode } from '../lib/swarmSkills.js'+import { isTeamDaemon, pmEngineHome } from './teamDaemon.js'+import { NO_PM_RELAY, teamRelayed } from '../team/relay.js'type Json = Record<string, unknown>export type ScopedRequest = (payload: Json) => Promise<Json>@@ -34,6 +38,12 @@ function requireSuccess(reply: Json): Json {return object(reply.value)}/** A Buddy's start note: its owner's chat, where it talks, and nothing to wait for. */+/** A project's Product Manager the Swarm started here (backend leadStart.ts): the Lead of the project's conversation, with+ * the lines Desktop's own-machine launch gives one (desktop super_tabs/launch_prompt.dart). */+function leadPrompt(tabId: string, chat: string, mode: SwarmSkillMode | null): string {+ return `You are the Product Manager of the project whose conversation is ${chat}, started by the Swarm on this machine. ${mode ? `${swarmSkillUse('lead', mode)} ` : ''}Discuss first; build when authorized. Coordinate: assign multi-part or 15+ minute work to Swarm agent groups; do only answers, lookups and work under 15 minutes yourself; your subagents only read/look up. Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Read the request with harness super-tab --tab ${tabId} messages ${chat}; if it is empty, ask there what to work on. Reply with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID], and answer each message once. Route only to start an agent or assign work, never your own: harness super-tab --tab ${tabId} route GROUP JSON. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`+}+function buddyPrompt(tabId: string, chat: string, mode: SwarmSkillMode | null): string {return `You are a person's Buddy in a shared Super Tab. ${mode ? `${swarmSkillUse('buddy', mode)} ` : ''}Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Your chat with your owner is conversation ${chat}: read it with harness super-tab --tab ${tabId} messages ${chat}, and reply there with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID. Then greet your owner there and ask what they have in mind. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`}@@ -307,6 +317,13 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:if (native.state === 'missing') {if (start.dispatched) return { error: 'START_UNCERTAIN', startId, creationId,detail: 'This start was submitted but its machine has no receipt. Inspect the machine before creating another agent.' }+ // A Codex Product Manager in a Harness Team account runs in an engine home of its own, with no sign-in there: it signs+ // in on the owner's relay, or not at all. With no relay it is refused before anything launches, and the queue moves it+ // on (backend leadStart.ts), rather than starting signed out (security re-check 3 of #2089).+ if (request.engine === 'codex' && request.leadFor && typeof request.leadFor === 'object' && isTeamDaemon() && !teamRelayed()) {+ requireSuccess(await scoped({ action: 'command', operationId: `refused-${startId}`, command: { type: 'agent.startFailed', startId, error: NO_PM_RELAY } }))+ return { error: 'START_FAILED', startId, detail: NO_PM_RELAY }+ }const resources = await inspectCapacity(target, request)if (resources.capacity.error === 'GUEST_NOT_ALLOWED') return {error: 'CONTRIBUTION_REQUIRED', startId,@@ -332,11 +349,13 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'// A Buddy's start names its owner (backend buddies.ts): it brainstorms in their chat and is never assigned work.const buddy = !!request.buddyOf && typeof request.buddyOf === 'object'+ // A project's Product Manager (backend leadStart.ts): the Lead of its project's conversation once it runs.+ const lead = !buddy && !!request.leadFor && typeof request.leadFor === 'object'// A contributed machine's host cannot read the tab as a Lead does: it asked the backend whose work this is when it// readied the start, and prepared it with the app's token if it is another person's (superTabs/projectFolder.ts).// Its Swarm read was refused with a 400 at every start until 2026-10-28, and its agents ran Harness orchestration// whatever their project's skills: the start read names them, and a backend from before that keeps orchestration.- const role = buddy ? 'buddy' : reviewer ? 'review' : 'dev', hosted = input.hostDispatch === true ? object(input.github) : null+ const role = buddy ? 'buddy' : lead ? 'lead' : reviewer ? 'review' : 'dev', hosted = input.hostDispatch === true ? object(input.github) : nullconst facts = skilled && !hosted ? await projectFacts(scoped, request.conversationId, start.machineOwnerId) : nullconst mode = !skilled ? null : isSwarmSkillMode(start.skillMode) ? start.skillMode : facts?.mode ?? 'orchestration'// A Buddy never writes code (Lead's ruling, privacy review of #1992): never the GitHub App's token. A Claude Buddy runs@@ -349,7 +368,8 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:...(asks ? { permissionMode: asks } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),...(github ? { swarmGitHub: true } : {}),- prompt: buddy ? buddyPrompt(String(input.tabId), String(request.conversationId), mode) : `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer+ prompt: buddy ? buddyPrompt(String(input.tabId), String(request.conversationId), mode)+ : lead ? `${leadPrompt(String(input.tabId), String(request.conversationId), mode)}${github ? ` ${githubPromptLine(github.requester)}` : ''}` : `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer? `Do not review yet. You review work in conversation ${request.conversationId} when it is ready for review.`: `Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}.`} Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.${github ? ` ${githubPromptLine(github.requester)}` : ''}`,...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`,@@ -357,6 +377,14 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:...(request.branchRef ? { branchRef: request.branchRef } : { branchBase: 'default' }) } : { cwd: request.cwd }),}for (const key of ['codexHome', 'gridModel', 'gridName']) if (request[key] !== undefined) payload[key] = request[key]+ // A Codex Product Manager in a Harness Team account runs in an engine home of its own, deleted whole when the Swarm+ // ends it, so nothing of its chats stays where the account's next agent reads (teamDaemon.ts, security re-check 2 of #2089).+ const pmHome = lead ? pmEngineHome(String(request.engine), creationId, isTeamDaemon(), homedir()) : null+ if (pmHome) {+ // Codex refuses a CODEX_HOME that is not there; only the Team user reads it.+ mkdirSync(pmHome, { recursive: true, mode: 0o700 })+ payload.codexHome = pmHome+ }// The routed model goes on the command line of this session alone. Typing /model into the pane afterwards saves// it as the person's default in their own Claude settings (manual run 2, 2026-10-19).launched = canLaunch && launchesWithModel(resources.capacity, request.engine)diff --git a/cli/src/superTabs/teamDaemon.ts b/cli/src/superTabs/teamDaemon.tsnew file mode 100644index 000000000..d29e3e29c--- /dev/null+++ b/cli/src/superTabs/teamDaemon.ts@@ -0,0 +1,35 @@+/**+ * Whether this daemon is a Harness Team account's, and where its Codex Product Managers keep their engine homes (#895). Read+ * by the core's guard (inCore/teamApps.ts) and by the Swarm's host as it launches a Product Manager (start.ts), so it holds+ * nothing of the core's.+ */+import { existsSync } from 'node:fs'+import { userInfo } from 'node:os'+import { join } from 'node:path'+import { readAuthSession } from '../lib/authSession.js'+import { readTeamConfig } from '../team/config.js'+import { TEAM_CONFIG_FILE } from '../team/layout.js'++/**+ * Whether this daemon is a Harness Team account's, decided once at startup (security review 1 of #2089): the Team config+ * names this macOS user, or the daemon is signed in as a Team account (a machine used only for agents, `harness team on`).+ * A Team config that is there but cannot be read counts as this user's: the guard is installed, as it fails closed.+ */+export function isTeamDaemon(deps: { configExists?: () => boolean; config?: () => ReturnType<typeof readTeamConfig>; user?: () => string;+ signedInAsTeam?: () => boolean } = {}): boolean {+ const exists = (deps.configExists ?? (() => existsSync(TEAM_CONFIG_FILE)))()+ const config = exists ? (deps.config ?? (() => readTeamConfig()))() : null+ if (exists && (!config || config.user === (deps.user ?? (() => userInfo().username))())) return true+ return (deps.signedInAsTeam ?? (() => readAuthSession()?.kind === 'team'))()+}++/** Where a Team daemon runs each Codex Product Manager in an engine home of its own, deleted whole when the Swarm ends it. */+export const PM_HOMES = '.harness-pm-homes'++/** The engine home a Product Manager's start [creationId] runs in on a Team daemon: its own, for Codex (security re-check 2+ * of #2089, the Lead's option A). Null for Claude Code, whose transcripts core reads only from the shared home (its files+ * are scrubbed instead, inCore/teamApps.ts scrubClaudeSession), and anywhere but a Team daemon. */+export function pmEngineHome(engine: string, creationId: string, team: boolean, home: string): string | null {+ if (!team || engine !== 'codex' || !/^[A-Za-z0-9_-]{1,160}$/.test(creationId)) return null+ return join(home, PM_HOMES, creationId, 'codex')+}diff --git a/cli/src/team/relay.spec.ts b/cli/src/team/relay.spec.tsindex dfa7f8ef2..d1c7bc8de 100644--- a/cli/src/team/relay.spec.ts+++ b/cli/src/team/relay.spec.ts@@ -6,7 +6,7 @@ import { CODEX_RELAY_ACCOUNT, type SubscriptionRelay } from '../lib/subscriptionimport { engineAccount } from '../lib/engineAccount.js'import type { TeamConfig } from './config.js'import {- publishTeamRelay, readTeamRelay, TEAM_RELAY_GUEST, teamRelayDir, teamRelayFile, teamRelayLaunch, teamRelayPublished, TeamRelayPublisher, prepareCodexHome, installedCodexVersion, CODEX_CLIENT_VERSION_FALLBACK,+ publishTeamRelay, readTeamRelay, TEAM_RELAY_GUEST, teamRelayDir, teamRelayFile, teamRelayLaunch, teamRelayPublished, NO_PM_RELAY, type OwnerRelayLaunch, TeamRelayPublisher, prepareCodexHome, installedCodexVersion, CODEX_CLIENT_VERSION_FALLBACK,type TeamRelayLaunchDeps, type TeamRelayPublisherDeps, type TeamRelayReadDeps,} from './relay.js'@@ -156,7 +156,7 @@ describe('a launch in the team account', () => {const deps = launchDeps()expect(await teamRelayLaunch('claude', deps)).toEqual({ env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9/claude', ANTHROPIC_AUTH_TOKEN: TOKEN }, args: [] })expect(deps.onboarded).toHaveBeenCalledWith('claude')- const codex = await teamRelayLaunch('codex', deps)+ const codex = await teamRelayLaunch('codex', deps) as OwnerRelayLaunch | nullexpect(codex?.env).toEqual({ HARNESS_RELAY_TOKEN: TOKEN })expect(codex?.args).toContain('model_provider="harness_owner"')// Its home is made ready first (the owner's model list), and Codex stays an API-key provider of the relay.@@ -164,12 +164,49 @@ describe('a launch in the team account', () => {expect(codex?.args).toContain('model_providers.harness_owner.env_key="HARNESS_RELAY_TOKEN"')expect(codex?.args.join(' ')).not.toContain('requires_openai_auth')// A home that could not be made ready still launches, as before.- expect((await teamRelayLaunch('codex', launchDeps({ codexHome: async () => { throw new Error('read-only') } })))?.args).toContain('model_provider="harness_owner"')+ expect((await teamRelayLaunch('codex', launchDeps({ codexHome: async () => { throw new Error('read-only') } })) as OwnerRelayLaunch | null)?.args).toContain('model_provider="harness_owner"')// A first-run screen that cannot be recorded is left for the engine to ask.expect(await teamRelayLaunch('claude', launchDeps({ onboarded: () => { throw new Error('read-only') } }))).not.toBeNull()expect(await teamRelayLaunch('codex', launchDeps({ signedIn: async () => { throw new Error('keychain') } }))).not.toBeNull()})+ // Security re-check of #2089: a Codex Product Manager in a Team account runs in an engine home of its own (superTabs/+ // teamDaemon.ts pmEngineHome). Whether it is signed in, and the owner's model list, are that home's, not the daemon's: it+ // started signed out when the Team user had a Codex sign-in of its own, and without the owner's models.+ it('for a launch in a Codex home of its own, asks that home whether it is signed in and readies that home', async () => {+ const signedIn = vi.fn(async (_engine: 'claude' | 'codex', home?: string) => home === undefined)+ const deps = launchDeps({ signedIn })+ const codex = await teamRelayLaunch('codex', deps, '/Users/team/.harness-pm-homes/super-1/codex') as OwnerRelayLaunch | null+ expect(signedIn).toHaveBeenCalledWith('codex', '/Users/team/.harness-pm-homes/super-1/codex')+ expect(deps.codexHome).toHaveBeenCalledWith(grant, '/Users/team/.harness-pm-homes/super-1/codex')+ expect(codex?.env).toEqual({ HARNESS_RELAY_TOKEN: TOKEN })+ // The daemon's own Codex home, signed in itself, still launches on its own sign-in.+ expect(await teamRelayLaunch('codex', deps)).toBeNull()+ })++ // Security re-check 2 of 9e49723b8: a launch in a Codex home of its own holds no sign-in there, so with no relay it is refused+ // with why (create.ts and launchOverrides.ts honour it), never started signed out.+ it('refuses a launch in a Codex home of its own that no relay and no sign-in there can sign in', async () => {+ const home = '/Users/team/.harness-pm-homes/super-1/codex'+ expect(await teamRelayLaunch('codex', launchDeps({ read: () => null }), home)).toEqual({ refused: NO_PM_RELAY })+ expect(await teamRelayLaunch('codex', launchDeps({ config: () => null }), home)).toEqual({ refused: NO_PM_RELAY })+ expect(NO_PM_RELAY).toBe('The owner\'s subscription relay is not available on this machine, so a Codex Product Manager cannot sign in here.')+ // Signed in in that home, or not a Team daemon, or no home of its own: nothing to refuse.+ expect(await teamRelayLaunch('codex', launchDeps({ read: () => null, signedIn: async () => true }), home)).toBeNull()+ expect(await teamRelayLaunch('codex', launchDeps({ read: () => null, team: () => false }), home)).toBeNull()+ expect(await teamRelayLaunch('codex', launchDeps({ read: () => null }))).toBeNull()+ })++ it('readies a Product Manager\'s own Codex home with the owner\'s models, and leaves the daemon\'s alone', async () => {+ const root = mkdtempSync(join(tmpdir(), 'team-pm-')), pm = join(root, '.harness-pm-homes', 'super-1', 'codex'), own = join(root, '.codex')+ onTestFinished(() => rmSync(root, { recursive: true, force: true }))+ const fetch = vi.fn(async () => new Response(JSON.stringify({ models: [{ slug: 'gpt-6.1-sol', visibility: 'list' }] }), { status: 200 }))+ const codex = await teamRelayLaunch('codex', launchDeps({ codexHome: (g, home) => prepareCodexHome(home ?? own, g, { fetch: fetch as never, version: () => '0.165.0', now: () => 0 }) }), pm) as OwnerRelayLaunch | null+ expect(codex?.args).toContain('model_provider="harness_owner"')+ expect(JSON.parse(readFileSync(join(pm, 'models_cache.json'), 'utf8')).models).toEqual([{ slug: 'gpt-6.1-sol', visibility: 'list' }])+ expect(existsSync(own)).toBe(false)+ })+it('adds nothing elsewhere: another engine, the owner\'s own daemon, no team account, its own sign-in, no relay', async () => {expect(await teamRelayLaunch('opencode', launchDeps())).toBeNull()expect(await teamRelayLaunch('claude', launchDeps({ team: () => false }))).toBeNull()diff --git a/cli/src/team/relay.ts b/cli/src/team/relay.tsindex c84bd5971..193c78a8a 100644--- a/cli/src/team/relay.ts+++ b/cli/src/team/relay.ts@@ -208,33 +208,43 @@ export function readTeamRelay(config: TeamConfig, deps: TeamRelayReadDeps = real/** What a Claude Code or Codex launch adds to spend the owner's subscription through the relay. */export interface OwnerRelayLaunch { env: Record<string, string>; args: string[] }+/** Why a launch in a Codex home of its own (a Swarm Product Manager's) is not made: no sign-in there, and no relay to give it+ * one. The launch refuses or holds with it, never starting signed out (security re-checks of #2089). */+export interface OwnerRelayRefusal { refused: string }+export const NO_PM_RELAY = 'The owner\'s subscription relay is not available on this machine, so a Codex Product Manager cannot sign in here.'export interface TeamRelayLaunchDeps {/** Whether this daemon runs team work only. */team(): booleanconfig(): TeamConfig | null- /** Whether the team account signed this engine in itself. */- signedIn(engine: 'claude' | 'codex'): Promise<boolean>+ /** Whether the team account signed this engine in itself: in [home], the launch's own Codex home, when it has one. */+ signedIn(engine: 'claude' | 'codex', home?: string): Promise<boolean>read(config: TeamConfig): TeamRelayGrant | null/** Claude Code that never ran in the team account opens on its first-run screens, which nobody is there to answer:* recorded as done, in the team account's own home, before the first launch on the relay. */onboarded(engine: 'claude' | 'codex'): void- /** Codex's home made ready for the relay before each launch ([prepareCodexHome]). Never throws. */- codexHome(grant: TeamRelayGrant): Promise<void>+ /** Codex's home made ready for the relay before each launch ([prepareCodexHome]): [home], the launch's own, when it has one.+ * Never throws. */+ codexHome(grant: TeamRelayGrant, home?: string): Promise<void>}-/** In the team daemon, for an engine it has not signed in itself: the owner's relay, when there is one. */-export async function teamRelayLaunch(engine: AgentEngine, deps: TeamRelayLaunchDeps): Promise<OwnerRelayLaunch | null> {+/** In the team daemon, for an engine it has not signed in itself: the owner's relay, when there is one. [codexHome]: the+ * launch's own Codex home (a Swarm Product Manager's, superTabs/teamDaemon.ts pmEngineHome), whose sign-in and model list+ * are its own, not the daemon's (security re-check of #2089: it started signed out, without the owner's models). */+export async function teamRelayLaunch(engine: AgentEngine, deps: TeamRelayLaunchDeps, codexHome?: string): Promise<OwnerRelayLaunch | OwnerRelayRefusal | null> {if (engine !== 'claude' && engine !== 'codex') return nullif (!deps.team()) return null+ const home = engine === 'codex' ? codexHome : undefined+ // A Codex home of its own holds no sign-in but what it was given: with no relay it is refused, not launched signed out.+ const none = home === undefined ? null : { refused: NO_PM_RELAY }const config = deps.config()- if (!config) return null- if (await deps.signedIn(engine).catch(() => false)) return null+ if (!config) return home !== undefined && !await deps.signedIn(engine, home).catch(() => false) ? none : null+ if (await (home === undefined ? deps.signedIn(engine) : deps.signedIn(engine, home)).catch(() => false)) return nullconst grant = deps.read(config)- if (!grant) return null+ if (!grant) return nonetry { deps.onboarded(engine) } catch { /* The engine asks on its screen, as it would have. */ }if (engine === 'claude') return { env: claudeRelayEnv(grant.url, grant.token), args: [] }- await deps.codexHome(grant).catch(() => {})+ await (home === undefined ? deps.codexHome(grant) : deps.codexHome(grant, home)).catch(() => {})return { env: codexRelayEnv(grant.token), args: codexRelayArgs(grant.url) }}@@ -289,16 +299,16 @@ export function installedCodexVersion(home: string): string | null {}/** The team daemon's own: its sign-in, the root-owned config, its engines' sign-ins in its own home. */-export const realTeamRelayLaunch = (engine: AgentEngine) => teamRelayLaunch(engine, {+export const realTeamRelayLaunch = (engine: AgentEngine, codexHome?: string) => teamRelayLaunch(engine, {team: () => readAuthSession()?.kind === 'team',config: () => readTeamConfig(),// Only presence is read, never a secret (lib/engineAccount.ts); the team daemon has no login shell to read.- signedIn: async (e) => (await engineAccount(e, { home: homedir(), env: process.env, lastUsed: false })).signedIn === true,+ signedIn: async (e, home) => (await engineAccount(e, { home: homedir(), env: home ? { ...process.env, CODEX_HOME: home } : process.env, lastUsed: false })).signedIn === true,read: (config) => readTeamRelay(config),onboarded: (e) => { if (e === 'claude') recordAcceptanceIn(join(homedir(), '.claude.json'), 'hasCompletedOnboarding') },- codexHome: (grant) => prepareCodexHome(process.env.CODEX_HOME || join(homedir(), '.codex'), grant,+ codexHome: (grant, home) => prepareCodexHome(home ?? (process.env.CODEX_HOME || join(homedir(), '.codex')), grant,{ fetch, version: () => installedCodexVersion(homedir()), now: Date.now }),-})+}, codexHome)/** In the team daemon: whether the owner's relay is there for its engines (superTabs/machines.ts readiness). */export const teamRelayed = (): boolean => {diff --git a/cli/vitest.super-tabs.config.ts b/cli/vitest.super-tabs.config.tsindex f115e2c89..be5575949 100644--- a/cli/vitest.super-tabs.config.ts+++ b/cli/vitest.super-tabs.config.ts@@ -5,7 +5,7 @@ import base from './vitest.config.js'/** Super Tab routing v1 (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md): new files outside* the core and services, which no other gate covers, held to 100% in every file. And the Swarm's side of the core's* process (superTabs/inCore/), which left the core's own 100% gate when the Swarm became a switch. */-const IN_CORE = ['adoption', 'agents', 'attention', 'cards', 'deliveries', 'launch', 'role', 'terminal'].map(name => `src/superTabs/inCore/${name}.ts`)+const IN_CORE = ['adoption', 'agents', 'attention', 'cards', 'deliveries', 'launch', 'role', 'teamApps', 'teamPurge', 'terminal'].map(name => `src/superTabs/inCore/${name}.ts`)const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/shortCommand.ts', ...IN_CORE]export default defineConfig({test: {