Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm: teammates' work runs only on Team machines that pass their privacy check (#1694)

Dee88bce8d84778
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index a78103c62..24f5b26bd 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -9,6 +9,7 @@ import { PrismaClient } from '@prisma/client'
import type { AuthUser } from '../src/lib/ssoAuth.js'
import { SuperTabStore } from '../src/superTabs/store.js'
import type { Command } from '../src/superTabs/commands.js'
+import type { ContributedMachine } from '../src/superTabs/machines.js'
// A team session (docs/plans/2026-10-24-swarm-team-account.md, Task 1) is the owner's account signed in on a second
// macOS user of the owner's Mac. In a Swarm it may host its own machine and speak as the agents running there, and
@@ -27,21 +28,27 @@ const run = (tab: string, command: Command, user: AuthUser = owner, asAgentId?:
const hostRun = (tab: string, command: Command, machineId = 'team-mac', user: AuthUser = team) =>
store.execute(user, tab, { operationId: randomUUID(), command }, undefined, machineId)
const LIMITED = { code: 'TEAM_SESSION_LIMITED', status: 403 }
-const reading = (generation: string) => ({ generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
+/** What the team account's privacy check reports (cli/src/team/privacy.ts): passed, or the first item that failed. */
+const PASSED = { mode: 'account', passed: true, checkedAt: Date.now() } as const
+const FAILED = { mode: 'account', passed: false, item: 'gitconfig', detail: 'The team account could read ~/.gitconfig.', checkedAt: Date.now() } as const
+/** A machine's reading. It always claims a privacy check; only a team session's claim is kept. */
+const reading = (generation: string, privacy: Record<string, unknown> = PASSED) => ({ generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
- quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })
+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [], privacy }) as Parameters<SuperTabStore['observeMachine']>[3]
/** The owner's Swarm with the person in it: the owner's Lead on the owner's machine, the person's own agent on the
- * person's personal Mac, and the person's Team machine contributed, with one agent started there by its team daemon. */
+ * person's personal Mac in the person's own project, and the person's Team machine contributed, with one agent of the
+ * owner's project started there by its team daemon. */
async function fixture() {
const tab = (await store.create(owner, randomUUID(), 'Team pilot')).id
const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
const lead = String((await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'owner-host', harnessId: randomUUID(),
name: 'Lead', configuration: config, lead: true })).result.agentId)
- const group = async (title: string) => String((await run(tab, { type: 'conversation.create', title, brief: 'Do it',
- checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
- const personalGroup = await group('Personal work'), teamGroup = await group('Team work')
+ const group = async (title: string, projectId = 'lead', user = owner) => String((await run(tab, { type: 'conversation.create', projectId, title, brief: 'Do it',
+ checks: [{ description: 'Verified', independent: false }] }, user)).result.conversationId)
+ const own = String((await run(tab, { type: 'project.create', name: 'Own', visibility: 'public', brief: '' }, person)).result.projectId)
+ const personalGroup = await group('Personal work', own, person), teamGroup = await group('Team work')
const personal = String((await run(tab, { type: 'agent.add', conversationId: personalGroup, machineId: 'personal-mac',
harnessId: randomUUID(), name: 'Personal', configuration: config, lead: false }, person)).result.agentId)
await run(tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', engines: ['codex'], maxAgents: 4 }, person)
@@ -53,7 +60,7 @@ async function fixture() {
const started = await hostRun(tab, { type: 'agent.started', startId, harnessId: `team-builder-${randomUUID()}`, configuration: config })
await hostRun(tab, { type: 'agent.startSettled', startId, warning: null })
const builder = String(started.result.agentId)
- return { tab, lead, personal, builder, personalGroup, teamGroup, startId, generation }
+ return { tab, lead, personal, builder, personalGroup, teamGroup, startId, generation, own }
}
beforeAll(async () => {
@@ -71,6 +78,7 @@ beforeAll(async () => {
machineId, userId, computerId, sessionKind, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
await machine('owner-host', owner.sub, 'cccccccccccccccccccccccccccccccc', 'computer')
await machine('personal-mac', person.sub, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'computer')
+ await machine('personal-laptop', person.sub, 'dddddddddddddddddddddddddddddddd', 'computer')
await machine('team-mac', person.sub, TEAM_COMPUTER, 'team')
})
afterAll(async () => {
@@ -101,11 +109,11 @@ describe('a team session hosting its own machine', () => {
it('never hosts the person\'s other machines', async () => {
const f = await fixture()
- await run(f.tab, { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', engines: ['codex'], maxAgents: 2 }, person)
+ 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 store.hostPools(person, 'personal-mac')).find(p => p.tabId === f.tab)!.machine.generation
await store.observeMachine(person, f.tab, 'personal-mac', reading(generation))
const queued = String((await run(f.tab, { type: 'agent.start', request: { conversationId: f.personalGroup, machineId: 'personal-mac', engine: 'codex',
- name: 'Another', cwd: '/work', worktree: false, requirements } })).result.startId)
+ name: 'Another', cwd: `/work/${f.own}`, worktree: false, requirements } }, person)).result.startId)
await expect(store.hostPools(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
await expect(store.hostTabs(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
await expect(store.hostTerminal(team, 'personal-mac')).rejects.toMatchObject(LIMITED)
@@ -262,3 +270,162 @@ describe('a team session speaking in a Swarm', () => {
expect(await store.mayObserve(team, f.tab, 'team-mac', 'any', person.sub)).toBe(false)
})
})
+
+// Teammates' work runs only on Team machines (Task 3): the owner's project on the person's machines needs the person's
+// Harness Team account with its privacy check passed. The person's own projects run on the person's machines as before.
+describe('a teammate\'s work and the machines that take it', () => {
+ /** The person's personal MacBook, contributed for every project, reporting from the person's own sign-in. */
+ async function personalMac(f: Awaited<ReturnType<typeof fixture>>) {
+ 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 store.hostPools(person, 'personal-mac')).find(p => p.tabId === f.tab)!.machine.generation
+ await store.observeMachine(person, f.tab, 'personal-mac', reading(generation))
+ return generation
+ }
+ /** A machine as a member reads it, with whether it takes teammates' projects now. */
+ const pool = (tab: string, machineId: string, user: AuthUser = owner, at: SuperTabStore = store) => at.read(user, tab)
+ .then(r => r.state.machines!.find(m => m.machineId === machineId)! as unknown as ContributedMachine & { teamWork: { allowed: boolean; code?: string; reason?: string } })
+ /** A start of the owner's project's Builder, on the team machine (its contribution's folder) or a personal one. */
+ const start = (tab: string, conversationId: string, machineId: string, user: AuthUser = owner, cwd = machineId === 'team-mac' ? '/team' : '/work/lead', at: SuperTabStore = store) =>
+ at.execute(user, tab, { operationId: randomUUID(), command: { type: 'agent.start', request: { conversationId, machineId, engine: 'codex', name: 'Builder',
+ cwd, worktree: false, requirements } } })
+ const NO_TEAM_ACCOUNT = 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.'
+
+ it('keeps privacy only from the team account\'s own reading, and the read says which machines take teammates\' projects', async () => {
+ const f = await fixture()
+ await personalMac(f)
+ expect((await pool(f.tab, 'team-mac')).observation!.privacy).toEqual({ ...PASSED, seenAt: expect.any(Number) })
+ expect((await pool(f.tab, 'team-mac')).teamWork).toEqual({ allowed: true })
+ // The person's own sign-in claimed the same check for its MacBook: an ordinary computer proves nothing about a team account.
+ expect((await pool(f.tab, 'personal-mac')).observation).not.toHaveProperty('privacy')
+ expect((await pool(f.tab, 'personal-mac')).teamWork).toEqual({ allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason: NO_TEAM_ACCOUNT })
+ // The same check sent again keeps the date it first arrived, so a check that stops running goes stale.
+ const first = (await pool(f.tab, 'team-mac')).observation!.privacy!.seenAt
+ await new Promise(resolve => setTimeout(resolve, 5))
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation))
+ expect((await pool(f.tab, 'team-mac')).observation!.privacy!.seenAt).toBe(first)
+ // A failing check: every member reads the item, only its contributor reads the detail.
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, FAILED))
+ 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' })
+ })
+
+ 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 () => {
+ const f = await fixture()
+ await personalMac(f)
+ await expect(start(f.tab, f.teamGroup, 'personal-mac')).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403, message: NO_TEAM_ACCOUNT })
+ expect((await start(f.tab, f.teamGroup, 'team-mac')).result.startId).toBeTruthy()
+ expect((await start(f.tab, f.personalGroup, 'personal-mac', person, `/work/${f.own}`)).result.startId).toBeTruthy()
+ // Off the Machines list nothing shows a privacy check, so the person's uncontributed laptop never takes the owner's project.
+ await expect(start(f.tab, f.teamGroup, 'personal-laptop', person, '/work')).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED' })
+ })
+
+ it('refuses it on a Team machine whose check failed, is missing or went stale', async () => {
+ const f = await fixture()
+ 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))
+ 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.
+ const later = new SuperTabStore(db, () => Date.now() + 20 * 60_000)
+ await later.observeMachine(team, f.tab, 'team-mac', reading(f.generation))
+ await expect(start(f.tab, f.teamGroup, 'team-mac', owner, '/team', later)).rejects.toMatchObject({ code: 'PRIVACY_CHECK_STALE' })
+ expect((await pool(f.tab, 'team-mac', owner, later)).teamWork.reason).toMatch(/^The privacy check on MacBook Pro · Team last passed 20 minutes ago/)
+ })
+
+ it('refuses work.assign of the owner\'s project to an agent on the person\'s personal Mac', async () => {
+ const f = await fixture()
+ await personalMac(f)
+ // The person added an agent of theirs to the owner's project by hand.
+ const volunteer = String((await run(f.tab, { type: 'agent.add', conversationId: f.teamGroup, machineId: 'personal-mac', harnessId: randomUUID(),
+ name: 'Volunteer', configuration: config, lead: false }, person)).result.agentId)
+ await expect(run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: volunteer })).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', message: NO_TEAM_ACCOUNT })
+ expect((await run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: f.builder })).result.assignmentId).toBeTruthy()
+ // The person's own project, to the person's own agent there, as before.
+ expect((await run(f.tab, { type: 'work.assign', conversationId: f.personalGroup, agentId: f.personal }, person)).result.assignmentId).toBeTruthy()
+ })
+
+ it('routes the owner\'s project around the machines that cannot take it, records why, and refuses a pick or reroute there', async () => {
+ const f = await fixture()
+ await personalMac(f)
+ const volunteer = String((await run(f.tab, { type: 'agent.add', conversationId: f.teamGroup, machineId: 'personal-mac', harnessId: randomUUID(),
+ name: 'Volunteer', configuration: config, lead: false }, person)).result.agentId)
+ const candidate = (id: string, machineId: string, patch: Record<string, unknown> = {}) => ({ id, kind: 'new' as const, machineId, engine: 'codex' as const,
+ model: 'default', effort: 'default', quality: 3, cost: 2, title: `Builder · ${machineId}`, label: `Codex on ${machineId}`, ...patch })
+ const decision = (pick: string) => ({ assessment: { difficulty: 'medium' as const, risk: 'low' as const, why: 'A small change.' },
+ candidates: [candidate('c0', 'team-mac'), candidate('c1', 'personal-mac'), candidate('c2', 'personal-mac', { kind: 'member', agentId: volunteer, title: 'Volunteer · personal-mac' })],
+ excluded: [], floor: 2, notes: false, pick, via: 'order' as const, p: null, belowFloor: false, why: 'Policy order.' })
+ const routed = await run(f.tab, { type: 'route.record', conversationId: f.teamGroup, decision: decision('c0') }, owner, f.lead)
+ const recorded = await store.routeDecision(owner, f.tab, String(routed.result.routeDecisionId))
+ expect(recorded.record.candidates.map(c => c.id)).toEqual(['c0'])
+ expect(recorded.record.excluded).toEqual([{ title: 'Builder · personal-mac', reason: NO_TEAM_ACCOUNT }, { title: 'Volunteer · personal-mac', reason: NO_TEAM_ACCOUNT }])
+ await expect(run(f.tab, { type: 'route.record', conversationId: f.teamGroup, decision: decision('c1') }, owner, f.lead))
+ .rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', message: `${NO_TEAM_ACCOUNT} Route again.` })
+ // A person's reroute to a machine that stopped showing its privacy since the route.
+ const both = await run(f.tab, { type: 'route.record', conversationId: f.teamGroup, decision: { ...decision('c1'), candidates: [candidate('c0', 'team-mac'), candidate('c1', 'owner-host')] } }, owner, f.lead)
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, FAILED))
+ await expect(run(f.tab, { type: 'route.override', decisionId: String(both.result.routeDecisionId), candidateId: 'c0', reason: 'More quota there.' }))
+ .rejects.toMatchObject({ code: 'PRIVACY_CHECK_FAILED' })
+ })
+
+ it('fails a queued start its Team machine will not take for good, and keeps one that waits on a stale check', async () => {
+ const f = await fixture()
+ const queued = String((await start(f.tab, f.teamGroup, 'team-mac')).result.startId)
+ // The check failed before the team daemon launched it: the start fails with that reason, the group is told.
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, FAILED))
+ await expect(hostRun(f.tab, { type: 'agent.startDispatch', startId: queued })).rejects.toMatchObject({ code: 'PRIVACY_CHECK_FAILED' })
+ const failed = (await store.read(owner, f.tab)).state.starts!.find(s => s.id === queued)!
+ expect(failed).toMatchObject({ dispatched: false, error: expect.stringContaining('is not private (gitconfig') })
+ expect((await store.messages(owner, f.tab, f.teamGroup, {})).messages.at(-1)!.text).toMatch(/^Could not start Builder: The Harness Team account on MacBook Pro · Team is not private/)
+ expect((await store.hostPools(team, 'team-mac')).find(p => p.tabId === f.tab)!.starts.map(s => s.id)).not.toContain(queued)
+ // A stale check may pass again by itself: that start keeps waiting for it.
+ const passedAgain = { ...PASSED, checkedAt: Date.now() + 1 }
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, passedAgain))
+ const waiting = String((await start(f.tab, f.teamGroup, 'team-mac')).result.startId)
+ const later = new SuperTabStore(db, () => Date.now() + 20 * 60_000)
+ await later.observeMachine(team, f.tab, 'team-mac', reading(f.generation, passedAgain))
+ await expect(later.execute(team, f.tab, { operationId: randomUUID(), command: { type: 'agent.startDispatch', startId: waiting } }, undefined, 'team-mac'))
+ .rejects.toMatchObject({ code: 'PRIVACY_CHECK_STALE' })
+ expect((await store.read(owner, f.tab)).state.starts!.find(s => s.id === waiting)).toMatchObject({ dispatched: false, error: null })
+ })
+
+ it('never fails a start its host already launched when the dispatch is repeated after the check failed', async () => {
+ const f = await fixture()
+ const launched = String((await start(f.tab, f.teamGroup, 'team-mac')).result.startId)
+ await hostRun(f.tab, { type: 'agent.startDispatch', startId: launched })
+ await store.observeMachine(team, f.tab, 'team-mac', reading(f.generation, FAILED))
+ await expect(hostRun(f.tab, { type: 'agent.startDispatch', startId: launched })).rejects.toMatchObject({ code: 'PRIVACY_CHECK_FAILED' })
+ expect((await store.read(owner, f.tab)).state.starts!.find(s => s.id === launched)).toMatchObject({ dispatched: true, error: null })
+ // Its agent still arrives.
+ expect((await hostRun(f.tab, { type: 'agent.started', startId: launched, harnessId: `launched-${randomUUID()}`, configuration: config })).result.agentId).toBeTruthy()
+ })
+
+ it('leaves agents already working for the owner\'s project on a personal Mac running; only new work for them is refused', async () => {
+ const f = await fixture()
+ const generation = await personalMac(f)
+ const old = String((await run(f.tab, { type: 'agent.add', conversationId: f.teamGroup, machineId: 'personal-mac', harnessId: 'before-release',
+ name: 'Old', configuration: config, lead: false }, person)).result.agentId)
+ // Its task was assigned by a release from before the rule: written into the stored Swarm as that release left it.
+ const row = await db.superTab.findUniqueOrThrow({ where: { id: f.tab } })
+ const state = structuredClone(row.state) as unknown as { conversations: Array<{ id: string; agentIds: string[]; assignment: unknown }> }
+ const work = state.conversations.find(c => c.id === f.teamGroup)!
+ work.assignment = { id: 'assigned-before', agentId: old, status: 'working', configuration: config, result: null,
+ execution: { machineId: 'personal-mac', harnessId: 'before-release', machineOwnerId: person.sub } }
+ await db.superTab.update({ where: { id: f.tab }, data: { state: state as never, revision: row.revision + 1 } })
+ await db.superTabRun.create({ data: { id: old, tabId: f.tab, assignmentId: 'assigned-before', machineId: 'personal-mac', harnessId: 'before-release' } })
+
+ await store.observeMachine(person, f.tab, 'personal-mac', reading(generation))
+ expect((await store.hostTabs(person, 'personal-mac')).find(r => r.tabId === f.tab && r.agent.id === old)).toMatchObject({ stopRequested: false })
+ expect(await store.hostAssignments(person, 'personal-mac')).toContainEqual({ tabId: f.tab, assignmentId: 'assigned-before', harnessId: 'before-release' })
+ await run(f.tab, { type: 'work.status', conversationId: f.teamGroup, assignmentId: 'assigned-before', status: 'blocked', result: 'Needs a token.' }, person, old)
+ await run(f.tab, { type: 'message.send', conversationId: f.teamGroup, text: 'Here it is.', replyTo: null, recipientIds: [old] })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: old } })).toBeGreaterThan(0)
+ await run(f.tab, { type: 'work.cancel', conversationId: f.teamGroup, assignmentId: 'assigned-before', reason: 'Moving it to the Team machine.' })
+ await expect(run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: old })).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED' })
+ })
+})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index dc2150483..3f5649212 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -3,7 +3,7 @@ import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest'
import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
import { PrismaClient } from '@prisma/client'
import Fastify, { type FastifyInstance } from 'fastify'
@@ -49,6 +49,16 @@ async function routedStart(tab: string, lead: string, role?: 'reviewer') {
return { routeDecisionId, startId }
}
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. */
+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' } })
+ onTestFinished(async () => { await db.machine.update({ where: { machineId }, data: { computerId: null, sessionKind: null } }) })
+ const session: AuthUser = { ...host, harnessSessionId: `team-${machineId}`, harnessSessionKind: 'team', harnessComputerId: computerId }
+ return { session, privacy: { mode: 'dedicated' as const } }
+}
async function invite(tab: string, role: 'collaborator' | 'viewer' = 'collaborator') {
const invitation = await run(tab, { type: 'invite.create', email: peer.email, role, conversationId: 'lead' })
await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
@@ -602,6 +612,7 @@ describe('private swarm projects on the real control API', () => {
const machineId = 'swarm-pool-host'
await db.machine.create({ data: { machineId, userId: host.sub, apiKey: 'fixture-swarm-pool', managerId: 'fixture',
autonomousEnv: 'prod', authMode: 'remote' } })
+ const team = await teamMachine(machineId)
const project = (await run(tab, { type: 'project.create', name: 'Second project', visibility: 'private', brief: '' })).result
const conversationId = String(project.conversationId), projectId = String(project.projectId)
await run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId: randomUUID(),
@@ -618,10 +629,10 @@ describe('private swarm projects on the real control API', () => {
await run(tab, { type: 'machine.contribute', machineId, name: 'Shared capacity', cwd: '/swarm-root',
scope: 'swarm', engines: ['codex'], maxAgents: 2 }, host)
const pool = (await store.hostPools(host, machineId))[0]!
- await store.observeMachine(host, tab, machineId, { generation: pool.machine.generation,
+ 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 },
- quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [] })
+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy })
expect(pool.projects).toEqual([])
await expect(run(tab, { type: 'agent.start', request: { ...request, cwd: '/swarm-root/lead' } }))
.rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
@@ -871,6 +882,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
const contribute = { type: 'machine.contribute' as const, machineId: 'pool-host', name: 'Host laptop', cwd: '/project', engines: ['codex' as const], maxAgents: 1 }
await db.machine.create({ data: { machineId: 'pool-host', userId: host.sub, apiKey: 'fixture-pool-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ const team = await teamMachine('pool-host')
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()
@@ -880,7 +892,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
const observation = { 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: [] }
await expect(store.observeMachine(owner, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
- await store.observeMachine(host, tab, 'pool-host', observation)
+ await store.observeMachine(team.session, tab, 'pool-host', { ...observation, privacy: team.privacy })
const request = { permissionMode: 'full', conversationId: 'lead', machineId: 'pool-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,
requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
await expect(run(tab, { type: 'agent.start', request: { ...request, cwd: '/private' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
@@ -1400,10 +1412,11 @@ describe('Super Tabs on a real Mongo replica set', () => {
await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
await run(tab, { type: 'machine.contribute', machineId: 'test-host', name: 'Host', cwd: '/swarm-root', scope: 'swarm', engines: ['codex'], maxAgents: 2 }, host)
const pool = (await store.hostPools(host, 'test-host')).find(p => p.tabId === tab)!
- await store.observeMachine(host, tab, 'test-host', { generation: pool.machine.generation,
+ const team = await teamMachine('test-host')
+ await store.observeMachine(team.session, tab, 'test-host', { 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 },
- quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [] })
+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy })
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 })
@@ -1921,10 +1934,11 @@ describe('Super Tabs on a real Mongo replica set', () => {
await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
await run(tab, { type: 'machine.contribute', machineId: 'test-host', name: 'Host', cwd: '/fixture/repo', engines: ['codex'], maxAgents: 4 }, host)
const machine = (await store.hostPools(host, 'test-host')).find(pool => pool.tabId === tab)!.machine
- await store.observeMachine(host, tab, 'test-host', { generation: machine.generation,
+ const team = await teamMachine('test-host')
+ await store.observeMachine(team.session, tab, 'test-host', { generation: machine.generation,
resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,
projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
- quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })
+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [], privacy: team.privacy })
const starts = [await routedStart(tab, lead), await routedStart(tab, lead)]
for (const { routeDecisionId } of starts) expect((await store.routeDecision(owner, tab, routeDecisionId)).outcome).toBeNull()
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 67e69d42e..8d484fa0d 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -33,6 +33,18 @@ function fixture() {
return { run, invite, add, group, get state() { return state } }
}
+/** Makes [machineId] [contributorId]'s contributed machine used only for agents (`harness team on`), reporting now, so a
+ * teammate's agent there may take another person's project (machines.ts teamWorkCheck). */
+function teamMachine(f: ReturnType<typeof fixture>, contributorId: string, machineId = 'host') {
+ const team = { sessionKind: 'team' as const, privacy: { mode: 'dedicated' as const, seenAt: 1000 } }
+ const existing = f.state.machines?.find(m => m.machineId === machineId)
+ if (existing) return void Object.assign(existing.observation!, team)
+ f.state.machines = [...(f.state.machines ?? []), { machineId, name: 'Studio', contributorId, membershipGeneration: f.state.people.find(p => p.id === contributorId)!.generation,
+ generation: 'g1', cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, observation: { generation: 'g1', receivedAt: 1000, ...team,
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] } }]
+}
+
describe('five-part tasks', () => {
const task = { goal: 'Save edits', changes: 'Persist the draft', constraints: 'No dependencies', owns: ['backend/src/superTabs'] }
const brief = 'Goal:\nSave edits\n\nChanges:\nPersist the draft\n\nConstraints:\nNo dependencies\n\nOwns:\n- backend/src/superTabs'
@@ -370,6 +382,7 @@ describe('Super Tab collaboration policy', () => {
it('withdraws a departing contributor and preserves execution identity until the host confirms a stop', () => {
const f = fixture()
f.invite()
+ teamMachine(f, 'peer')
const group = f.group()
const worker = f.add('worker', 'peer', group)
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
@@ -944,6 +957,7 @@ it('requires the exact stop request for host acknowledgement and prevents promot
it('allows the contributor to keep a completed worker and refuses another project’s Lead', () => {
const f = fixture(); f.invite()
+ teamMachine(f, 'peer')
f.add('lead', 'owner', 'lead', true)
const group = f.group(), worker = f.add('worker', 'peer', group)
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
@@ -1733,6 +1747,7 @@ describe('machine.remove', () => {
f.state.agents.find(a => a.id === lead)!.machineId = 'elsewhere'
f.invite()
contribute(f, 'peer')
+ teamMachine(f, 'peer')
const worker = f.add('worker', 'peer', group), owners = f.add('owners', 'owner')
f.run({ type: 'work.assign', conversationId: group, agentId: worker })
f.state.rules = [{ id: 'both', projectId: 'lead', rule: { kind: 'machines', machineIds: ['host', 'elsewhere'] }, text: 'Only these two.',
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 6872e32bd..71cf7b4be 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
-import { admitMachineStart, expireRemoval, expireRemovals, machineContribution, machineOffline, ownedMachine, type ContributedMachine } from './machines.js'
+import { admitMachineStart, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, ownedMachine, requireTeamWork, teamWorkCheck, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
@@ -219,6 +219,9 @@ export interface CommandContext {
terminalRequest?: TerminalRequest
/** The mention `mention.done` names, read from SuperTabMention by the store. */
mention?: MentionTarget
+ /** The tab's contributed machines whose account row is signed in as a Harness Team account (`Machine.sessionKind`),
+ * read by the store for the commands that start, assign or route work (machines.ts teamWorkCheck). */
+ teamMachines?: string[]
}
/** Messages in a row between the Lead and its worker after which the Lead's message is no longer delivered automatically. */
@@ -504,6 +507,16 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
effects.routeDecisions.push({ op: 'final', id: decision.id, final: finalOf(decision), ...(override ? { override } : {}), ...(assignmentId ? { assignmentId } : {}) })
return { decision, expected, override }
}
+ /** Why a route candidate cannot take a teammate's work in [conversationId], or null (machines.ts teamWorkCheck). A
+ * member runs under its own contributor's grant; a new agent under the contribution's, or off the Machines list under
+ * the grant of whoever will start it ([starter]). */
+ const candidateRefusal = (candidate: RouteCandidate, conversationId: string, starter: string) => {
+ const project = groupProject(state, conversation(state, conversationId))
+ const member = candidate.kind === 'member' ? state.agents.find(a => a.id === candidate.agentId) : undefined
+ if (candidate.kind === 'member' && !member) return null
+ const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === candidate.machineId)?.contributorId ?? starter
+ return teamWorkCheck(state, member?.machineId ?? candidate.machineId, contributor, project, context.now, context.teamMachines)
+ }
/** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */
const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {
if (!lead) protectLead(state, target.id)
@@ -998,7 +1011,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) {
fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
}
- const pool = admitMachineStart(state, command.request, context.now)
+ const pool = admitMachineStart(state, command.request, context.now, undefined, context.teamMachines)
+ // Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
+ if (!pool) requireTeamWork(state, command.request.machineId, grant.contributorId, home, context.now, context.teamMachines)
state.starts.push({ ...(pool ? { poolGeneration: pool.generation } : {}), ...(command.routeDecisionId ? { routeDecisionId: command.routeDecisionId } : {}), id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,
hostGrant: grant.hostGrant ?? null, request: command.request, harnessId: null, dispatched: false, error: null })
@@ -1040,7 +1055,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {
fail('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.', 403)
}
- admitMachineStart(state, start.request, context.now, start)
+ admitMachineStart(state, start.request, context.now, start, context.teamMachines)
if (start.dispatched || start.error || start.harnessId) fail('START_CLAIMED', 'This native start was already requested. Read its creation status; do not start another.')
start.dispatched = true
break
@@ -1207,6 +1222,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
group.agentIds = group.agentIds.filter(id => id !== command.agentId)
if (group.leadId === command.agentId) group.leadId = null
} else {
+ // A Reviewer added to a group is handed its review, as an assignment hands a Builder its task.
+ if (reviewer) requireTeamWork(state, member.machineId, member.contributorId, groupProject(state, group), context.now, context.teamMachines)
ruled(agentTarget(state, member), group.id, `${who} added ${member.name}`)
if (!group.agentIds.includes(command.agentId)) group.agentIds.push(command.agentId)
// Adding a Reviewer to a group reuses it, as assigning work reuses a Builder.
@@ -1309,26 +1326,37 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
case 'route.record': {
controls(state, actor, command.conversationId)
- const chosen = command.decision.candidates.find(c => c.id === command.decision.pick)!
+ // A teammate's work runs only on Team machines: candidates elsewhere leave the decision for its exclusions, with
+ // why, so the Lead and people see it. A pick there is refused; a current CLI already leaves those machines out.
+ const starter = actor.kind === 'agent' ? agent(state, actor.agentId).contributorId : actor.userId
+ const refusals = new Map(command.decision.candidates.flatMap(c => {
+ const refusal = candidateRefusal(c, command.conversationId, starter)
+ return refusal ? [[c.id, refusal] as const] : []
+ }))
+ const pickRefusal = refusals.get(command.decision.pick)
+ if (pickRefusal) failTeamWork(pickRefusal, ' Route again.')
+ const decision = !refusals.size ? command.decision : { ...command.decision,
+ candidates: command.decision.candidates.filter(c => !refusals.has(c.id)),
+ excluded: [...command.decision.candidates.flatMap(c => refusals.has(c.id) ? [{ title: c.title, reason: refusals.get(c.id)!.reason }] : []),
+ ...command.decision.excluded].slice(0, 200) }
+ const chosen = decision.candidates.find(c => c.id === decision.pick)!
const member = chosen.kind === 'member' ? state.agents.find(a => a.id === chosen.agentId) : undefined
if (member) assignable(conversation(state, command.conversationId), member)
// Only the pick is checked, so an older CLI that still lists a ruled-out candidate records an allowed pick.
ruled(member ? agentTarget(state, member) : chosen, command.conversationId, `${who} routed to ${chosen.title}`)
requireWorkerDecisions(state, actor, open(state, command.conversationId), chosen.kind === 'member' ? chosen.agentId : undefined)
if ((context.recentRoutes ?? 0) >= 30) fail('RATE_LIMITED', 'This Super Tab routed 30 tasks in the last hour. Wait before routing again.', 429)
- const decision = command.decision
- const pick = decision.candidates.find(c => c.id === decision.pick)!
const via = decision.via === 'jev' ? `Jev ${Math.round((decision.p ?? 0) * 100)}%`
: decision.via === 'only' ? 'only candidate' : 'by policy order'
effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId, record: decision })
result.routeDecisionId = operationId
// The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.
const reason = decision.assessment.why
- message(command.conversationId, `Routed to ${pick.title} — ${via} · "${reason}"`, [], null, {
+ message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"`, [], null, {
kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: reason,
...(decision.via === 'order' && decision.fallback ? { fallback: decision.fallback } : {}),
- pick: { id: pick.id, title: pick.title },
- alternatives: decision.candidates.filter(c => c.id !== pick.id).map(c => ({ id: c.id, title: c.title })),
+ pick: { id: chosen.id, title: chosen.title },
+ alternatives: decision.candidates.filter(c => c.id !== chosen.id).map(c => ({ id: c.id, title: c.title })),
})
break
}
@@ -1351,6 +1379,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const chosen = decision.record.candidates.find(c => c.id === command.candidateId) ?? fail('NOT_FOUND', 'Choose one of this decision’s candidates.', 404)
if (chosen.id === current) fail('ALREADY_CHOSEN', 'That candidate is already the choice.')
if (chosen.kind === 'member' && !state.agents.some(a => a.id === chosen.agentId)) fail('CANDIDATE_UNAVAILABLE', 'That agent left this Super Tab. Choose another.')
+ // Its machine may have stopped showing its privacy since the route; the group's Lead is who would start it.
+ const leadId = conversation(state, decision.conversationId).leadId
+ const teamRefusal = candidateRefusal(chosen, decision.conversationId, state.agents.find(a => a.id === leadId)?.contributorId ?? actor.userId)
+ if (teamRefusal) failTeamWork(teamRefusal)
ruled(chosen.kind === 'member' ? agentTarget(state, agent(state, chosen.agentId!)) : chosen, decision.conversationId, `${who} chose ${chosen.title}`)
effects.routeDecisions.push({ op: 'override', id: decision.id, override: { by: 'person', actorKey: actorKey(actor), candidateId: chosen.id, reason: command.reason } })
const lead = conversation(state, decision.conversationId).leadId
@@ -1393,6 +1425,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const home = groupProject(state, group)
if (command.roleId) worker.roleId = chosenRole(home, command.roleId, agentKind(state, worker)).id
else requireCustomRole(home, agentKind(state, worker))
+ // A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
+ requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines)
requireWorkerDecisions(state, actor, group, worker.id)
if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 8844076e6..6c61c03ae 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,6 +1,6 @@
import { z } from 'zod'
import { activeWork, fail, person, type Actor, type Agent, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
-import { agentProjectId, groupProject, ledProject, projectsOf } from './projects.js'
+import { agentProjectId, groupProject, ledProject, projectsOf, type SwarmProject } from './projects.js'
import { conversation } from './model.js'
/** An explicit grant for this tab and project. It never creates a MachineShare. */
@@ -16,8 +16,9 @@ export interface ContributedMachine {
maxAgents: number
paused: boolean
/** `sessionKind` is how the reporting machine is signed in, stamped from its session by the store, never taken from
- * the report: `team` for a Mac's team account (lib/teamSession.ts), `computer` for any other. Absent on older readings. */
- observation?: MachineObservation & { receivedAt: number; sessionKind?: 'team' | 'computer' }
+ * the report: `team` for a Mac's team account (lib/teamSession.ts), `computer` for any other. Absent on older readings.
+ * `privacy` is kept only from a team session's reading (observedPrivacy). */
+ observation?: Omit<MachineObservation, 'privacy'> & { receivedAt: number; sessionKind?: 'team' | 'computer'; privacy?: StoredPrivacy }
/** Set by machine.remove: an online machine stays listed, paused, while its host deletes the Swarm's folders there, until
* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and
* its cleanup waits for its host (expireRemovals). */
@@ -47,6 +48,22 @@ const quota = z.object({ engine: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), kn
windows: z.array(z.object({ name: z.string().max(80), usedPercent: z.number().min(0).max(100),
resetsAt: z.union([z.string().max(80), z.number().finite(), z.null()]) }).strict()).max(10),
}).strict()
+/** Milliseconds since the epoch, on the reporting Mac's clock. */
+const checkedAt = z.number().finite().nonnegative()
+/**
+ * What a Harness Team daemon says about its privacy check with each reading (cli/src/team/privacy.ts, docs/plans/
+ * 2026-10-24-swarm-team-account.md Task 2): `account`, it runs in a Mac's Harness Team account and the check passed, or
+ * failed with the first failing item (`unchecked` when it could not run); `dedicated`, the whole machine is for agents
+ * (`harness team on`). The owner's own daemon sends none. `item` is a short slug, so a newer CLI's item still reads.
+ */
+export const machinePrivacySchema = z.union([
+ z.object({ mode: z.literal('account'), passed: z.literal(true), checkedAt }).strict(),
+ z.object({ mode: z.literal('account'), passed: z.literal(false), item: z.string().regex(/^[a-z][a-z0-9-]{0,39}$/), detail: z.string().max(1000), checkedAt }).strict(),
+ z.object({ mode: z.literal('dedicated') }).strict(),
+])
+export type MachinePrivacy = z.infer<typeof machinePrivacySchema>
+/** As a pool keeps it: `seenAt` is when this server first received that check's result, on the server's clock. */
+export type StoredPrivacy = MachinePrivacy & { seenAt: number }
export const machineObservationSchema = z.object({ generation: z.string().max(160), resources: resource,
tools: z.record(z.string().max(80), z.boolean()).refine(v => Object.keys(v).length <= 20),
toolProbeErrors: z.record(z.string().max(80), z.string().max(200)).refine(v => Object.keys(v).length <= 20).optional(),
@@ -64,12 +81,101 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16
* agent (cli/src/lib/codingModel.ts), with why: so the route can tell a Lead asked for one why it is not offered. */
refusedModels: z.array(z.object({ grid: z.string().min(1).max(160), model: z.string().min(1).max(200),
name: z.string().max(200).optional(), why: z.string().min(1).max(300) }).strict()).max(16).optional(),
+ /** A Harness Team daemon's privacy check; absent from the owner's own daemon and from hosts before it. The store keeps
+ * it only when a team session reported it (observedPrivacy). */
+ privacy: machinePrivacySchema.optional(),
}).strict()
export type MachineObservation = z.infer<typeof machineObservationSchema>
/** A machine reports every 15 seconds (cli/src/superTabs/machines.ts); three missed beats is offline. */
export const MACHINE_FRESH_MS = 45_000
+// ── Teammates' work runs only on Team machines (docs/plans/2026-10-24-swarm-team-account.md, Task 3) ──────────────
+// A start or an assignment for a project whose owner is not the person whose grant runs the machine is a teammate's
+// work. It would run as that machine's owner, with their files, logins and subscriptions, so it is admitted only on a
+// Team machine — the Mac's Harness Team account, or a machine used only for agents — that shows its privacy now.
+// Everything else refuses it and says why; a person's own projects on their own machines are unchanged.
+
+/** How long a passed privacy check counts, from when this server first received it. The team account checks again
+ * every 5 minutes (cli/src/team/privacy.ts PRIVACY_RECHECK_MS) and reports within a 15-second beat, so a healthy
+ * machine's check is never older than about 5 minutes here. 15 minutes allows two missed rechecks (a slow check, a
+ * daemon restart) before routing stops, and bounds to 15 minutes how long a home folder opened again but no longer
+ * checked can still be trusted. A failing check counts at once, whatever its age. */
+export const PRIVACY_FRESH_MS = 15 * 60_000
+
+/**
+ * The privacy a reading leaves on the pool: only a team session's, since an ordinary computer's says nothing about a
+ * team account. The same check sent again keeps the date it first arrived, so a check that stops running goes stale on
+ * the server's clock, whatever the reporting Mac's clock says.
+ */
+export function observedPrivacy(previous: StoredPrivacy | undefined, reported: MachinePrivacy | undefined, team: boolean, now: number): StoredPrivacy | undefined {
+ if (!team || !reported) return undefined
+ const same = previous && previous.mode === reported.mode && (reported.mode === 'dedicated'
+ || (previous.mode === 'account' && previous.passed === reported.passed && previous.checkedAt === reported.checkedAt))
+ return { ...reported, seenAt: same ? previous.seenAt : now }
+}
+
+export type TeamWorkCode = 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
+export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }
+/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */
+export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED']
+
+/** What each item of the privacy check (cli/src/team/privacy.ts) could reach when it failed. */
+const PRIVACY_ITEMS: Record<string, string> = {
+ sentinel: 'it could read the privacy sentinel in its owner\'s home folder', 'home-listing': 'it could list its owner\'s home folder',
+ gitconfig: 'it could read its owner\'s ~/.gitconfig', ssh: 'it could list its owner\'s ~/.ssh', projects: 'it could list its owner\'s project folders',
+ keychain: 'it could list its owner\'s login Keychain folder', chrome: 'it could list its owner\'s Chrome profile', safari: 'it could list its owner\'s Safari folder',
+ 'standard-user': 'the team account is an administrator', unchecked: 'the check did not run',
+}
+const ONLY_OWN = 'so it runs only its owner\'s projects'
+
+/** Why this contributed machine may not run a teammate's project now, or null when it may. `teamRow`: its account row
+ * says it is signed in as a team account (`Machine.sessionKind`), read by the store. */
+export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false): TeamWorkRefusal | null {
+ const reading = pool.observation, name = pool.name
+ if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {
+ return { code: 'MACHINE_OFFLINE', reason: `${name} is offline, so it cannot show that its Harness Team account is private.` }
+ }
+ if (!teamRow && reading.sessionKind !== 'team') return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `${name} has no Harness Team account yet, ${ONLY_OWN}.` }
+ const privacy = reading.privacy
+ if (!privacy) return { code: 'PRIVACY_UNCHECKED', reason: `${name} has not reported a privacy check from its Harness Team account, ${ONLY_OWN}.` }
+ if (privacy.mode === 'dedicated') return null
+ if (!privacy.passed) {
+ const what = PRIVACY_ITEMS[privacy.item]
+ return { code: 'PRIVACY_CHECK_FAILED', reason: `The Harness Team account on ${name} is not private (${privacy.item}${what ? `: ${what}` : ''}), ${ONLY_OWN}.` }
+ }
+ if (now - privacy.seenAt > PRIVACY_FRESH_MS) {
+ const minutes = Math.floor((now - privacy.seenAt) / 60_000)
+ return { code: 'PRIVACY_CHECK_STALE', reason: `The privacy check on ${name} last passed ${minutes} minutes ago, ${ONLY_OWN} until it passes again.` }
+ }
+ return null
+}
+
+/**
+ * Whether work for [project] may run on [machineId] under [contributorId]'s grant there: the pool's contributor for a
+ * start on a contributed machine, the agent's contributor for an agent already in the Swarm. The project owner's own
+ * grant always may. A teammate's needs a contributed Team machine that shows its privacy (teamWorkRefusal); a machine
+ * outside the Swarm's Machines list reports nothing, so it never does. `teamMachines`: the tab's machines whose account
+ * row is signed in as a team account, read by the store.
+ */
+export function teamWorkCheck(state: SuperTabState, machineId: string, contributorId: string, project: SwarmProject, now: number,
+ teamMachines: readonly string[] = []): TeamWorkRefusal | null {
+ if (project.ownerId === contributorId) return null
+ const pool = state.machines?.find(m => m.machineId === machineId)
+ if (!pool) return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `This machine is not a Team machine of this Swarm, ${ONLY_OWN}.` }
+ return teamWorkRefusal(pool, now, teamMachines.includes(machineId))
+}
+
+/** Refuses with the refusal's code and sentence: 403, or 409 like any start on an offline machine. */
+export function failTeamWork(refusal: TeamWorkRefusal, after = ''): never {
+ fail(refusal.code, `${refusal.reason}${after}`, refusal.code === 'MACHINE_OFFLINE' ? 409 : 403)
+}
+
+export function requireTeamWork(...args: Parameters<typeof teamWorkCheck>): void {
+ const refusal = teamWorkCheck(...args)
+ if (refusal) failTeamWork(refusal)
+}
+
/** Since when an agent has been down: the stored time a reading first showed its session gone or the host confirmed its
* stop, or its machine's last reading once that is stale. Nothing is written while a machine is silent, so that case is
* read from the reading itself. Undefined while it is up. */
@@ -202,7 +308,9 @@ export function localModelAllowed(state: SuperTabState, request: AgentStartReque
&& (pool.observation.localModels ?? []).some(l => l.grid === request.gridName && l.model === request.gridModel)
}
-export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart) {
+/** `teamMachines`: the tab's machines whose account row is signed in as a team account, read by the store. A start is
+ * admitted again when its host launches it, so a Team machine whose check failed or went stale since never launches it. */
+export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart, teamMachines: readonly string[] = []) {
const pool = machineContribution(state, request.machineId)
if (!pool) return null
if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
@@ -210,6 +318,8 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
if (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.')
+ // Before the request's own fields: a machine that takes none of this project's work says so first.
+ requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines)
const cwd = pool.scope === 'swarm'
? project.repository?.machineId === pool.machineId ? project.repository.cwd : `${pool.cwd.replace(/\/+$/, '')}/${project.id}`
: pool.cwd
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index eed64a652..691ff6945 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -403,6 +403,12 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
delete visible.overlapAlerts
// Only that machine's host roster lists them (store.ts hostTabs); a removed private agent's session is not every member's.
delete visible.closingSessions
+ // A failing privacy check's detail is its contributor's: an error from the check can name paths on their Mac. Everyone
+ // else reads which item failed (machines.ts teamWorkRefusal).
+ for (const pool of visible.machines ?? []) {
+ const privacy = pool.observation?.privacy
+ if (privacy && 'detail' in privacy && !(actor.kind === 'person' && actor.userId === pool.contributorId)) delete (privacy as { detail?: string }).detail
+ }
expireRemovals(visible, now)
// A read never hands out the cleanup records it just applied (store.ts hostTabs delivers them to the machine's host).
delete visible.machineCleanups
diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.ts
index 2cec74d15..d16b7ed58 100644
--- a/backend/src/superTabs/projects.test.ts
+++ b/backend/src/superTabs/projects.test.ts
@@ -443,13 +443,14 @@ describe('custom role sets', () => {
it('starts and assigns by a role id that exists in the custom set and matches the agent\'s kind', () => {
const { f, p } = custom()
f.run({ type: 'project.role.set', projectId: p.projectId, role: role('abcdefabcdef', 'Docs writer', 'builder') }, peer)
- const start = (extra: Record<string, unknown>) => String(f.run({ type: 'agent.start', request: request(p.conversationId, extra) } as Command).startId)
+ // The project's owner starts it: a teammate's project runs only on a Team machine (machines.ts teamWorkCheck).
+ const start = (extra: Record<string, unknown>) => String(f.run({ type: 'agent.start', request: request(p.conversationId, extra) } as Command, peer).startId)
expect(() => start({ roleId: 'review' })).toThrow('kind')
expect(() => start({ roleId: 'lead' })).toThrow('kind')
expect(() => start({ roleId: 'eeeeeeeeeeee' })).toThrow('not in this project')
expect(() => start({ role: 'reviewer', roleId: 'dev' })).toThrow('kind')
const startId = start({ roleId: 'abcdefabcdef' })
- const worker = String(f.run({ type: 'agent.started', startId, harnessId: 'native', configuration }).agentId)
+ const worker = String(f.run({ type: 'agent.started', startId, harnessId: 'native', configuration }, peer).agentId)
expect(f.state.agents.find(a => a.id === worker)!.roleId).toBe('abcdefabcdef')
const group = String(f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Work', brief: 'Do it', checks: [{ description: 'Done', independent: false }] }, peer).conversationId)
expect(() => f.run({ type: 'work.assign', conversationId: group, agentId: worker, roleId: 'review' }, peer)).toThrow('kind')
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index a08efd735..739441c17 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,4 +1,4 @@
-import { contributedEngines, expireRemovals, hostLocalGrid, machineContribution, machineObservationSchema, machineSlots, recordAgentPresence, removalPreview, swarmGridRow, type MachineObservation } from './machines.js'
+import { contributedEngines, expireRemovals, hostLocalGrid, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, observedPrivacy, recordAgentPresence, removalPreview, swarmGridRow, teamWorkRefusal, type MachineObservation } from './machines.js'
import { createHash } from 'node:crypto'
import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery, SuperTabMessage } from '@prisma/client'
import type { AuthUser } from '../lib/ssoAuth.js'
@@ -101,6 +101,9 @@ async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promi
/** A Lead's start dispatches within seconds of being recorded; one still undispatched after this long was given up. */
export 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'])
+
/** 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. */
async function abandonedStarts(tx: Transaction, tabId: string, state: SuperTabState, machineId: string, now: number) {
@@ -186,6 +189,16 @@ export class SuperTabStore {
}
}
+ /** The tab's contributed machines whose account row is signed in as a Harness Team account (`Machine.sessionKind`,
+ * lib/teamSession.ts): one of the two signs routing reads that a machine is a Team machine (machines.ts teamWorkCheck). */
+ private async teamMachines(tx: Transaction, state: SuperTabState): Promise<string[]> {
+ const ids = (state.machines ?? []).map(m => m.machineId)
+ if (!ids.length) return []
+ const rows = await tx.machine.findMany({ where: { machineId: { in: ids }, autonomousEnv: state.environment, sessionKind: 'team', ...machineAlive },
+ select: { machineId: true } })
+ return rows.map(r => r.machineId)
+ }
+
private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }
async accountPolicy(user: AuthUser) {
@@ -412,11 +425,18 @@ export class SuperTabStore {
// command with a newer revision owns the state; its write also reconstructs any missing link lists.
await tx.superTab.updateMany({ where: { id: tabId, revision: row.revision }, data: { state: json(state) } })
}
- const visible = visibleState(state, actor, this.now())
- const mentions = actor.kind === 'person' ? { mentionsWaiting: await mentionsWaiting(tx, tabId, state, actor, this.now()) } : {}
- return { revision: row.revision, state: { ...visible, ...mentions, machines: visible.machines?.map(pool => ({
- ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, state.machines!.find(m => m.machineId === pool.machineId)!)),
- })) } }
+ const now = this.now()
+ const visible = visibleState(state, actor, now)
+ const mentions = actor.kind === 'person' ? { mentionsWaiting: await mentionsWaiting(tx, tabId, state, actor, now) } : {}
+ const teamMachines = visible.machines?.length ? await this.teamMachines(tx, state) : []
+ return { revision: row.revision, state: { ...visible, ...mentions, machines: visible.machines?.map(pool => {
+ const stored = state.machines!.find(m => m.machineId === pool.machineId)!
+ // Whether it takes teammates' projects now, and if not why (machines.ts teamWorkRefusal): what routing leaves it
+ // out for, and what Desktop can show on the machine.
+ const refusal = teamWorkRefusal(stored, now, teamMachines.includes(pool.machineId))
+ return { ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),
+ teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const } }
+ }) } }
})
}
@@ -442,6 +462,26 @@ export class SuperTabStore {
}
async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {
+ try { return await this.executeOnce(user, tabId, input, asAgentId, hostMachineId) } catch (error) {
+ // A queued start its machine will not take for good — no Harness Team account, or one that is not private — fails
+ // with that reason instead of waiting there: its host would otherwise try to launch it on every pass, and it would
+ // hold a slot. A stale check or an offline machine may pass again by itself, so that start keeps waiting.
+ const command = input.command
+ if (command?.type === 'agent.startDispatch' && hostMachineId && error instanceof SuperTabError && LASTING_TEAM_REFUSALS.includes(error.code)) {
+ // Only one never launched: a repeated dispatch of a launched start is admitted again too, and its agent may be starting.
+ const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv } })
+ const start = row ? stateOf(row).starts?.find(s => s.id === command.startId) : undefined
+ if (start && !start.dispatched && !start.harnessId && !start.error) {
+ await this.executeOnce(user, tabId, { operationId: `team-refused-${command.startId}`,
+ command: { type: 'agent.startFailed', startId: command.startId, error: error.message } }, asAgentId, hostMachineId)
+ .catch(() => { /* Settled by a concurrent pass: the dispatch is refused either way. */ })
+ }
+ }
+ throw error
+ }
+ }
+
+ private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {
const { operationId, command } = operationSchema.parse(input)
let ended: WorkHold[] = []
const done = await transaction(this.db, async tx => {
@@ -557,6 +597,7 @@ export class SuperTabStore {
if (command.type === 'mention.done') context.mention = await readMention(tx, tabId, command.mentionId)
if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)
if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)
+ if (TEAM_WORK_COMMANDS.has(command.type)) context.teamMachines = await this.teamMachines(tx, original)
if (command.type === 'agent.screen' || command.type === 'agent.input') {
// A machine that is gone or no longer shared refuses at once instead of leaving the request to time out.
await this.agentGrant(tx, original, agent(original, command.agentId))
@@ -1186,9 +1227,13 @@ export class SuperTabStore {
return { revision: row.revision + 1 }
}
recordAgentPresence(state, machineId, observation.runningHarnessIds, now)
- pool.observation = { ...observation, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: now,
+ const team = isTeamSession(user)
+ // Its privacy check counts only from the Harness Team account's own session; an ordinary sign-in's claim is dropped.
+ const { privacy: reported, ...reading } = observation
+ const privacy = observedPrivacy(pool.observation?.privacy, reported, team, now)
+ pool.observation = { ...reading, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: now,
// How the machine is signed in, from the session that reported and never from the report (lib/teamSession.ts).
- sessionKind: isTeamSession(user) ? 'team' : 'computer' }
+ sessionKind: team ? 'team' : 'computer', ...(privacy ? { privacy } : {}) }
// Current-generation physical stop proof also finishes a close whose membership was already withdrawn.
for (const proof of observation.stoppedReservations ?? []) {
if (!observation.stoppedHarnessIds.includes(proof.harnessId)) continue
diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.ts
new file mode 100644
index 000000000..5fc544ae3
--- /dev/null
+++ b/backend/src/superTabs/teamRouting.test.ts
@@ -0,0 +1,329 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { admitMachineStart, machineObservationSchema, observedPrivacy, PRIVACY_FRESH_MS, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'
+import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type AgentStart, type SuperTabState } from './model.js'
+import type { RouteDecision } from './routeRecord.js'
+
+// Teammates' work runs only on Team machines (docs/plans/2026-10-24-swarm-team-account.md, Task 3): a start or an
+// assignment for a project whose owner did not contribute the machine needs a Harness Team account whose privacy check
+// passed, or a machine used only for agents. A person's own projects on their own machine are unchanged.
+
+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: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }
+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 }
+type Reading = NonNullable<ContributedMachine['observation']>
+/** A reading as the store keeps it: stamped with the reporting session's kind and, from a team session, its privacy. */
+const reading = (sessionKind: 'team' | 'computer', privacy?: MachinePrivacy, receivedAt = NOW, seenAt = receivedAt): Reading => ({
+ generation: 'g1', receivedAt, sessionKind, resources, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [],
+ ...(privacy ? { privacy: { ...privacy, seenAt } } : {}) })
+const refusal = (body: () => unknown): SuperTabError | null => {
+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error; throw error }
+}
+
+/** The owner's Swarm: the owner's project ('lead') and the teammate's own project, the owner's Mac, the teammate's
+ * personal MacBook and the teammate's Team machine, all contributed for every project. */
+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 effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...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): ContributedMachine => ({ machineId, name, contributorId,
+ membershipGeneration: generation(contributorId), generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, paused: false, observation })
+ state.machines = [
+ pool('owner-mac', 'owner', 'Owner Mac', reading('computer')),
+ pool('mate-mac', 'mate', 'MacBook Pro', reading('computer')),
+ pool('mate-team', 'mate', 'MacBook Pro · Team', reading('team', PASSED)),
+ ]
+ const mine = String(run({ type: 'project.create', name: 'Mine', visibility: 'public', brief: '' }, mate).result.projectId)
+ const group = (projectId = 'lead', actor: Actor = owner) => String(run({ type: 'conversation.create', projectId, title: 'Work', brief: 'Build it.',
+ checks: [{ description: 'Tests pass.', independent: false }] }, actor).result.conversationId)
+ /** An agent already in the Swarm on [machineId], run by [contributorId]'s grant there. */
+ const member = (id: string, machineId: string, contributorId: string, projectId = 'lead', extra: Record<string, unknown> = {}) => {
+ state.agents.push({ id, machineId, harnessId: `harness-${id}`, projectId, machineOwnerId: contributorId, contributorId,
+ membershipGeneration: generation(contributorId), hostGrant: null, name: id, configuration: config, ...extra })
+ return id
+ }
+ const machine = (machineId: string) => state.machines!.find(m => m.machineId === machineId)!
+ /** A start request for [conversationId] on a contributed machine, in the folder the contribution gives that project. */
+ const request = (conversationId: string, machineId: string, projectId = 'lead') =>
+ ({ conversationId, machineId, engine: 'codex', name: 'Builder', cwd: `/swarm/${projectId}`, worktree: true, requirements })
+ const pooled = (machineId: string) => ({ contribution: { machineOwnerId: machine(machineId).contributorId, contributorId: machine(machineId).contributorId, hostGrant: null } })
+ return { run, group, member, machine, request, pooled, mine, get state() { return state } }
+}
+
+describe('the privacy field of a machine reading', () => {
+ const { receivedAt: _receivedAt, sessionKind: _kind, ...sent } = reading('computer')
+
+ it('takes each shape the Harness Team account sends, and nothing else', () => {
+ for (const privacy of [PASSED, FAILED, { mode: 'dedicated' }, { ...FAILED, item: 'unchecked', detail: 'The privacy check did not run: EIO' }]) {
+ expect(machineObservationSchema.safeParse({ ...sent, privacy }).success, JSON.stringify(privacy)).toBe(true)
+ }
+ expect(machineObservationSchema.safeParse(sent).success).toBe(true)
+ for (const privacy of [
+ { mode: 'account', passed: true }, { ...PASSED, item: 'gitconfig' }, { ...PASSED, checkedAt: -1 }, { ...PASSED, checkedAt: 'now' },
+ { mode: 'account', passed: false, item: 'gitconfig', checkedAt: NOW }, { ...FAILED, item: 'Git Config' }, { ...FAILED, item: '' },
+ { ...FAILED, detail: 'x'.repeat(1001) }, { mode: 'dedicated', passed: true }, { mode: 'vm' }, { ...PASSED, extra: 1 }, null,
+ ]) expect(machineObservationSchema.safeParse({ ...sent, privacy }).success, JSON.stringify(privacy)).toBe(false)
+ })
+
+ it('is kept only from a team session\'s reading, dated by when this server first received that check', () => {
+ expect(observedPrivacy(undefined, PASSED, true, NOW)).toEqual({ ...PASSED, seenAt: NOW })
+ // An ordinary computer's reading proves nothing about a team account, so what it claims is dropped.
+ expect(observedPrivacy(undefined, PASSED, false, NOW)).toBeUndefined()
+ expect(observedPrivacy({ ...PASSED, seenAt: NOW }, { mode: 'dedicated' }, false, NOW)).toBeUndefined()
+ expect(observedPrivacy({ ...PASSED, seenAt: NOW }, undefined, true, NOW)).toBeUndefined()
+ // The same check sent again keeps its first date, so a check that stops running goes stale whatever the Mac's clock says.
+ expect(observedPrivacy({ ...PASSED, seenAt: NOW - 20 * MINUTE }, PASSED, true, NOW)).toEqual({ ...PASSED, seenAt: NOW - 20 * MINUTE })
+ expect(observedPrivacy({ ...PASSED, seenAt: NOW - 20 * MINUTE }, { ...PASSED, checkedAt: NOW }, true, NOW)).toEqual({ ...PASSED, checkedAt: NOW, seenAt: NOW })
+ expect(observedPrivacy({ ...PASSED, seenAt: NOW - 20 * MINUTE }, { ...FAILED, checkedAt: PASSED.checkedAt }, true, NOW)).toMatchObject({ passed: false, seenAt: NOW })
+ expect(observedPrivacy({ mode: 'dedicated', seenAt: NOW - 20 * MINUTE }, { mode: 'dedicated' }, true, NOW)).toEqual({ mode: 'dedicated', seenAt: NOW - 20 * MINUTE })
+ })
+
+ it('shows a failing check\'s detail only to the machine\'s contributor', () => {
+ const f = swarm()
+ f.machine('mate-team').observation = reading('team', FAILED)
+ const privacy = (actor: Actor) => visibleState(f.state, actor, NOW).machines!.find(m => m.machineId === 'mate-team')!.observation!.privacy
+ expect(privacy(mate)).toMatchObject({ item: 'gitconfig', detail: FAILED.detail })
+ expect(privacy(owner)).toEqual({ mode: 'account', passed: false, item: 'gitconfig', checkedAt: FAILED.checkedAt, seenAt: NOW })
+ })
+})
+
+describe('which machines take a teammate\'s project', () => {
+ const pool = (observation?: Reading) => ({ machineId: 'mac', name: 'MacBook Pro', contributorId: 'mate', membershipGeneration: 'g', generation: 'g1',
+ cwd: '/swarm', engines: ['codex'], maxAgents: 2, paused: false, ...(observation ? { observation } : {}) }) as ContributedMachine
+
+ it('a Team machine whose privacy check passed and is fresh', () => {
+ expect(teamWorkRefusal(pool(reading('team', PASSED)), NOW)).toBeNull()
+ // Fresh up to the bound, measured from when the server first received the check.
+ expect(teamWorkRefusal(pool(reading('team', PASSED, NOW, NOW - PRIVACY_FRESH_MS)), NOW)).toBeNull()
+ })
+
+ it('a machine used only for agents', () => {
+ expect(teamWorkRefusal(pool(reading('team', { mode: 'dedicated' }, NOW, NOW - 60 * MINUTE)), NOW)).toBeNull()
+ })
+
+ it('not with a stale check', () => {
+ expect(teamWorkRefusal(pool(reading('team', PASSED, NOW, NOW - PRIVACY_FRESH_MS - MINUTE)), NOW)).toEqual({ code: 'PRIVACY_CHECK_STALE',
+ reason: 'The privacy check on MacBook Pro last passed 16 minutes ago, so it runs only its owner\'s projects until it passes again.' })
+ })
+
+ it('not with a failing check, naming the item', () => {
+ expect(teamWorkRefusal(pool(reading('team', FAILED)), NOW)).toEqual({ code: 'PRIVACY_CHECK_FAILED',
+ reason: '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.' })
+ expect(teamWorkRefusal(pool(reading('team', { ...FAILED, item: 'standard-user' })), NOW)?.reason).toContain('(standard-user: the team account is an administrator)')
+ expect(teamWorkRefusal(pool(reading('team', { ...FAILED, item: 'unchecked' })), NOW)?.reason).toContain('(unchecked: the check did not run)')
+ expect(teamWorkRefusal(pool(reading('team', { ...FAILED, item: 'icloud' })), NOW)?.reason).toContain('(icloud)')
+ })
+
+ it('not on a machine with no Harness Team account', () => {
+ expect(teamWorkRefusal(pool(reading('computer')), NOW)).toEqual({ code: 'TEAM_ACCOUNT_REQUIRED',
+ reason: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' })
+ // A reading from before readings were stamped with their session is an ordinary machine's.
+ const { sessionKind: _kind, ...unstamped } = reading('computer')
+ expect(teamWorkRefusal(pool(unstamped as Reading), NOW)?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+
+ it('not on a Team machine that reported no privacy check', () => {
+ expect(teamWorkRefusal(pool(reading('team')), NOW)).toEqual({ code: 'PRIVACY_UNCHECKED',
+ reason: 'MacBook Pro has not reported a privacy check from its Harness Team account, so it runs only its owner\'s projects.' })
+ // Its account row says team, but the reading came from an ordinary sign-in, which carries no privacy.
+ expect(teamWorkRefusal(pool(reading('computer')), NOW, true)?.code).toBe('PRIVACY_UNCHECKED')
+ })
+
+ it('not while offline', () => {
+ for (const offline of [pool(), pool(reading('team', PASSED, NOW - 46_000))]) {
+ expect(teamWorkRefusal(offline, NOW)).toEqual({ code: 'MACHINE_OFFLINE',
+ reason: 'MacBook Pro is offline, so it cannot show that its Harness Team account is private.' })
+ }
+ })
+})
+
+describe('starting a teammate\'s work', () => {
+ it('is refused on a personal machine, with a reason a person understands', () => {
+ const f = swarm(), group = f.group()
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))))
+ .toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403, message: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' })
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('is admitted on the teammate\'s Team machine whose privacy check passed', () => {
+ const f = swarm(), group = f.group()
+ f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, f.pooled('mate-team'))
+ expect(f.state.starts).toHaveLength(1)
+ })
+
+ it('is refused on a Team machine whose check is stale, failing or missing, and while it is offline', () => {
+ for (const [observation, code] of [[reading('team', PASSED, NOW, NOW - 20 * MINUTE), 'PRIVACY_CHECK_STALE'], [reading('team', FAILED), 'PRIVACY_CHECK_FAILED'],
+ [reading('team'), 'PRIVACY_UNCHECKED'], [reading('team', PASSED, NOW - 60_000), 'MACHINE_OFFLINE']] as const) {
+ const f = swarm(), group = f.group()
+ f.machine('mate-team').observation = observation
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, f.pooled('mate-team')))?.code).toBe(code)
+ }
+ })
+
+ it('reads the account row too: a team row with an ordinary reading has no privacy check to show', () => {
+ const f = swarm(), group = f.group()
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, { ...f.pooled('mate-mac'), teamMachines: ['mate-mac'] }))?.code)
+ .toBe('PRIVACY_UNCHECKED')
+ })
+
+ it('leaves a person\'s own projects on their own machines as they were', () => {
+ const f = swarm()
+ f.run({ type: 'agent.start', request: f.request(f.group(), 'owner-mac') }, owner, f.pooled('owner-mac'))
+ const mine = f.group(f.mine, mate)
+ f.run({ type: 'agent.start', request: f.request(mine, 'mate-mac', f.mine) }, mate, f.pooled('mate-mac'))
+ expect(f.state.starts).toHaveLength(2)
+ // The teammate's project on the owner's Mac is the same rule the other way round.
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(mine, 'owner-mac', f.mine) }, mate, f.pooled('owner-mac')))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+
+ it('is re-checked when its host launches it: an admitted start whose check went stale waits', () => {
+ const f = swarm(), group = f.group()
+ f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, f.pooled('mate-team'))
+ const start = f.state.starts![0]! as AgentStart
+ f.machine('mate-team').observation = reading('team', PASSED, NOW, NOW - 20 * MINUTE)
+ expect(refusal(() => admitMachineStart(f.state, start.request, NOW, start))?.code).toBe('PRIVACY_CHECK_STALE')
+ })
+
+ it('is refused on a machine outside the Swarm\'s Machines list, which shows no privacy check', () => {
+ const f = swarm(), group = f.group()
+ // The teammate by hand, on their own uncontributed laptop, for the owner's project.
+ expect(refusal(() => f.run({ type: 'agent.start', request: { ...f.request(group, 'mate-laptop'), cwd: '/work' } }, mate,
+ { contribution: { machineOwnerId: 'mate', contributorId: 'mate' } }))).toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED',
+ message: 'This machine is not a Team machine of this Swarm, so it runs only its owner\'s projects.' })
+ // Their own project there, or the owner's project on a machine shared with the owner by name, as before.
+ f.run({ type: 'agent.start', request: { ...f.request(f.group(f.mine, mate), 'mate-laptop'), cwd: '/work' } }, mate, { contribution: { machineOwnerId: 'mate', contributorId: 'mate' } })
+ f.run({ type: 'agent.start', request: { ...f.request(group, 'shared-mac'), cwd: '/work' } }, owner, { contribution: { machineOwnerId: 'mate', contributorId: 'owner', hostGrant: 'grant-1' } })
+ expect(f.state.starts).toHaveLength(2)
+ })
+})
+
+describe('giving an existing agent a teammate\'s work', () => {
+ it('work.assign is refused for an agent on a personal machine and admitted on a Team machine', () => {
+ const f = swarm(), group = f.group()
+ const personal = f.member('personal', 'mate-mac', 'mate'), team = f.member('team', 'mate-team', 'mate')
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: group, agentId: personal })))
+ .toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403, message: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' })
+ f.run({ type: 'work.assign', conversationId: group, agentId: team })
+ expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ agentId: team, status: 'working' })
+ })
+
+ it('work.assign of a person\'s own project to their own agent is unchanged', () => {
+ const f = swarm(), group = f.group(f.mine, mate)
+ const personal = f.member('personal', 'mate-mac', 'mate', f.mine)
+ f.run({ type: 'work.assign', conversationId: group, agentId: personal }, mate)
+ expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ agentId: personal })
+ })
+
+ it('adding a Reviewer to a group, which hands it the review, is refused on a personal machine', () => {
+ const f = swarm(), group = f.group()
+ const reviewer = f.member('reviewer', 'mate-mac', 'mate', 'lead', { role: 'reviewer' })
+ expect(refusal(() => f.run({ type: 'conversation.agent', conversationId: group, agentId: reviewer, present: true, lead: false }))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ const teamReviewer = f.member('team-reviewer', 'mate-team', 'mate', 'lead', { role: 'reviewer' })
+ f.run({ type: 'conversation.agent', conversationId: group, agentId: teamReviewer, present: true, lead: false })
+ expect(f.state.conversations.find(c => c.id === group)!.agentIds).toContain(teamReviewer)
+ })
+})
+
+describe('routing a teammate\'s work', () => {
+ const candidate = (id: string, machineId: string, patch: Record<string, unknown> = {}) => ({ id, kind: 'new', machineId, engine: 'codex',
+ model: 'default', effort: 'default', quality: 3, cost: 2, title: `${id} on ${machineId}`, label: `Label ${id}`, ...patch })
+ const record = (candidates: unknown[], pick = 'c0') => ({ assessment: { difficulty: 'medium', risk: 'low', why: 'A small change.' },
+ candidates, excluded: [{ title: 'Owner Mac · claude', reason: 'Subscription exhausted.' }], floor: 2, notes: false, pick, via: 'order', p: null,
+ belowFloor: false, why: 'Policy order.' })
+ function routed() {
+ const f = swarm()
+ const lead = String(f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: 'lead', name: 'Lead', configuration: config, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId)
+ const group = f.group()
+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'owner' }
+ const personal = f.member('personal', 'mate-mac', 'mate')
+ return { ...f, get state() { return f.state }, group, leadActor, personal }
+ }
+
+ it('leaves out the machines that cannot take it, and says why', () => {
+ const f = routed()
+ const effects = f.run({ type: 'route.record', conversationId: f.group, decision: record([candidate('c0', 'mate-team'), candidate('c1', 'mate-mac'),
+ candidate('c2', 'mate-mac', { kind: 'member', agentId: f.personal, title: 'personal on mate-mac' }), candidate('c3', 'owner-mac')]) } as Command,
+ f.leadActor, { recentRoutes: 0 })
+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'create', record: {
+ candidates: [{ id: 'c0' }, { id: 'c3' }],
+ excluded: [
+ { title: 'c1 on mate-mac', reason: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' },
+ { title: 'personal on mate-mac', reason: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' },
+ { title: 'Owner Mac · claude', reason: 'Subscription exhausted.' },
+ ] } })
+ expect(effects.messages[0]!.source).toMatchObject({ pick: { id: 'c0' }, alternatives: [{ id: 'c3', title: 'c3 on owner-mac' }] })
+ })
+
+ it('names the failing item and a stale or missing check in the exclusion', () => {
+ const f = routed()
+ f.state.machines!.push({ ...structuredClone(f.machine('mate-team')), machineId: 'mate-stale', name: 'Mini · Team',
+ observation: reading('team', PASSED, NOW, NOW - 30 * MINUTE) })
+ f.machine('mate-team').observation = reading('team', FAILED)
+ const effects = f.run({ type: 'route.record', conversationId: f.group, decision: record([candidate('c0', 'owner-mac'), candidate('c1', 'mate-team'),
+ candidate('c2', 'mate-stale')]) } as Command, f.leadActor, { recentRoutes: 0 })
+ expect((effects.routeDecisions[0] as { record: { excluded: { reason: string }[] } }).record.excluded.map(e => e.reason)).toEqual([
+ '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.',
+ 'The privacy check on Mini · Team last passed 30 minutes ago, so it runs only its owner\'s projects until it passes again.',
+ 'Subscription exhausted.',
+ ])
+ })
+
+ it('refuses a pick that cannot take it, so no decision names it', () => {
+ const f = routed()
+ expect(refusal(() => f.run({ type: 'route.record', conversationId: f.group, decision: record([candidate('c0', 'mate-mac'), candidate('c1', 'mate-team')]) } as Command,
+ f.leadActor, { recentRoutes: 0 }))).toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED',
+ message: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects. Route again.' })
+ })
+
+ it('refuses a person\'s reroute to a candidate whose machine can no longer take it', () => {
+ const f = routed()
+ const decision = { id: 'd1', conversationId: f.group, record: record([candidate('c0', 'owner-mac'), candidate('c1', 'mate-team')]),
+ final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision
+ f.machine('mate-team').observation = reading('team', FAILED)
+ expect(refusal(() => f.run({ type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'More quota there.' }, owner, { routeDecision: decision }))?.code)
+ .toBe('PRIVACY_CHECK_FAILED')
+ f.machine('mate-team').observation = reading('team', PASSED)
+ expect(f.run({ type: 'route.override', decisionId: 'd1', candidateId: 'c1', reason: 'More quota there.' }, owner, { routeDecision: decision }).routeDecisions)
+ .toEqual([expect.objectContaining({ op: 'override', id: 'd1' })])
+ })
+
+ it('keeps a person\'s own project routing as it was', () => {
+ const f = routed()
+ const effects = f.run({ type: 'route.record', conversationId: f.group, decision: record([candidate('c0', 'owner-mac')]) } as Command, f.leadActor, { recentRoutes: 0 })
+ expect(effects.routeDecisions[0]).toMatchObject({ record: { candidates: [{ id: 'c0' }], excluded: [{ title: 'Owner Mac · claude' }] } })
+ })
+})
+
+describe('agents already working on a personal machine', () => {
+ it('keep their task, its reports and their messages; only new work for them is refused', () => {
+ const f = swarm(), group = f.group()
+ // Work assigned before the rule: a teammate's agent on their personal Mac doing the owner's project.
+ const old = f.member('old', 'mate-mac', 'mate')
+ const work = f.state.conversations.find(c => c.id === group)!
+ work.agentIds.push(old)
+ work.assignment = { id: 'before-release', agentId: old, status: 'working', configuration: config,
+ execution: { machineId: 'mate-mac', harnessId: 'harness-old', machineOwnerId: 'mate' }, result: null }
+ const oldActor: Actor = { kind: 'agent', agentId: old, machineOwnerId: 'mate' }
+ f.run({ type: 'work.status', conversationId: group, assignmentId: 'before-release', status: 'blocked', result: 'Needs a token.' }, oldActor)
+ expect(f.run({ type: 'message.send', conversationId: group, text: 'Here it is.', replyTo: null, recipientIds: [old] }).messages[0]!.recipients).toEqual([old])
+ expect(f.state.agents.find(a => a.id === old)).not.toHaveProperty('workDecision')
+ expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ id: 'before-release', status: 'blocked' })
+ f.run({ type: 'work.cancel', conversationId: group, assignmentId: 'before-release', reason: 'Moving it.' })
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: group, agentId: old }))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+})
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 3d64c4333..4da0cc5d2 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -771,6 +771,27 @@ describe('routing contributed capacity', () => {
expect(answer).toMatchObject({ ok: true, pick: { machineId: 'm1', engine: 'codex' } })
expect((answer.alternatives as Array<{ machineId: string; engine: string }>).map(x => [x.machineId, x.engine])).toEqual([['m1', 'claude'], ['m2', 'claude'], ['m3', 'claude']])
})
+ it('leaves out a machine that cannot take a teammate\'s project, with the backend\'s reason, and keeps its owner\'s own work there', async () => {
+ const reason = 'Contributed laptop has no Harness Team account yet, so it runs only its owner\'s projects.'
+ const refusing = (contributorId: string) => ({ ...healthy(), contributorId, teamWork: { allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason } })
+ const owners = { id: 'lead', ownerId: 'owner' }
+ // The Swarm owner's project on a teammate's personal laptop: no new agent there, and not its member either.
+ const teammate = await runPool(refusing('mate'), true, {}, owners)
+ expect(teammate.answer).toMatchObject({ error: 'NO_CANDIDATE' })
+ expect(teammate.answer.excluded).toEqual(expect.arrayContaining([
+ expect.objectContaining({ title: expect.stringContaining('Multiply'), reason }),
+ expect.objectContaining({ title: expect.not.stringContaining('Multiply'), reason })]))
+ // The same laptop's own owner's project, as before.
+ expect((await runPool(refusing('mate'), false, {}, { id: 'lead', ownerId: 'mate' })).answer.ok).toBe(true)
+ // A Team machine that takes it, and a backend from before the rule that says nothing.
+ expect((await runPool({ ...healthy(), contributorId: 'mate', teamWork: { allowed: true } }, false, {}, owners)).answer.ok).toBe(true)
+ expect((await runPool({ ...healthy(), contributorId: 'mate' }, false, {}, owners)).answer.ok).toBe(true)
+ // Offline is said once, by the reading's own age.
+ const offline = { ...refusing('mate'), teamWork: { allowed: false, code: 'MACHINE_OFFLINE', reason: 'Contributed laptop is offline.' } }
+ offline.observation.receivedAt = 0
+ const silent = await runPool(offline, false, {}, owners)
+ expect(silent.answer.excluded).not.toEqual(expect.arrayContaining([expect.objectContaining({ reason: expect.stringContaining('Contributed laptop is offline.') })]))
+ })
it('refuses unobserved tools and devices, without probing arbitrary paths on a teammate computer', async () => {
expect((await runPool(healthy(), false, { tools: ['docker'], devices: ['/dev/fixture'] })).answer.ok).not.toBe(true)
})
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index f422f3198..3015f13bd 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -144,9 +144,16 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// The Lead's own machine is the account's even when the list could not be read.
if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })
for (const m of members) if (!machines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.machineId), status: 'unknown', account: false })
+ // A teammate's project runs only on Team machines: the backend says per machine whether it takes one now, and why not
+ // (backend superTabs/machines.ts teamWorkRefusal). Its project owner's own machines take its work as before.
+ const projectOwner = project?.ownerId ?? state.ownerId
for (const original of list(state.machines)) {
const repository = object(project?.repository)
+ const teamWork = object(original.teamWork)
const pool: Json = { ...original,
+ // Offline is said once, by the reading's own age below.
+ ...(teamWork.allowed === false && teamWork.code !== 'MACHINE_OFFLINE' && typeof teamWork.reason === 'string'
+ ? { teammatesRefused: teamWork.reason, projectOwnerId: projectOwner } : {}),
...(original.scope === 'swarm' ? { cwd: repository.machineId === original.machineId
? repository.cwd : `${String(original.cwd).replace(/\/+$/, '')}/${projectId}` } : {}),
...(original.scope !== 'swarm' && projectId !== 'lead' ? { projectUnavailable: true } : {}),
@@ -322,7 +329,9 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const quota = (engine: string) => { const q = quotas.find(q => q.engine === engine); return fresh && q ? quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })) }) : UNKNOWN_QUOTA }
const blocked = [...(!fresh ? [OFFLINE] : []), ...(pool.paused ? ['New work is paused on this machine.'] : [])]
const tools = object(observed.tools)
- const newReasons = [...blocked,
+ /** Work for a project its owner does not run here: a new agent runs under the contribution, a member under its own grant. */
+ const teammates = (contributorId: unknown) => typeof pool.teammatesRefused === 'string' && contributorId !== pool.projectOwnerId ? [pool.teammatesRefused] : []
+ const newReasons = [...blocked, ...teammates(pool.contributorId),
...(pool.projectUnavailable === true ? ['Its owner must add this machine to the swarm again to support other projects.'] : []),
...(pool.repositoryUnavailable === true ? ['Share a repository for this project before starting agents on this machine.'] : []),
...(pool.availableSlots === 0 ? ['This machine has no available agent slots.'] : []),
@@ -333,7 +342,8 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
return [...members.map(m => {
const allowance = quota(String(object(m.configuration).engine))
const running = Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.includes(m.harnessId) : null
- return memberProbe(m, fresh ? memberRefusals(running, allowance, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)) : [OFFLINE],
+ return memberProbe(m, fresh ? [...memberRefusals(running, allowance, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),
+ ...teammates(m.contributorId)] : [OFFLINE],
allowance, null, fresh && running === null)
}),
...models.map(m => newProbe(m, [...newReasons, ...(quota(m.engine).leftPercent === 0 ? ['Subscription exhausted.'] : [])], quota(m.engine), fresh && quota(m.engine).known,
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 662307bf2..60b2da34d 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -24,7 +24,7 @@ const HELP = {
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. On Custom skills, add "roleId" to the start request to start the agent in that role of its kind (a builder or reviewer role from status); without it the agent takes the first role of its kind. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',
release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
- route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","local":"optional true, only when a person asked for a local model","model":"optional: the model a person named, in their words; only it is offered","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out; soft rules (a preferred engine for the kind, idle agents first) rank the rest. A pick on a model served on the Swarm\'s grid starts with gridModel and gridName in place of model and effort. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',
+ route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","local":"optional true, only when a person asked for a local model","model":"optional: the model a person named, in their words; only it is offered","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out, and so are machines that cannot take a teammate\'s project: it runs only on Team machines (a Mac\'s Harness Team account whose privacy check passed, or a machine used only for agents), and the route says why the others were left out. Soft rules (a preferred engine for the kind, idle agents first) rank the rest. A pick on a model served on the Swarm\'s grid starts with gridModel and gridName in place of model and effort. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',
screen: 'screen AGENT [--scrollback N]: read a worker\'s terminal as plain text, with up to 200 lines of scrollback. Only its project\'s Lead may. Use it when a worker seems stuck.',
type: 'type AGENT [TEXT] [--key K]...: type text, then keys (Enter, Esc, Tab, Up, Down, Left, Right, Ctrl-C, 0-9), into a worker\'s terminal. Answer prompts within its task; ask the owner before approving anything risky.',
capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.md
index 390181667..7b237eb1b 100644
--- a/docs/plans/2026-10-24-swarm-team-account.md
+++ b/docs/plans/2026-10-24-swarm-team-account.md
@@ -72,9 +72,17 @@ Files: new `cli/src/team/` (setup script, launchd job, privacy check), `cli/src/
Files: `backend/src/superTabs/machines.ts`, `store.ts`, `routeDecisions.ts`; `cli/src/superTabs/host.ts`.
-- [ ] Tests: a start for a project owned by someone other than the machine's contributor is refused on a personal machine and admitted on a Team machine whose privacy check passed; routing proposes only eligible machines and says why the others were skipped.
+- [x] Tests: a start for a project owned by someone other than the machine's contributor is refused on a personal machine and admitted on a Team machine whose privacy check passed; routing proposes only eligible machines and says why the others were skipped.
- [ ] Joining a Swarm, or contributing a Mac, asks the CLI to run `harness team setup` once. A declined or failed prompt leaves the Mac serving only its owner's projects, with one line on the machine saying why.
-- [ ] Migration: existing contributions keep running agents; new cross-person starts follow the rule.
+- [x] Migration: existing contributions keep running agents; new cross-person starts follow the rule.
+
+How it works (`backend/src/superTabs/machines.ts`, `teamWorkCheck`):
+
+- **A teammate's work** is a start, an assignment, a Reviewer added to a group, or a route pick for a project whose owner is not the person whose grant runs the machine: the contributor of a contributed machine, or the agent's own contributor. It is admitted only on a contributed machine that is a Team machine (its account row's `sessionKind` is `team`, or its reading came from a team session) and whose `privacy` is `dedicated`, or `account` with `passed: true` and fresh. Everything else is refused with a code and a sentence: `TEAM_ACCOUNT_REQUIRED` ("MacBook Pro has no Harness Team account yet, so it runs only its owner's projects."), `PRIVACY_UNCHECKED`, `PRIVACY_CHECK_FAILED` (names the item), `PRIVACY_CHECK_STALE` and `MACHINE_OFFLINE`. A machine off the Swarm's Machines list reports no privacy, so it never takes a teammate's work.
+- **Privacy** is kept from a reading only when a team session sent it; an ordinary computer's claim is dropped. Each check is dated by when the server first received it, so the Mac's clock does not matter. A passed check counts for 15 minutes (`PRIVACY_FRESH_MS`): the team account checks every 5, so that allows two missed checks. A failing check counts at once. Only the machine's contributor reads a failing check's `detail`; everyone reads the item.
+- **Enforced** in `admitMachineStart` (on `agent.start` and again on `agent.startDispatch`), on starts off the Machines list, `work.assign`, `conversation.agent` adding a Reviewer, `route.record` and `route.override`. A queued start whose Team machine refuses it for good (no team account, no check, failing check) fails with that reason when its host tries to launch it; one waiting on a stale check keeps waiting.
+- **Routing.** The tab read gives each machine `teamWork`: `{ allowed: true }`, or `{ allowed: false, code, reason }`. The CLI's route leaves those machines out for a teammate's project and lists the reason in `excluded[]`. The backend does the same with any candidate an older CLI still sends, and refuses a pick there ("… Route again.").
+- **Migration.** Nothing is stopped. Agents already running on personal machines keep their current task, its reports, messages and their sessions. New starts, new assignments and new Reviewer groups for another person's project follow the rule. A personal machine contributed with scope "swarm" now serves only its owner's projects. So does a machine contributed before projects (no scope) by someone other than the Swarm's owner: the Swarm's first project is the owner's.
## Task 4: Harness GitHub App (backend, CLI)