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 Workspaces (backend): several Workspaces and Swarms on one account, with roles (#1811)

0xken1574f0697165bc
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index 9409ded79..1d53448f2 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -330,7 +330,7 @@ describe('Swarm list and old routes (design 4.9, 4.11)', () => {
it('lists the caller\'s Swarms with their newest change', async () => {
const s = await scene()
const { body } = await get('/api/super-tabs/list', outsider)
- expect(body.data.tabs).toContainEqual({ id: s.tabId, name: 'Pilot', ownerId: owner.sub, paused: false, lastChangedAt: MIGRATED })
+ expect(body.data.tabs).toContainEqual({ id: s.tabId, name: 'Pilot', ownerId: owner.sub, workspaceId: null, paused: false, lastChangedAt: MIGRATED })
})
it.each(['/api/super-tabs', '/api/super-tabs/TAB', '/api/super-tabs/hosts/host', '/api/super-tabs/hosts/host/pools', '/api/super-tabs/hosts/host/assignments'])(
diff --git a/backend/integration/superTabWorkspaces.test.ts b/backend/integration/superTabWorkspaces.test.ts
new file mode 100644
index 000000000..65ae1e74b
--- /dev/null
+++ b/backend/integration/superTabWorkspaces.test.ts
@@ -0,0 +1,457 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { promisify } from 'node:util'
+import Fastify, { type FastifyInstance } from 'fastify'
+import { PrismaClient } from '@prisma/client'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { migrateWorkspaces, rollbackWorkspaces } from '../src/superTabs/migration/workspaces.js'
+import { hasWorkspaceAccess, SwarmWorkspaces } from '../src/superTabs/workspaceStore.js'
+
+// Workspaces above Swarms (docs/plans/2026-10-27-swarm-workspaces.md): every route, authorization and Mongo transaction is real.
+let replica: MongoMemoryReplSet, db: PrismaClient, store: SuperTabStore, app: FastifyInstance
+
+const user = (n: number, email: string): AuthUser => ({ sub: `30000000000000000000000${n}`, email, autonomousEnv: 'prod', role: 'user' })
+const owner = user(1, '[email protected]'), peer = user(2, '[email protected]'), other = user(3, '[email protected]'),
+ admin = user(4, '[email protected]'), member = user(5, '[email protected]')
+const legacyOwner = user(6, '[email protected]'), legacyPeer = user(7, '[email protected]')
+const accounts = [owner, peer, other, admin, member, legacyOwner, legacyPeer]
+const call = (method: 'GET' | 'POST', url: string, as: AuthUser, body?: object) =>
+ app.inject({ method, url, headers: { authorization: `Bearer ${as.sub}` }, ...(body ? { payload: body } : {}) })
+const run = async (tab: string, command: Command, as = owner) => {
+ const reply = await call('POST', `/api/super-tabs/${tab}/commands`, as, { operationId: randomUUID(), command })
+ if (reply.statusCode !== 200) throw new Error(`${command.type}: ${reply.statusCode} ${reply.body}`)
+ return reply.json().data as { result: Record<string, unknown> }
+}
+const create = async (as = owner, name = 'Fixture Swarm', workspaceId?: string) => {
+ const reply = await call('POST', '/api/super-tabs', as, { operationId: randomUUID(), name, ...(workspaceId ? { workspaceId } : {}) })
+ if (reply.statusCode !== 200) throw new Error(`create: ${reply.statusCode} ${reply.body}`)
+ return reply.json().data.id as string
+}
+const workspacesOf = async (as: AuthUser) => (await call('GET', '/api/super-tabs/workspaces', as)).json().data.workspaces as
+ Array<{ id: string; name: string; role: string; swarms: Array<{ id: string; name: string; member: boolean }> }>
+const listed = async (as: AuthUser) => ((await call('GET', '/api/super-tabs/list', as)).json().data.tabs as Array<{ id: string; workspaceId: string | null }>)
+/** Adds `who` to the Swarm the way an owner does today: an invitation, accepted. */
+const invite = async (tab: string, who: AuthUser, by = owner) => {
+ const invitation = await run(tab, { type: 'invite.create', email: who.email, role: 'collaborator', conversationId: 'lead' } as Command, by)
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string } as Command, who)
+}
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_workspaces_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ store = new SuperTabStore(db)
+ for (const account of accounts) await db.user.create({ data: { id: account.sub, externalId: `workspaces-fixture-${account.sub}`,
+ email: account.email, autonomousEnv: account.autonomousEnv } })
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ app.addHook('onRequest', async (req, reply) => {
+ const account = accounts.find(a => `Bearer ${a.sub}` === req.headers.authorization)
+ if (!account) return reply.code(401).send({ success: false })
+ req.user = account
+ })
+ await app.register(superTabRoutes, { store })
+ await app.ready()
+})
+afterAll(async () => { await app?.close(); await db?.$disconnect(); await replica?.stop() })
+
+describe('a new Swarm lands in a Workspace', () => {
+ it('puts a person\'s Swarms in their own Workspace, made on first need, and lists it with its Swarms', async () => {
+ const first = await create(other, 'Lamp OS'), second = await create(other, 'Second')
+ const workspaces = await workspacesOf(other)
+ expect(workspaces).toHaveLength(1)
+ expect(workspaces[0]).toMatchObject({ name: 'Lamp OS', role: 'owner' })
+ expect(workspaces[0]!.swarms.map(s => s.id).sort()).toEqual([first, second].sort())
+ const rows = await listed(other)
+ expect(rows.filter(r => r.id === first || r.id === second).map(r => r.workspaceId)).toEqual([workspaces[0]!.id, workspaces[0]!.id])
+ })
+})
+
+describe('the Workspace check on every Swarm read and command', () => {
+ it('refuses a person whose Workspace membership was removed on every read path and command, before their Swarm removal runs', async () => {
+ const tab = await create(owner, 'Checked')
+ await invite(tab, peer)
+ const cursor = (await call('GET', `/api/super-tabs/${tab}/parts`, peer)).json().data.cursor as string
+ const reads = [`/api/super-tabs/${tab}/parts`, `/api/super-tabs/${tab}/changes?cursor=${encodeURIComponent(cursor)}`, `/api/super-tabs/${tab}/groups?dormant=1`,
+ `/api/super-tabs/${tab}/groups/lead`, `/api/super-tabs/${tab}/conversations/lead/messages`, `/api/super-tabs/${tab}/mentions?state=waiting`,
+ `/api/super-tabs/${tab}/decisions?state=open`, `/api/super-tabs/${tab}/route-decisions`, `/api/super-tabs/${tab}/leaderboard?projectId=lead`,
+ `/api/super-tabs/${tab}/routing-policy`, `/api/super-tabs/${tab}/conversations/lead/attempts`]
+ for (const url of reads) expect((await call('GET', url, peer)).statusCode, url).toBe(200)
+ expect((await listed(peer)).map(r => r.id)).toContain(tab)
+
+ // As a removal whose Swarm cleanup has not run yet leaves it: the person is still in the Swarm's people.
+ const [workspace] = await workspacesOf(owner)
+ const removed = await db.swarmWorkspaceMember.update({ where: { id: `${workspace!.id}:${peer.sub}` }, data: { removedAt: new Date(), removedBy: owner.sub } })
+ await db.swarmWorkspaceRemoval.create({ data: { id: `${removed.id}:${removed.generation}`, workspaceId: workspace!.id, userId: peer.sub, email: peer.email,
+ generation: removed.generation, autonomousEnv: 'prod', removedAt: new Date(), removedBy: owner.sub, finishedAt: null } })
+
+ for (const url of reads) {
+ const reply = await call('GET', url, peer)
+ expect(reply.statusCode, url).toBe(403)
+ expect(JSON.stringify(reply.json()), url).toContain('WORKSPACE_ACCESS_REVOKED')
+ }
+ const send = await call('POST', `/api/super-tabs/${tab}/commands`, peer,
+ { operationId: randomUUID(), command: { type: 'message.send', conversationId: 'lead', text: 'still here?', replyTo: null, recipientIds: [] } })
+ expect(send.statusCode).toBe(403)
+ expect((await listed(peer)).map(r => r.id)).not.toContain(tab)
+ // The Swarm's own people are untouched.
+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, owner)).statusCode).toBe(200)
+ // The sweep finishes the Swarm removal that did not run.
+ expect(await swarmPeople(tab)).toContain(peer.sub)
+ expect(await store.workspaces.finishRemovals()).toBe(0)
+ expect(await swarmPeople(tab)).not.toContain(peer.sub)
+ })
+
+ it('keeps a person of one Workspace out of another Workspace\'s Swarm', async () => {
+ const theirs = await create(other, 'Elsewhere')
+ const reply = await call('GET', `/api/super-tabs/${theirs}/parts`, owner)
+ expect(reply.statusCode).toBe(403)
+ expect(JSON.stringify(reply.json())).not.toContain('Elsewhere')
+ expect((await workspacesOf(owner)).flatMap(o => o.swarms.map(s => s.id))).not.toContain(theirs)
+ })
+})
+
+/** A Workspace of the owner with an admin, a member and a guest, each having accepted their invitation. */
+async function workspace(name: string) {
+ const created = await call('POST', '/api/super-tabs/workspaces', owner, { operationId: randomUUID(), name })
+ if (created.statusCode !== 200) throw new Error(`workspace create: ${created.statusCode} ${created.body}`)
+ const workspaceId = created.json().data.id as string
+ for (const [who, role] of [[admin, 'admin'], [member, 'member'], [peer, 'guest']] as const) {
+ const invited = await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, owner, { email: who.email, role })
+ if (invited.statusCode !== 200) throw new Error(`invite: ${invited.statusCode} ${invited.body}`)
+ const accepted = await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, who, {})
+ if (accepted.statusCode !== 200) throw new Error(`accept: ${accepted.statusCode} ${accepted.body}`)
+ }
+ return workspaceId
+}
+const people = async (workspaceId: string, as: AuthUser) => call('GET', `/api/super-tabs/workspaces/${workspaceId}/members`, as)
+const roleOf = async (workspaceId: string, who: AuthUser) =>
+ ((await people(workspaceId, owner)).json().data.members as Array<{ userId: string; role: string }>).find(m => m.userId === who.sub)?.role
+const swarmPeople = async (tab: string) => ((await call('GET', `/api/super-tabs/${tab}/parts`, owner)).json().data.members as Array<{ data: { id: string } }>).map(p => p.data.id)
+
+describe('Workspace people and roles', () => {
+ it('shows the people list to members and up, never to guests or outsiders, and lets only owners and admins invite', async () => {
+ const workspaceId = await workspace('People')
+ const list = await people(workspaceId, member)
+ expect(list.statusCode).toBe(200)
+ expect((list.json().data.members as Array<{ email: string; role: string }>).map(m => [m.email, m.role]).sort()).toEqual([
+ [admin.email, 'admin'], [member.email, 'member'], [owner.email, 'owner'], [peer.email, 'guest']].sort())
+ expect((await people(workspaceId, peer)).statusCode).toBe(403)
+ expect((await people(workspaceId, other)).statusCode).toBe(404)
+ // Someone not invited cannot accept.
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, other, {})).statusCode).toBe(404)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, member, { email: other.email, role: 'guest' })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, admin, { email: other.email, role: 'admin' })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, admin, { email: other.email, role: 'guest' })).statusCode).toBe(200)
+ })
+
+ it('lets an admin change members and guests but not another admin, and the owner anyone but themselves', async () => {
+ const workspaceId = await workspace('Roles')
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${peer.sub}`, admin, { role: 'member' })).statusCode).toBe(200)
+ expect(await roleOf(workspaceId, peer)).toBe('member')
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${admin.sub}`, admin, { role: 'member' })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${member.sub}`, admin, { role: 'admin' })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${admin.sub}`, owner, { role: 'member' })).statusCode).toBe(200)
+ expect(await roleOf(workspaceId, admin)).toBe('member')
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${owner.sub}`, owner, { role: 'admin' })).statusCode).toBe(403)
+ })
+
+ it('transfers ownership only to an admin; the old owner becomes an admin', async () => {
+ const workspaceId = await workspace('Transfer')
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/transfer`, owner, { userId: member.sub })).statusCode).toBe(409)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/transfer`, admin, { userId: admin.sub })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/transfer`, owner, { userId: admin.sub })).statusCode).toBe(200)
+ expect([await roleOf(workspaceId, admin), await roleOf(workspaceId, owner)]).toEqual(['owner', 'admin'])
+ })
+})
+
+describe('Swarms open to the Workspace', () => {
+ it('lets members, not guests, find and join a Swarm only once it is open to the Workspace', async () => {
+ const workspaceId = await workspace('Open')
+ const tab = await create(owner, 'Shared work', workspaceId)
+ const names = async (who: AuthUser) => (await workspacesOf(who)).find(o => o.id === workspaceId)?.swarms.map(s => s.id) ?? []
+ expect(await names(member)).not.toContain(tab)
+ expect(await names(admin)).toContain(tab)
+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, member, { operationId: randomUUID() })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, member, { visibility: 'workspace' })).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, owner, { visibility: 'workspace' })).statusCode).toBe(200)
+ expect(await names(member)).toContain(tab)
+ const joinedOf = async (who: AuthUser) => (await workspacesOf(who)).find(o => o.id === workspaceId)!.swarms.find(s => s.id === tab)!.member
+ expect([await joinedOf(member), await joinedOf(owner)]).toEqual([false, true])
+ expect(await names(peer)).not.toContain(tab)
+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, peer, { operationId: randomUUID() })).statusCode).toBe(403)
+ const joined = await call('POST', `/api/super-tabs/${tab}/workspace-join`, member, { operationId: randomUUID() })
+ expect(joined.statusCode).toBe(200)
+ expect(joined.json().data.role).toBe('collaborator')
+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, member)).statusCode).toBe(200)
+ // Closing it again leaves those who joined, and hides it from the others.
+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, admin, { visibility: 'invite-only' })).statusCode).toBe(200)
+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, member)).statusCode).toBe(200)
+ })
+
+ it('refuses creating a Swarm in a Workspace for a guest or an outsider', async () => {
+ const workspaceId = await workspace('Create')
+ for (const who of [peer, other]) {
+ const reply = await call('POST', '/api/super-tabs', who, { operationId: randomUUID(), name: 'Mine', workspaceId })
+ expect(reply.statusCode, who.email).not.toBe(200)
+ }
+ })
+})
+
+describe('removing someone from a Workspace', () => {
+ it('removes them from every Swarm of the Workspace at once, and leaves their other Workspaces alone', async () => {
+ const workspaceId = await workspace('Removal')
+ const a = await create(owner, 'A', workspaceId), b = await create(owner, 'B', workspaceId)
+ for (const tab of [a, b]) await invite(tab, member)
+ const elsewhere = await create(other, 'Their own')
+ await invite(elsewhere, member, other)
+ const removed = await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${member.sub}/remove`, admin, {})
+ expect(removed.statusCode).toBe(200)
+ for (const tab of [a, b]) {
+ expect(await swarmPeople(tab)).not.toContain(member.sub)
+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, member)).statusCode).toBe(403)
+ }
+ expect((await workspacesOf(member)).map(o => o.id)).not.toContain(workspaceId)
+ expect((await call('GET', `/api/super-tabs/${elsewhere}/parts`, member)).statusCode).toBe(200)
+ })
+
+ it('never removes the owner, nor someone who owns one of the Workspace\'s Swarms, and lets a person leave by themselves', async () => {
+ const workspaceId = await workspace('Guards')
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${owner.sub}/remove`, owner, {})).statusCode).toBe(409)
+ await create(member, 'Member owned', workspaceId)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${member.sub}/remove`, owner, {})).statusCode).toBe(409)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${peer.sub}/remove`, peer, {})).statusCode).toBe(200)
+ expect((await workspacesOf(peer)).map(o => o.id)).not.toContain(workspaceId)
+ })
+
+ it('keeps a removed person from rejoining by a link, while a new invitation brings them back', async () => {
+ const workspaceId = await workspace('Rejoin')
+ const tab = await create(owner, 'Linked', workspaceId)
+ const sharing = await store.sharing(owner, tab)
+ const saved = await store.saveSharing(owner, tab, { operationId: randomUUID(), revision: sharing.revision, access: { mode: 'link', role: 'collaborator' } })
+ const token = new URL(saved.joinUrl!).searchParams.get('token')!
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${peer.sub}/remove`, owner, {})).statusCode).toBe(200)
+ const again = await call('POST', `/api/super-tabs/${tab}/join`, peer, { operationId: randomUUID(), token })
+ expect(again.statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, owner, { email: peer.email, role: 'guest' })).statusCode).toBe(200)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, peer, {})).statusCode).toBe(200)
+ expect((await call('POST', `/api/super-tabs/${tab}/join`, peer, { operationId: randomUUID(), token })).statusCode).toBe(200)
+ })
+})
+
+describe('a machine contributed to Swarms of two Workspaces', () => {
+ /** A contributed machine as the Swarm's parts hold it (only the fields this lookup reads). */
+ const contribute = (tabId: string, machineId: string) => db.swarmMachine.create({ data: { id: `${tabId}:machine:${machineId}`, tabId,
+ key: machineId, version: 1, changedAt: new Date(), ordinal: 0, data: {}, machineId, contributed: true, cleanupOwnerIds: [] } })
+ const lookup = async (tabId: string, machineId: string) => db.$transaction(async tx => {
+ const state = { ...(await store.load(tx, owner, tabId)).state }
+ return store.otherWorkspaceMachines(tx, { ...state, machines: [{ machineId } as never] })
+ })
+
+ it('is named for this Swarm only when the other Swarm is in another Workspace', async () => {
+ const workspaceId = await workspace('Machines')
+ const here = await create(owner, 'Here', workspaceId), sameWorkspace = await create(owner, 'Same Workspace', workspaceId), elsewhere = await create(other, 'Other Workspace')
+ await contribute(sameWorkspace, 'shared-mac')
+ expect(await lookup(here, 'shared-mac')).toEqual([])
+ await contribute(elsewhere, 'shared-mac')
+ expect(await lookup(here, 'shared-mac')).toEqual(['shared-mac'])
+ })
+})
+
+describe('the migration of today\'s Swarms into Workspaces, and its undo', () => {
+ /** A Swarm as it was before Workspaces: no Workspace on its row or head, and no Workspace of its owner. */
+ async function legacy(as: AuthUser, name: string) {
+ const tab = await create(as, name)
+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${tab}:head` } })
+ const { workspaceId: _workspaceId, ...data } = head.data as Record<string, unknown>
+ await db.swarmHead.update({ where: { id: head.id }, data: { data: data as never } })
+ await db.superTab.update({ where: { id: tab }, data: { workspaceId: null } })
+ await db.swarmWorkspaceMember.deleteMany({ where: { userId: as.sub } })
+ await db.swarmWorkspace.deleteMany({ where: { ownerId: as.sub } })
+ return tab
+ }
+
+ it('dry-runs without writing, then puts each owner\'s Swarms in one Workspace with everyone else a guest, once; the undo restores today', async () => {
+ const first = await legacy(legacyOwner, 'Legacy one'), second = await legacy(legacyOwner, 'Legacy two')
+ await invite(first, legacyPeer, legacyOwner)
+ const before = await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)
+
+ const dry = await migrateWorkspaces(db, { apply: false })
+ expect(dry.swarms).toBe(2)
+ expect(dry.workspacesCreated).toBe(1)
+ expect(await db.superTab.count({ where: { id: { in: [first, second] }, workspaceId: { not: null } } })).toBe(0)
+ expect(await db.swarmWorkspace.count({ where: { ownerId: legacyOwner.sub } })).toBe(0)
+
+ const applied = await migrateWorkspaces(db, { apply: true })
+ expect(applied).toMatchObject({ swarms: 2, workspacesCreated: 1, guestsAdded: 1, failed: [] })
+ const [ownerWorkspace] = await workspacesOf(legacyOwner)
+ expect(ownerWorkspace).toMatchObject({ name: 'Legacy one', role: 'owner' })
+ expect(ownerWorkspace!.swarms.map(s => s.id).sort()).toEqual([first, second].sort())
+ const peerWorkspaces = await workspacesOf(legacyPeer)
+ expect(peerWorkspaces.map(o => [o.id, o.role, o.swarms.map(s => s.id)])).toEqual([[ownerWorkspace!.id, 'guest', [first]]])
+ // Nobody gains or loses access.
+ expect((await call('GET', `/api/super-tabs/${first}/parts`, legacyPeer)).statusCode).toBe(200)
+ expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyPeer)).statusCode).toBe(403)
+ expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)).json().data.members).toEqual(before.json().data.members)
+ expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)).json().data.head.data.workspaceId).toBe(ownerWorkspace!.id)
+
+ expect(await migrateWorkspaces(db, { apply: true })).toMatchObject({ swarms: 0, workspacesCreated: 0, guestsAdded: 0 })
+
+ const undone = await rollbackWorkspaces(db, { apply: true })
+ expect(undone.failed).toEqual([])
+ expect(await db.superTab.count({ where: { id: { in: [first, second] }, workspaceId: { not: null } } })).toBe(0)
+ expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)).json().data.head.data.workspaceId).toBeUndefined()
+ expect(await db.swarmWorkspaceMember.count({ where: { userId: { in: [legacyOwner.sub, legacyPeer.sub] } } })).toBe(0)
+ expect((await call('GET', `/api/super-tabs/${first}/parts`, legacyPeer)).statusCode).toBe(200)
+ })
+
+ it('serves a Swarm without a Workspace by its own membership until the switch is on, then refuses and stops listing it', async () => {
+ const tab = await legacy(legacyOwner, 'Before Workspaces')
+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, legacyOwner)).statusCode).toBe(200)
+ process.env.SWARM_WORKSPACES_REQUIRED = '1'
+ try {
+ const reply = await call('GET', `/api/super-tabs/${tab}/parts`, legacyOwner)
+ expect(reply.statusCode).toBe(403)
+ expect(JSON.stringify(reply.json())).toContain('WORKSPACE_ACCESS_REVOKED')
+ expect((await listed(legacyOwner)).map(r => r.id)).not.toContain(tab)
+ } finally { delete process.env.SWARM_WORKSPACES_REQUIRED }
+ await migrateWorkspaces(db, { apply: true })
+ await rollbackWorkspaces(db, { apply: true })
+ })
+
+ it('lists the machines that would serve two Workspaces afterwards, before anything is written', async () => {
+ const mine = await legacy(legacyOwner, 'Mine'), theirs = await legacy(legacyPeer, 'Theirs')
+ for (const tabId of [mine, theirs]) await db.swarmMachine.create({ data: { id: `${tabId}:machine:both`, tabId, key: 'both-mac', version: 1,
+ changedAt: new Date(), ordinal: 0, data: {}, machineId: 'both-mac', contributed: true, cleanupOwnerIds: [] } })
+ const dry = await migrateWorkspaces(db, { apply: false })
+ expect(dry.anomalies.machinesInTwoWorkspaces).toContainEqual({ machineId: 'both-mac', tabIds: [mine, theirs].sort() })
+ await migrateWorkspaces(db, { apply: true })
+ await rollbackWorkspaces(db, { apply: true })
+ })
+})
+
+describe('what the Workspace check costs', () => {
+ it('reads one small Workspace row per person per request, once however many agents that person contributed', async () => {
+ let reads = 0
+ const counted = db.$extends({ query: { swarmWorkspaceMember: { async findUnique({ args, query }) { reads++; return query(args) } } } }) as unknown as PrismaClient
+ const counting = new SuperTabStore(counted)
+ const tab = await create(owner, 'Counted')
+ reads = 0
+ await counting.read(owner, tab)
+ expect(reads).toBe(1)
+ reads = 0
+ await counted.$transaction(async tx => {
+ const { state } = await counting.load(tx, owner, tab)
+ for (let i = 0; i < 5; i++) expect(await hasWorkspaceAccess(tx, state, owner.sub)).toBe(true)
+ })
+ expect(reads).toBe(1)
+ })
+})
+
+describe('a removal whose Swarm cleanup failed', () => {
+ /** As a removal leaves things when leaving one Swarm failed: removed from the Workspace, its record open, still in the Swarm. */
+ async function failedRemoval(workspaceId: string, who: AuthUser) {
+ const row = await db.swarmWorkspaceMember.findUniqueOrThrow({ where: { id: `${workspaceId}:${who.sub}` } })
+ await db.swarmWorkspaceMember.update({ where: { id: row.id }, data: { removedAt: new Date(), removedBy: owner.sub } })
+ await db.swarmWorkspaceRemoval.create({ data: { id: `${row.id}:${row.generation}`, workspaceId, userId: who.sub, email: who.email,
+ generation: row.generation, autonomousEnv: 'prod', removedAt: new Date(), removedBy: owner.sub, finishedAt: null } })
+ }
+
+ it('is finished before a Workspace-only re-invite brings the person back, so the old private Swarm stays closed to them', async () => {
+ const workspaceId = await workspace('Revival')
+ const privateTab = await create(owner, 'Private work', workspaceId)
+ await invite(privateTab, member)
+ const operationId = randomUUID(), command = { type: 'message.send', conversationId: 'lead', text: 'before', replyTo: null, recipientIds: [] }
+ expect((await call('POST', `/api/super-tabs/${privateTab}/commands`, member, { operationId, command })).statusCode).toBe(200)
+ await failedRemoval(workspaceId, member)
+
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, owner, { email: member.email, role: 'member' })).statusCode).toBe(200)
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, member, {})).statusCode).toBe(200)
+ expect((await workspacesOf(member)).map(o => o.id)).toContain(workspaceId)
+ expect(await swarmPeople(privateTab)).not.toContain(member.sub)
+ expect((await call('GET', `/api/super-tabs/${privateTab}/parts`, member)).statusCode).toBe(403)
+ expect((await call('POST', `/api/super-tabs/${privateTab}/commands`, member, { operationId, command })).statusCode).toBe(403)
+ })
+
+ it('keeps the person out while the earlier removal cannot finish', async () => {
+ const workspaceId = await workspace('Stuck')
+ const tab = await create(owner, 'Stuck work', workspaceId), elsewhere = await create(owner, 'Healthy work', workspaceId)
+ await invite(tab, member)
+ await failedRemoval(workspaceId, member)
+ // The Swarm cannot be loaded for now, so leaving it fails again.
+ await db.superTab.update({ where: { id: tab }, data: { format: 1 } })
+ try {
+ expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, owner, { email: member.email, role: 'member' })).statusCode).toBe(200)
+ const accepted = await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, member, {})
+ expect(accepted.statusCode).toBe(409)
+ expect((await workspacesOf(member)).map(o => o.id)).not.toContain(workspaceId)
+ // Nor does a Swarm invitation make them a guest of the Workspace meanwhile.
+ const invitation = await run(elsewhere, { type: 'invite.create', email: member.email, role: 'collaborator', conversationId: 'lead' } as Command)
+ const viaSwarm = await call('POST', `/api/super-tabs/${elsewhere}/commands`, member,
+ { operationId: randomUUID(), command: { type: 'invite.accept', inviteId: invitation.result.inviteId } })
+ expect(viaSwarm.statusCode).toBe(409)
+ } finally { await db.superTab.update({ where: { id: tab }, data: { format: 2 } }) }
+ })
+})
+
+describe('the sweep of unfinished removals', () => {
+ it('reaches every open removal, however many, including one whose first try failed', async () => {
+ const workspaceId = await workspace('Many removals')
+ const tab = await create(owner, 'Last one', workspaceId)
+ await invite(tab, member)
+ const removedAt = new Date(Date.now() - 60_000)
+ await db.swarmWorkspaceRemoval.createMany({ data: Array.from({ length: 500 }, (_, i) => ({ id: `${workspaceId}:filler-${i}:g`, workspaceId,
+ userId: `filler-${i}`, email: `filler-${i}@example.com`, generation: 'g', autonomousEnv: 'prod', removedAt, removedBy: owner.sub, finishedAt: null })) })
+ const row = await db.swarmWorkspaceMember.findUniqueOrThrow({ where: { id: `${workspaceId}:${member.sub}` } })
+ await db.swarmWorkspaceMember.update({ where: { id: row.id }, data: { removedAt: new Date() } })
+ await db.swarmWorkspaceRemoval.create({ data: { id: `${row.id}:${row.generation}`, workspaceId, userId: member.sub, email: member.email,
+ generation: row.generation, autonomousEnv: 'prod', removedAt: new Date(), removedBy: owner.sub, finishedAt: null } })
+
+ let failOnce = true
+ const leaves: string[] = []
+ const workspaces = new SwarmWorkspaces(db, { transaction: body => db.$transaction(body), now: Date.now, leave: async (person, tabId, operationId) => {
+ if (tabId !== tab) return store.workspaces['deps'].leave(person, tabId, operationId)
+ leaves.push(`${person.sub}:${tabId}`)
+ if (failOnce) { failOnce = false; throw new Error('the Swarm was busy') }
+ return store.workspaces['deps'].leave(person, tabId, operationId)
+ } })
+ expect(await workspaces.finishRemovals()).toBeGreaterThanOrEqual(1)
+ expect(await workspaces.finishRemovals()).toBe(0)
+ expect(leaves).toEqual([`${member.sub}:${tab}`, `${member.sub}:${tab}`])
+ expect(await swarmPeople(tab)).not.toContain(member.sub)
+ expect(await db.swarmWorkspaceRemoval.count({ where: { workspaceId, finishedAt: null } })).toBe(0)
+ })
+})
+
+describe('who may invite people to a Workspace\'s Swarm', () => {
+ it('lets the Swarm\'s owner and the Workspace\'s owners, admins and members in it invite, never a guest; revoking is for owners and admins', async () => {
+ const workspaceId = await workspace('Inviting')
+ const tab = await create(owner, 'Invites', workspaceId)
+ for (const who of [admin, member, peer]) await invite(tab, who)
+ const inviteAs = async (who: AuthUser, email: string) => call('POST', `/api/super-tabs/${tab}/commands`, who,
+ { operationId: randomUUID(), command: { type: 'invite.create', email, role: 'collaborator', conversationId: 'lead' } })
+ for (const [who, email] of [[owner, '[email protected]'], [admin, '[email protected]'], [member, '[email protected]']] as const) {
+ const reply = await inviteAs(who, email)
+ expect(reply.statusCode, who.email).toBe(200)
+ }
+ const refused = await inviteAs(peer, '[email protected]')
+ expect(refused.statusCode).toBe(403)
+ const inviteId = (await inviteAs(member, '[email protected]')).json().data.result.inviteId as string
+ const revokeAs = (who: AuthUser) => call('POST', `/api/super-tabs/${tab}/commands`, who,
+ { operationId: randomUUID(), command: { type: 'invite.revoke', inviteId } })
+ expect((await revokeAs(member)).statusCode).toBe(403)
+ expect((await revokeAs(admin)).statusCode).toBe(200)
+ })
+})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 05f4cce1c..fd07581b6 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -1432,6 +1432,27 @@ describe('Super Tabs on a real Mongo replica set', () => {
await run(tab, { type: 'project.delete', projectId: other })
expect(await db.superTabRoleText.count({ where: { tabId: tab, projectId: other } })).toBe(0)
})
+ it('serves no role text once the reader, or the hosted agent\'s contributor, left the Swarm\'s Workspace, before that removal reaches the Swarm', async () => {
+ const { tab } = await fixture()
+ await invite(tab)
+ await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(), name: 'Worker', configuration: config, lead: false })
+ await run(tab, { type: 'project.roles.create', projectId: 'lead', roles: [{ id: 'lead', name: 'Product Manager', kind: 'lead' as const, text: 'LEAD-TEXT' },
+ { id: 'dev', name: 'Engineer', kind: 'builder' as const, text: 'DEV-TEXT' }] })
+ await run(tab, { type: 'project.skills', projectId: 'lead', mode: 'custom' })
+ const text = (user: AuthUser) => app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/projects/lead/roles/dev`, headers: { authorization: `Bearer ${user.sub}` } })
+ expect((await text(owner)).statusCode).toBe(200)
+ expect((await text(host)).statusCode).toBe(200)
+ // The owner, who is the project's owner and the Worker's contributor, is marked removed as a removal leaves it before its cleanup.
+ const row = await db.superTab.findUniqueOrThrow({ where: { id: tab } })
+ await db.swarmWorkspaceMember.update({ where: { id: `${row.workspaceId}:${owner.sub}` }, data: { removedAt: new Date() } })
+ try {
+ for (const user of [owner, host]) {
+ const answer = await text(user)
+ expect(answer.statusCode, user.email).not.toBe(200)
+ expect(answer.body).not.toContain('DEV-TEXT')
+ }
+ } finally { await db.swarmWorkspaceMember.update({ where: { id: `${row.workspaceId}:${owner.sub}` }, data: { removedAt: null } }) }
+ })
it('closes the replying agent\'s own deliveries of a message as answered, and nobody else\'s', async () => {
const { tab, lead } = await fixture()
const helper = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 654fcc427..c08377841 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1009,9 +1009,12 @@ model SuperTab {
format Int @default(1)
migratedAt DateTime?
legacyState Json?
+ /// The Workspace (SwarmWorkspace) it belongs to, also on its head part. Null only on a Swarm from before Workspaces, until migrated.
+ workspaceId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ @@index([autonomousEnv, workspaceId])
@@index([autonomousEnv, memberIds])
@@index([autonomousEnv, invitedEmails])
@@index([autonomousEnv, machineIds])
@@ -1323,6 +1326,72 @@ model SuperTabTerminalRequest {
// (`deleted`) until `purgeAt`, so readers learn it is gone. `data` keeps the record's shape from `SuperTab.state`.
/// The Swarm's scalars and settings: projects (without progress), rules, invitations, sharing, routing, Local models.
+/// A Workspace: Swarms and the people who may be in them (docs/plans/2026-10-27-swarm-workspaces.md). Not the Harness Team
+/// account. It never grants reading a Swarm: that needs the Swarm's own membership too.
+model SwarmWorkspace {
+ id String @id @map("_id")
+ autonomousEnv String
+ name String
+ ownerId String
+ revision Int @default(0)
+ createdAt DateTime @default(now())
+ deletedAt DateTime?
+ purgeAt DateTime?
+}
+
+/// One person of a Workspace. A removal keeps the row with `removedAt` until it is purged; a rejoin writes a new generation.
+model SwarmWorkspaceMember {
+ /// `workspaceId:userId`
+ id String @id @map("_id")
+ workspaceId String
+ userId String
+ email String
+ role String
+ generation String
+ version Int @default(1)
+ addedBy String
+ addedAt DateTime @default(now())
+ removedAt DateTime?
+ removedBy String?
+ purgeAt DateTime?
+
+ @@index([workspaceId, removedAt])
+ @@index([userId, removedAt])
+}
+
+/// One removal of one Workspace membership, open until the person has left every Swarm of the Workspace. While one is open the
+/// person cannot be brought back into the Workspace; the hourly sweep finishes them in order (superTabs/workspaceStore.ts).
+model SwarmWorkspaceRemoval {
+ /// `workspaceId:userId:generation`: the membership generation that was removed.
+ id String @id @map("_id")
+ workspaceId String
+ userId String
+ email String
+ generation String
+ autonomousEnv String
+ removedAt DateTime
+ removedBy String
+ finishedAt DateTime?
+ purgeAt DateTime?
+
+ @@index([finishedAt, id])
+ @@index([workspaceId, userId, finishedAt])
+}
+
+/// An invitation to a Workspace, by email; deleted when accepted or revoked, purged when it expires.
+model SwarmWorkspaceInvitation {
+ /// `workspaceId:email`
+ id String @id @map("_id")
+ workspaceId String
+ email String
+ role String
+ invitedBy String
+ expiresAt DateTime
+
+ @@index([email, expiresAt])
+ @@index([workspaceId])
+}
+
model SwarmHead {
id String @id @map("_id")
tabId String
diff --git a/backend/scripts/swarm-workspaces/migrate.ts b/backend/scripts/swarm-workspaces/migrate.ts
new file mode 100644
index 000000000..d385a0461
--- /dev/null
+++ b/backend/scripts/swarm-workspaces/migrate.ts
@@ -0,0 +1,27 @@
+/**
+ * Puts today's Swarms into Workspaces, or takes the Workspaces away again (src/superTabs/migration/workspaces.ts,
+ * docs/plans/2026-10-27-swarm-workspaces.md). A dry run unless --apply: it prints what it would do and the anomalies to read
+ * first (owners missing from their Swarms, people in several Workspaces, machines that would serve two Workspaces). Production
+ * only with the owner's go, after the backend that knows Workspaces is deployed; turn on SWARM_WORKSPACES_REQUIRED only afterwards.
+ *
+ * DATABASE_URL=… node --import tsx scripts/swarm-workspaces/migrate.ts [--apply]
+ * DATABASE_URL=… node --import tsx scripts/swarm-workspaces/migrate.ts --rollback [--apply]
+ */
+import { PrismaClient } from '@prisma/client'
+import { migrateWorkspaces, rollbackWorkspaces } from '../../src/superTabs/migration/workspaces.js'
+
+const args = new Set(process.argv.slice(2))
+const unknown = [...args].filter(arg => !['--apply', '--rollback'].includes(arg))
+if (unknown.length || !process.env.DATABASE_URL) {
+ console.error('Usage: DATABASE_URL=… node --import tsx scripts/swarm-workspaces/migrate.ts [--rollback] [--apply]')
+ process.exit(2)
+}
+const db = new PrismaClient()
+try {
+ const apply = args.has('--apply')
+ const report = args.has('--rollback') ? await rollbackWorkspaces(db, { apply }) : await migrateWorkspaces(db, { apply })
+ console.log(JSON.stringify(report, null, 2))
+ if (report.failed.length) process.exitCode = 1
+} finally {
+ await db.$disconnect()
+}
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 20c4c7da8..152523aca 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -22,12 +22,27 @@ import { logger } from '../utils/logger.js'
import { SwarmReads } from '../superTabs/read/service.js'
import { HostReads } from '../superTabs/read/host.js'
import { UPDATE_REQUIRED } from '../superTabs/read/contract.js'
+import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const tabParams = z.object({ tabId: id })
const agentQuery = z.object({ asAgentId: id.optional() }).strict()
-const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160), projectVisibility: z.enum(['public', 'private']).optional() }).strict()
+const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160), projectVisibility: z.enum(['public', 'private']).optional(),
+ workspaceId: id.optional() }).strict()
const operation = operationSchema.extend({ asAgentId: id.optional() })
+// Workspaces (superTabs/workspaceStore.ts). A Team session (lib/teamSession.ts) never acts on a Workspace: only the signed-in person does.
+const workspaceParams = z.object({ workspaceId: id })
+const workspaceMemberParams = z.object({ workspaceId: id, userId: id })
+const workspaceName = z.string().trim().min(1).max(160)
+const workspaceCreate = z.object({ operationId: id, name: workspaceName }).strict()
+const workspaceRename = z.object({ name: workspaceName }).strict()
+const workspaceInvite = z.object({ email: z.email().max(320), role: z.enum(['admin', 'member', 'guest']) }).strict()
+const workspaceRole = z.object({ role: z.enum(['admin', 'member', 'guest']) }).strict()
+const workspaceTransfer = z.object({ userId: id }).strict()
+const workspaceVisibility = z.object({ visibility: z.enum(['invite-only', 'workspace']) }).strict()
+const workspaceJoin = z.object({ operationId: id }).strict()
+const personOnly = (user: AuthUser) => { if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403) }
const listQuery = z.object({ after: id.optional() }).strict()
const cursor = z.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/)
const changesQuery = agentQuery.extend({ cursor })
@@ -150,7 +165,37 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Querystring: z.infer<typeof listQuery> }>('/api/super-tabs/list', { preHandler: validateQuery(listQuery) },
(req, reply) => respond(reply, () => reads.list(req.user!, req.query.after)))
app.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },
- (req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility)))
+ (req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility, req.body.workspaceId)))
+ // Workspaces (docs/plans/2026-10-27-swarm-workspaces.md): the person's Workspaces and the Swarms they may see in each.
+ app.get('/api/super-tabs/workspaces', (req, reply) => respond(reply, () => store.workspaceList(req.user!)))
+ app.post<{ Body: z.infer<typeof workspaceCreate> }>('/api/super-tabs/workspaces', { preHandler: validateBody(workspaceCreate) },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.create(req.user!, req.body.operationId, req.body.name) }))
+ app.get('/api/super-tabs/workspace-invitations', (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.invitationsFor(req.user!) }))
+ app.post<{ Params: z.infer<typeof workspaceParams>; Body: z.infer<typeof workspaceRename> }>('/api/super-tabs/workspaces/:workspaceId',
+ { preHandler: [validateParams(workspaceParams), validateBody(workspaceRename)] },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.rename(req.user!, req.params.workspaceId, req.body.name) }))
+ app.get<{ Params: z.infer<typeof workspaceParams> }>('/api/super-tabs/workspaces/:workspaceId/members', { preHandler: validateParams(workspaceParams) },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.members(req.user!, req.params.workspaceId) }))
+ app.post<{ Params: z.infer<typeof workspaceParams>; Body: z.infer<typeof workspaceInvite> }>('/api/super-tabs/workspaces/:workspaceId/invitations',
+ { preHandler: [validateParams(workspaceParams), validateBody(workspaceInvite)] },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.invite(req.user!, req.params.workspaceId, req.body.email, req.body.role) }))
+ app.post<{ Params: z.infer<typeof workspaceParams> }>('/api/super-tabs/workspaces/:workspaceId/accept', { preHandler: validateParams(workspaceParams) },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.accept(req.user!, req.params.workspaceId) }))
+ app.post<{ Params: z.infer<typeof workspaceMemberParams>; Body: z.infer<typeof workspaceRole> }>('/api/super-tabs/workspaces/:workspaceId/members/:userId',
+ { preHandler: [validateParams(workspaceMemberParams), validateBody(workspaceRole)] },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.setRole(req.user!, req.params.workspaceId, req.params.userId, req.body.role) }))
+ // A POST, not a DELETE: Desktop reaches the backend through the daemon, which forwards only GET and POST (cli superTabs/service.ts).
+ app.post<{ Params: z.infer<typeof workspaceMemberParams> }>('/api/super-tabs/workspaces/:workspaceId/members/:userId/remove', { preHandler: validateParams(workspaceMemberParams) },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.remove(req.user!, req.params.workspaceId, req.params.userId) }))
+ app.post<{ Params: z.infer<typeof workspaceParams>; Body: z.infer<typeof workspaceTransfer> }>('/api/super-tabs/workspaces/:workspaceId/transfer',
+ { preHandler: [validateParams(workspaceParams), validateBody(workspaceTransfer)] },
+ (req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.transfer(req.user!, req.params.workspaceId, req.body.userId) }))
+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof workspaceVisibility> }>('/api/super-tabs/:tabId/workspace-visibility',
+ { preHandler: [validateParams(tabParams), validateBody(workspaceVisibility)] },
+ (req, reply) => respond(reply, () => store.setWorkspaceVisibility(req.user!, req.params.tabId, req.body.visibility)))
+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof workspaceJoin> }>('/api/super-tabs/:tabId/workspace-join',
+ { preHandler: [validateParams(tabParams), validateBody(workspaceJoin)] },
+ (req, reply) => respond(reply, () => store.workspaceJoin(req.user!, req.params.tabId, req.body.operationId)))
app.get('/api/super-tabs/invitations', (req, reply) => respond(reply, () => store.invitations(req.user!)))
app.get<{ Params: z.infer<typeof tabParams> }>('/api/super-tabs/:tabId/sharing',
{ preHandler: validateParams(tabParams) },
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index c350dd077..b5a0b3266 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -18,6 +18,7 @@ import { ABANDONED, failureNotice, MACHINE_REMOVED } from './startFailure.js'
import { digestStartsAfter, knownTimeZone } from './digest.js'
import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'
import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'
+import { workspaceCan, type WorkspaceRole } from './workspaces.js'
import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAnswer, recordAsked, recordMerged, recordReview, recordRun, recordStatus } from './leaderboard/record.js'
import { WEEK_MS } from './leaderboard/week.js'
import { react, reactionSchema, type ReactionTarget } from './reactions.js'
@@ -274,6 +275,10 @@ export interface CommandContext {
/** 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[]
+ /** The person's role in the Swarm's Workspace, read by the store for invitations (workspaces.ts); absent outside a Workspace. */
+ workspaceRole?: WorkspaceRole
+ /** Machines of this Swarm also contributed to a Swarm of another Workspace (store.ts otherWorkspaceMachines). */
+ otherWorkspaceMachines?: string[]
/** No Harness GitHub App on this server (routes/superTabs.ts): a Mac's Harness Team account has no git login to fetch or
* push with, so starts on the Mac stay with the Mac, as before team accounts (machines.ts teamMachineFor). */
teamAccountsIdle?: boolean
@@ -420,6 +425,14 @@ export function postable(state: SuperTabState, actor: Actor, conversationId: str
function owner(state: SuperTabState, actor: Actor): void {
if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can manage invitations.', 403)
}
+/** Inviting to a Workspace's Swarm (design, Roles): its owner, or anyone in it whose Workspace role may invite to a Swarm they are
+ * in — owners, admins and members, never guests. Revoking: its owner, or the Workspace's owners and admins. A Swarm from
+ * before Workspaces keeps invitations to its owner. */
+function inviter(state: SuperTabState, actor: Actor, context: Partial<CommandContext>, action: 'swarm.invite' | 'swarm.manage'): void {
+ if (actor.kind === 'person' && actor.userId === state.ownerId) return
+ if (state.workspaceId && actor.kind === 'person' && context.workspaceRole && workspaceCan(context.workspaceRole, action)) return
+ fail('OWNER_REQUIRED', 'Your role cannot manage invitations to this Swarm.', 403)
+}
/** A requester is a member who can read the project the work is in. */
function requester(state: SuperTabState, project: SwarmProject, personId: string): string {
const member = person(state, personId)
@@ -601,7 +614,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// A new agent on a Mac for a teammate's project runs in the Mac's Harness Team account (machines.ts teamStartRequest).
const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines)
const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starter
- return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines)
+ return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines, context.otherWorkspaceMachines)
}
/** 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 } = {}) => {
@@ -1224,9 +1237,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
// A teammate's project started on a Mac runs in that Mac's Harness Team account, never as its owner (machines.ts).
const request = teamStartRequest(state, command.request, home, context.teamAccountsIdle, context.teamMachines)
- const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines)
+ const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
- if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines)
+ if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
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, harnessId: null, dispatched: false, error: null })
@@ -1269,7 +1282,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, context.teamMachines)
+ admitMachineStart(state, start.request, context.now, start, context.teamMachines, context.otherWorkspaceMachines)
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
start.dispatchedAt = context.now
@@ -1466,7 +1479,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('AUDIENCE_LEAD_ONLY', 'A private conversation holds only the Lead among agents.', 403)
}
// 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)
+ if (reviewer) requireTeamWork(state, member.machineId, member.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
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.
@@ -1480,7 +1493,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
}
case 'invite.create': {
- owner(state, actor)
+ inviter(state, actor, context, 'swarm.invite')
const landing = inviteLanding(state, command.conversationId) ?? fail('NO_PROJECT', 'Create a project before inviting people.')
const email = command.email.trim().toLowerCase()
if (state.people.some(p => p.email === email)) fail('ALREADY_MEMBER', 'This person is already in the Super Tab.')
@@ -1491,7 +1504,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
}
case 'invite.revoke':
- owner(state, actor)
+ inviter(state, actor, context, 'swarm.manage')
state.invitations = state.invitations.filter(i => i.id !== command.inviteId)
break
case 'member.status':
@@ -1686,7 +1699,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
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)
+ requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
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 1399ca5cb..78f97c543 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,5 +1,6 @@
import { z } from 'zod'
import { activeWork, fail, person, type Actor, type Agent, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
+import { WORKSPACE_LABEL } from './workspaces.js'
import { agentProjectId, groupProject, ledProject, projectsOf, type SwarmProject } from './projects.js'
import { conversation } from './model.js'
@@ -142,9 +143,10 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M
}
export type TeamWorkCode = 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
+ | 'MACHINE_IN_OTHER_WORKSPACE'
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']
+export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE']
/** What each item of the privacy check (cli/src/team/privacy.ts) could reach when it failed. */
const PRIVACY_ITEMS: Record<string, string> = {
@@ -175,9 +177,12 @@ export function teamAccountRequired(state?: Pick<SuperTabState, 'ownerId' | 'peo
/** 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. `required`: whether the Swarm it is
* in needs a team account on every machine ([teamAccountRequired] of that Swarm). */
-export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, required = teamAccountRequired()): TeamWorkRefusal | null {
+/** `otherWorkspace`: the machine is contributed to a Swarm of another Workspace too (store.ts otherWorkspaceMachines). Its Team account
+ * runs every teammate's work as one macOS user, so it serves one Workspace's teammates at a time (swarm-workspaces design). */
+export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, required = teamAccountRequired(), otherWorkspace = false): TeamWorkRefusal | null {
const reading = pool.observation, name = pool.name
if (!teamRow && reading?.sessionKind !== 'team' && !required) return null
+ if (otherWorkspace) return { code: 'MACHINE_IN_OTHER_WORKSPACE', reason: `The Harness Team account on ${name} also serves another ${WORKSPACE_LABEL}'s Swarms, ${ONLY_OWN} here.` }
if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {
// A Mac's team account goes by its Mac's name ("One machine"), and the Mac itself may well be online.
return { code: 'MACHINE_OFFLINE', reason: pool.hostMachineId
@@ -207,7 +212,7 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =
* 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 {
+ teamMachines: readonly string[] = [], otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {
if (project.ownerId === contributorId) return null
const pool = state.machines?.find(m => m.machineId === machineId)
if (!pool) {
@@ -215,7 +220,7 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contribut
if (!teamAccountRequired(state)) return null
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), teamAccountRequired(state))
+ return teamWorkRefusal(pool, now, teamMachines.includes(machineId), teamAccountRequired(state), otherWorkspaceMachines.includes(machineId))
}
// ── One machine: a Mac and its Harness Team account ─────────────────────────────────────────────────────────────────
@@ -421,7 +426,8 @@ export function localModelAllowed(state: SuperTabState, request: AgentStartReque
/** `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[] = []) {
+export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart, teamMachines: readonly string[] = [],
+ otherWorkspaceMachines: 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.')
@@ -430,7 +436,7 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
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)
+ requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)
const cwd = projectFolder(pool, project)
// Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
// setting can be a path or a name of the caller's own.
diff --git a/backend/src/superTabs/migration/workspaces.ts b/backend/src/superTabs/migration/workspaces.ts
new file mode 100644
index 000000000..67809d6d0
--- /dev/null
+++ b/backend/src/superTabs/migration/workspaces.ts
@@ -0,0 +1,161 @@
+/**
+ * Today's Swarms into Workspaces, and back (docs/plans/2026-10-27-swarm-workspaces.md, Migration and rollback). Never run by the
+ * server: `scripts/swarm-workspaces/migrate.ts` runs it, a dry run unless `--apply`, and on production only with the owner's go.
+ *
+ * Each owner's Swarms go into one Workspace of theirs (the id their next new Swarm would make, workspaceStore.ts personalWorkspaceId),
+ * named after their first Swarm. The owner owns it; everyone else in those Swarms becomes a guest, so nobody reads more
+ * than before. Only Swarms in parts and without a Workspace are touched; a second run finds nothing to do.
+ *
+ * The undo takes every Workspace away: the rows' and heads' Workspace, and the Workspace collections. Swarm people stay as they are,
+ * so each Swarm reads by its own membership again, as the previous release does.
+ */
+import type { Prisma, PrismaClient } from '@prisma/client'
+import { clock, guardedWrite, PartConflict } from '../parts/index.js'
+import { addMember, personalWorkspaceId } from '../workspaceStore.js'
+import type { Person } from '../model.js'
+
+type Transaction = Prisma.TransactionClient
+const TRANSACTION = { maxWait: 5_000, timeout: 60_000 }
+
+export interface WorkspaceMigrationReport {
+ apply: boolean
+ /** Swarms put (or, in a dry run, to be put) into a Workspace. */
+ swarms: number
+ workspacesCreated: number
+ guestsAdded: number
+ /** Swarms not in parts yet: left alone, they get their Workspace when they are opened and migrated, then rerun. */
+ skipped: string[]
+ failed: Array<{ tabId: string; error: string }>
+ anomalies: {
+ /** A Swarm whose owner is not among its people. */
+ ownerMissing: string[]
+ /** People in Swarms of several owners: a guest of each Workspace, which shows nothing new. */
+ peopleInSeveralWorkspaces: Array<{ userId: string; workspaceCount: number }>
+ /** Machines contributed to Swarms of two owners: afterwards their Harness Team account takes teammates' work in neither. */
+ machinesInTwoWorkspaces: Array<{ machineId: string; tabIds: string[] }>
+ }
+}
+
+interface Pending { id: string; autonomousEnv: string; ownerId: string; createdAt: Date; name: string; people: Person[]; headVersion: number;
+ head: Prisma.JsonObject; headFields: { groupCounter: number; visibilityEpoch: number; sequenceBase: number } }
+
+async function pendingSwarms(db: PrismaClient, report: WorkspaceMigrationReport): Promise<Pending[]> {
+ const rows = (await db.superTab.findMany({ select: { id: true, autonomousEnv: true, ownerId: true, createdAt: true, format: true, workspaceId: true } }))
+ .filter(r => !r.workspaceId)
+ report.skipped = rows.filter(r => r.format !== 2).map(r => r.id)
+ const split = rows.filter(r => r.format === 2)
+ const heads = new Map((await db.swarmHead.findMany({ where: { id: { in: split.map(r => `${r.id}:head`) } } })).map(h => [h.tabId, h]))
+ const members = await db.swarmMember.findMany({ where: { tabId: { in: split.map(r => r.id) }, deleted: false } })
+ return split.flatMap(row => {
+ const head = heads.get(row.id)
+ if (!head) { report.failed.push({ tabId: row.id, error: 'it has no head part' }); return [] }
+ const people = members.filter(m => m.tabId === row.id).map(m => m.data as unknown as Person)
+ if (!people.some(p => p.id === row.ownerId)) report.anomalies.ownerMissing.push(row.id)
+ const data = head.data as Prisma.JsonObject
+ return [{ id: row.id, autonomousEnv: row.autonomousEnv, ownerId: row.ownerId, createdAt: row.createdAt, name: String(data.name ?? ''), people,
+ headVersion: head.version, head: data, headFields: { groupCounter: head.groupCounter, visibilityEpoch: head.visibilityEpoch, sequenceBase: head.sequenceBase } }]
+ })
+}
+
+/** Writes the Workspace on a Swarm's head (a guarded write, so a command in between wins and the Swarm is retried) and row. */
+async function stampSwarm(tx: Transaction, tabId: string, seen: number, head: Prisma.JsonObject, headFields: Pending['headFields'], workspaceId: string | null) {
+ const { workspaceId: _old, workspaceVisibility: _visibility, ...rest } = head
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'head', key: 'head', seen, data: (workspaceId ? { ...rest, workspaceId } : rest) as never, head: headFields }, clock.next())
+ const row = await tx.superTab.findUniqueOrThrow({ where: { id: tabId } })
+ const updated = await tx.superTab.updateMany({ where: { id: tabId, revision: row.revision }, data: { revision: row.revision + 1, workspaceId } })
+ if (!updated.count) throw new PartConflict('head', 'index')
+}
+
+export async function migrateWorkspaces(db: PrismaClient, opts: { apply: boolean }): Promise<WorkspaceMigrationReport> {
+ const report: WorkspaceMigrationReport = { apply: opts.apply, swarms: 0, workspacesCreated: 0, guestsAdded: 0, skipped: [], failed: [],
+ anomalies: { ownerMissing: [], peopleInSeveralWorkspaces: [], machinesInTwoWorkspaces: [] } }
+ const pending = await pendingSwarms(db, report)
+ const owners = new Map<string, Pending[]>()
+ for (const swarm of pending.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())) {
+ const key = personalWorkspaceId(swarm.autonomousEnv, swarm.ownerId)
+ owners.set(key, [...owners.get(key) ?? [], swarm])
+ }
+
+ // What the migration would make: each owner's Workspace, read against the Workspaces that already exist.
+ const workspacesOf = new Map<string, Set<string>>()
+ for (const [workspaceId, swarms] of owners) for (const p of swarms.flatMap(s => s.people)) workspacesOf.set(p.id, (workspacesOf.get(p.id) ?? new Set()).add(workspaceId))
+ report.anomalies.peopleInSeveralWorkspaces = [...workspacesOf].filter(([, workspaces]) => workspaces.size > 1).map(([userId, workspaces]) => ({ userId, workspaceCount: workspaces.size }))
+ report.anomalies.machinesInTwoWorkspaces = await machinesInTwoWorkspaces(db, owners)
+
+ for (const [workspaceId, swarms] of owners) {
+ const first = swarms[0]!
+ const exists = !!await db.swarmWorkspace.findUnique({ where: { id: workspaceId } })
+ if (!exists) report.workspacesCreated++
+ const guests = new Map(swarms.flatMap(s => s.people).filter(p => p.id !== first.ownerId).map(p => [p.id, p]))
+ for (const guest of guests.values()) {
+ const current = await db.swarmWorkspaceMember.findUnique({ where: { id: `${workspaceId}:${guest.id}` } })
+ if (!current || current.removedAt) report.guestsAdded++
+ }
+ report.swarms += swarms.length
+ if (!opts.apply) continue
+ try {
+ await db.$transaction(async tx => {
+ if (!await tx.swarmWorkspace.findUnique({ where: { id: workspaceId } })) {
+ await tx.swarmWorkspace.create({ data: { id: workspaceId, autonomousEnv: first.autonomousEnv, name: first.name || 'Workspace', ownerId: first.ownerId, deletedAt: null, purgeAt: null } })
+ }
+ const ownerEmail = first.people.find(p => p.id === first.ownerId)?.email
+ ?? (await tx.user.findUnique({ where: { id: first.ownerId }, select: { email: true } }))?.email ?? ''
+ await addMember(tx, workspaceId, { id: first.ownerId, email: ownerEmail }, 'owner', first.ownerId, `migration:${workspaceId}`)
+ for (const guest of guests.values()) await addMember(tx, workspaceId, guest, 'guest', first.ownerId, `migration:${workspaceId}:${guest.id}`)
+ }, TRANSACTION)
+ } catch (error) {
+ for (const swarm of swarms) report.failed.push({ tabId: swarm.id, error: error instanceof Error ? error.message : String(error) })
+ continue
+ }
+ for (const swarm of swarms) {
+ try {
+ await db.$transaction(tx => stampSwarm(tx, swarm.id, swarm.headVersion, swarm.head, swarm.headFields, workspaceId), TRANSACTION)
+ } catch (error) {
+ report.failed.push({ tabId: swarm.id, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ }
+ return report
+}
+
+/** Machines contributed to Swarms that will be in different Workspaces, with the Workspaces that exist already taken into account. */
+async function machinesInTwoWorkspaces(db: PrismaClient, owners: Map<string, Pending[]>): Promise<WorkspaceMigrationReport['anomalies']['machinesInTwoWorkspaces']> {
+ const pools = await db.swarmMachine.findMany({ where: { deleted: false, contributed: true }, select: { tabId: true, machineId: true } })
+ const workspaceOf = new Map<string, string>()
+ for (const [workspaceId, swarms] of owners) for (const swarm of swarms) workspaceOf.set(swarm.id, workspaceId)
+ for (const row of await db.superTab.findMany({ where: { id: { in: pools.map(p => p.tabId) } }, select: { id: true, workspaceId: true } })) {
+ if (row.workspaceId) workspaceOf.set(row.id, row.workspaceId)
+ }
+ const byMachine = new Map<string, string[]>()
+ for (const pool of pools) byMachine.set(pool.machineId, [...byMachine.get(pool.machineId) ?? [], pool.tabId])
+ return [...byMachine].filter(([, tabIds]) => new Set(tabIds.map(t => workspaceOf.get(t)).filter(Boolean)).size > 1)
+ .map(([machineId, tabIds]) => ({ machineId, tabIds: [...tabIds].sort() }))
+}
+
+export interface WorkspaceRollbackReport { apply: boolean; swarms: number; workspaces: number; failed: Array<{ tabId: string; error: string }> }
+
+/** Takes every Workspace away (see the top of this file). A dry run only counts. */
+export async function rollbackWorkspaces(db: PrismaClient, opts: { apply: boolean }): Promise<WorkspaceRollbackReport> {
+ const rows = await db.superTab.findMany({ where: { workspaceId: { not: null } }, select: { id: true } })
+ const report: WorkspaceRollbackReport = { apply: opts.apply, swarms: rows.length, workspaces: await db.swarmWorkspace.count(), failed: [] }
+ if (!opts.apply) return report
+ for (const row of rows) {
+ try {
+ await db.$transaction(async tx => {
+ const head = await tx.swarmHead.findUniqueOrThrow({ where: { id: `${row.id}:head` } })
+ await stampSwarm(tx, row.id, head.version, head.data as Prisma.JsonObject,
+ { groupCounter: head.groupCounter, visibilityEpoch: head.visibilityEpoch, sequenceBase: head.sequenceBase }, null)
+ }, TRANSACTION)
+ } catch (error) {
+ report.failed.push({ tabId: row.id, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ // The Workspaces go only once no Swarm names one, so a failed Swarm keeps the Workspace it still points at; rerun to finish.
+ if (!report.failed.length) {
+ await db.swarmWorkspaceInvitation.deleteMany({})
+ await db.swarmWorkspaceRemoval.deleteMany({})
+ await db.swarmWorkspaceMember.deleteMany({})
+ await db.swarmWorkspace.deleteMany({})
+ }
+ return report
+}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0bddb73cf..411797c0b 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -242,6 +242,10 @@ export interface SuperTabState {
/** Read-only, for a Lead's own reads (visibleState): the active work of the other projects it may know about. */
otherProjectsWork?: OtherProjectWork[]
ownerId: string
+ /** The Workspace it belongs to (workspaceStore.ts); absent on a Swarm from before Workspaces until the migration gives it one. */
+ workspaceId?: string
+ /** Who in the Workspace may find and join it by themselves: `workspace` lets members and up join; absent reads as invite-only. */
+ workspaceVisibility?: 'invite-only' | 'workspace'
environment: string
/** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */
routingPolicy?: import('./routingPolicy.js').RoutingOverride
diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.ts
index 16a21dabb..20c0afce1 100644
--- a/backend/src/superTabs/native.ts
+++ b/backend/src/superTabs/native.ts
@@ -37,6 +37,8 @@ interface Deps {
contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }): Promise<Grant>
/** The one machine a team session (lib/teamSession.ts) hosts for; null for any other sign-in. */
teamHost(tx: Transaction, user: AuthUser): Promise<string | null>
+ /** Refuses a person no longer in the Swarm's Workspace (workspaceStore.ts requireWorkspaceAccess). */
+ workspaceAccess(tx: Transaction, state: SuperTabState, userId: string): Promise<void>
}
const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
@@ -72,6 +74,7 @@ export class SuperTabNativeStore {
fail('NATIVE_CONTEXT_REVOKED', 'This terminal context no longer belongs to the current contribution.', 403)
}
await this.deps.agentGrant(tx, state, target)
+ await this.deps.workspaceAccess(tx, state, binding.operator.id)
// Read the person's current identity, rather than trusting a name supplied by
// a terminal client or reusing an old email after an account change.
const user = await tx.user.findUnique({ where: { id: operator.id }, select: { email: true, autonomousEnv: true } })
@@ -89,6 +92,7 @@ export class SuperTabNativeStore {
const request = openNativeSchema.parse(input)
return this.deps.transaction(async tx => {
const { state } = await this.deps.load(tx, user, tabId, [request.conversationId])
+ await this.deps.workspaceAccess(tx, state, user.sub)
const operator = author(state, { kind: 'person', userId: user.sub, email: user.email }, true)
const target = agent(state, request.agentId)
const group = readConversation(state, { kind: 'person', userId: user.sub, email: user.email }, request.conversationId)
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 41f5941a8..51a7152dd 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -24,7 +24,7 @@ export type GroupChange = LivePart<GroupView> | Tombstone | DormantStub
/** The head as a reader sees it: no sharing, overlap alerts, retired number or parked groups; projects, rules and
* invitations filtered (invitations only for the Swarm owner). */
export type HeadView = Pick<SuperTabState, 'version' | 'id' | 'name' | 'project' | 'projects' | 'leadsConversationId' | 'ownerId'
- | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels'>
+ | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility'>
/** A member's avatar says only `{ kind: 'upload' }` for an upload: its link comes signed in `derived.avatars`. */
export type MemberView = Omit<Person, 'avatar'> & { avatar?: import('../profile.js').AvatarView }
/** The stored agent. Time-based and cross-part values (`downSince`, `limitedUntil`, an awaiting decision, the custom
@@ -131,7 +131,8 @@ export interface CommandReply {
/** GET /api/super-tabs/list[?after=] */
export interface SwarmList {
- tabs: Array<{ id: string; name: string; ownerId: string; paused: boolean; lastChangedAt: number | null }>
+ /** `workspaceId` names its Workspace (null before the migration); a Swarm whose Workspace the person left is not listed. */
+ tabs: Array<{ id: string; name: string; ownerId: string; workspaceId: string | null; paused: boolean; lastChangedAt: number | null }>
next: string | null
}
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 05f62b743..38af63dd5 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -13,6 +13,7 @@ import { migrateSwarm } from '../migration/migrate.js'
import * as parts from '../parts/index.js'
import type { SwarmParts } from '../parts/index.js'
import { canReadGroup, readProject } from '../projects.js'
+import { workspacesRequired } from '../workspaceStore.js'
import type { Leaderboard } from '../leaderboard/contract.js'
import { readableWeek, recentDormantGroups } from '../leaderboard/read.js'
import { LEDGER_WEEKS } from '../leaderboard/record.js'
@@ -127,8 +128,12 @@ export class SwarmReads {
async list(user: AuthUser, after?: string): Promise<SwarmList> {
if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },
- ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101, select: { id: true, ownerId: true, format: true } })
- const page = rows.slice(0, 100)
+ ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101, select: { id: true, ownerId: true, format: true, workspaceId: true } })
+ // A Swarm of a Workspace the person is no longer in is not theirs to list, even before their removal from it has run.
+ const workspaceIds = [...new Set(rows.flatMap(r => r.workspaceId ? [r.workspaceId] : []))]
+ const current = new Set((await this.db.swarmWorkspaceMember.findMany({ where: { workspaceId: { in: workspaceIds }, userId: user.sub, removedAt: null },
+ select: { workspaceId: true } })).map(m => m.workspaceId))
+ const page = rows.slice(0, 100).filter(r => r.workspaceId ? current.has(r.workspaceId) : !workspacesRequired())
// A Swarm not yet in parts is migrated when it is opened; until then the list names it from its old row.
const legacy = await this.db.superTab.findMany({ where: { id: { in: page.filter(r => r.format !== 2).map(r => r.id) } }, select: { id: true, state: true } })
const ids = page.filter(r => r.format === 2).map(r => r.id)
@@ -136,8 +141,8 @@ export class SwarmReads {
const [heads, newest] = await transaction(this.db, tx => Promise.all([parts.loadChanged(tx, ids, new Date(0), ['head']), parts.lastChangedAt(tx, ids)]))
return { tabs: page.map(row => {
const head = (heads.get(row.id)?.[0]?.data ?? legacy.find(l => l.id === row.id)?.state) as { name: string; paused: boolean }
- return { id: row.id, name: head.name, ownerId: row.ownerId, paused: head.paused, lastChangedAt: newest.get(row.id) ?? null }
- }), next: rows.length > 100 ? page.at(-1)!.id : null }
+ return { id: row.id, name: head.name, ownerId: row.ownerId, workspaceId: row.workspaceId, paused: head.paused, lastChangedAt: newest.get(row.id) ?? null }
+ }), next: rows.length > 100 ? rows[99]!.id : null }
}
/** Runs a read; a Swarm still in one row is migrated first, as a safety net for one the job did not see (design 6.1),
@@ -155,13 +160,14 @@ export class SwarmReads {
const loaded = await loader(tx, tabId, opts)
const state = parts.reassemble(loaded)
const actor = await this.store.actor(tx, user, state, asAgentId)
- const [teamMachines, counts, newest] = await Promise.all([
+ const [teamMachines, otherWorkspaceMachines, counts, newest] = await Promise.all([
state.machines?.length ? this.store.teamMachines(tx, state) : [],
+ state.machines?.length ? this.store.otherWorkspaceMachines(tx, state) : [],
actor.kind === 'person' ? Promise.all([mentionsWaiting(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor)]) : undefined,
parts.lastChangedAt(tx, [tabId]),
])
return { parts: loaded, actor, lastChangedAt: newest.get(tabId) ?? null,
- view: readerView(loaded, actor, t0, { teamMachines,
+ view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines,
...(counts ? { mentionsWaiting: counts[0], decisionsWaiting: counts[1].count, decisionsDigest: counts[1].digest } : {}) }) }
}
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 38cb9b406..b80a9741f 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -29,6 +29,8 @@ export interface ReaderView {
export interface ReadExtras {
/** Machines whose account row is a Harness Team account (store read helper). */
teamMachines: string[]
+ /** Machines also contributed to a Swarm of another Workspace (store.ts otherWorkspaceMachines). */
+ otherWorkspaceMachines?: string[]
/** A person's open mentions, counted by the store. */
mentionsWaiting?: number
/** A person's open decisions (decisions.ts). */
@@ -38,7 +40,7 @@ export interface ReadExtras {
}
const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',
- 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels'] as const
+ 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility'] as const
export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, data: T): LivePart<T> =>
({ key: part.key, version: part.version, changedAt: part.changedAt, data })
@@ -97,7 +99,8 @@ export const progressView = (data: NonNullable<SwarmParts['progress'][number]['d
function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now: number, extras: ReadExtras): Derived {
const machine = (pool: ContributedMachine) => {
const stored = state.machines!.find(m => m.machineId === pool.machineId)!
- const refusal = teamWorkRefusal(stored, now, extras.teamMachines.includes(pool.machineId), teamAccountRequired(state))
+ const refusal = teamWorkRefusal(stored, now, extras.teamMachines.includes(pool.machineId), teamAccountRequired(state),
+ !!extras.otherWorkspaceMachines?.includes(pool.machineId))
return [pool.machineId, { availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),
teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const } }] as const
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index f9e059af4..04bf4caf7 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -26,6 +26,8 @@ import { clock, insertParts, lastChangedAt, loadActive, reassemble, split, type
import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'
import { touchesFor } from './parts/touches.js'
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
+import { activeMember, addMember, hasWorkspaceAccess, listWorkspaces, memberId, WORKSPACE_ACCESS_REVOKED, workspaceForNewSwarm, requireWorkspaceAccess, requireWorkspaceRole, SwarmWorkspaces } from './workspaceStore.js'
+import { WORKSPACE_LABEL, type WorkspaceRole } from './workspaces.js'
import {
activeWork, actorKey, agent, agentOnly, agentRole, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
SuperTabError, isLeads, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type Conversation, type MessageDraft, type SuperTabState,
@@ -188,6 +190,7 @@ const routeDecisionOf = (command: Command): string | undefined => command.type =
export class SuperTabStore {
readonly native: SuperTabNativeStore
+ readonly workspaces: SwarmWorkspaces
/** The private avatar bucket, whose links member reads sign (read/service.ts); null when avatar uploads are off. */
get avatars(): AvatarStore | null { return this.attachments?.avatars ?? null }
constructor(readonly db: PrismaClient, readonly now: () => number = Date.now,
@@ -200,6 +203,13 @@ export class SuperTabStore {
agentGrant: (tx, state, target) => this.agentGrant(tx, state, target),
contribution: (tx, state, actor, command) => this.contribution(tx, state, actor, command),
teamHost: (tx, user) => this.teamHost(tx, user),
+ workspaceAccess: (tx, state, userId) => requireWorkspaceAccess(tx, state, userId),
+ })
+ this.workspaces = new SwarmWorkspaces(db, {
+ transaction: body => transaction(db, body),
+ leave: (person, tabId, operationId) => this.executeOnce(person, tabId, { operationId, command: { type: 'member.remove', userId: person.sub } },
+ undefined, undefined, true),
+ now,
})
}
@@ -270,6 +280,19 @@ export class SuperTabStore {
return rows.map(r => r.machineId)
}
+ /** This Swarm's contributed machines that are also contributed to a Swarm of another Workspace: their Harness Team account
+ * takes no teammate's work here (machines.ts teamWorkRefusal). One indexed read of the machines' parts, one of rows. */
+ async otherWorkspaceMachines(tx: Transaction, state: SuperTabState): Promise<string[]> {
+ const ids = (state.machines ?? []).map(m => m.machineId)
+ if (!state.workspaceId || !ids.length) return []
+ const elsewhere = await tx.swarmMachine.findMany({ where: { machineId: { in: ids }, deleted: false, contributed: true, tabId: { not: state.id } },
+ select: { tabId: true, machineId: true } })
+ if (!elsewhere.length) return []
+ const rows = await tx.superTab.findMany({ where: { id: { in: [...new Set(elsewhere.map(e => e.tabId))] } }, select: { id: true, workspaceId: true } })
+ const other = new Set(rows.filter(r => r.workspaceId && r.workspaceId !== state.workspaceId).map(r => r.id))
+ return [...new Set(elsewhere.filter(e => other.has(e.tabId)).map(e => e.machineId))]
+ }
+
private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }
async accountPolicy(user: AuthUser) {
@@ -376,11 +399,13 @@ export class SuperTabStore {
}
/** Shared with the read API (superTabs/read, design section 7.2). */
- async actor(tx: Transaction, user: AuthUser, state: SuperTabState, agentId?: string): Promise<Actor> {
+ /** `workspaceLeave` is a Workspace removal leaving this Swarm for the person (workspaceStore.ts SwarmWorkspaces.remove): past the Workspace check. */
+ async actor(tx: Transaction, user: AuthUser, state: SuperTabState, agentId?: string, workspaceLeave = false): Promise<Actor> {
const team = await this.teamHost(tx, user)
if (!agentId) {
// A team session never speaks or reads as the person.
if (team !== null) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ if (!workspaceLeave) await requireWorkspaceAccess(tx, state, user.sub)
return { kind: 'person', userId: user.sub, email: user.email }
}
const target = agent(state, agentId)
@@ -392,7 +417,10 @@ export class SuperTabStore {
}
/** Shared with the read API (superTabs/read, design section 7.2). */
+ /** Every path that serves an agent's host checks this, so it also holds the Workspace check: the agent acts for its
+ * contributor, who must still be in the Swarm's Workspace. Its host need not be, as it need not be in the Swarm. */
async agentGrant(tx: Transaction, state: SuperTabState, target: Agent): Promise<void> {
+ await requireWorkspaceAccess(tx, state, target.contributorId)
const machine = await tx.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId,
autonomousEnv: state.environment, ...machineAlive } })
if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
@@ -436,10 +464,10 @@ export class SuperTabStore {
return { machineOwnerId: machine.userId, contributorId, hostGrant, ...host }
}
- async create(user: AuthUser, operationId: string, name: string, projectVisibility?: ProjectVisibility) {
+ async create(user: AuthUser, operationId: string, name: string, projectVisibility?: ProjectVisibility, workspaceId?: string) {
this.personOnly(user)
const id = stableId('super-tab', user.autonomousEnv, user.sub, operationId)
- const requestHash = hash({ name, ...(projectVisibility ? { projectVisibility } : {}) })
+ const requestHash = hash({ name, ...(projectVisibility ? { projectVisibility } : {}), ...(workspaceId ? { workspaceId } : {}) })
return transaction(this.db, async tx => {
const prior = await tx.superTabOperation.findUnique({ where: { id } })
if (prior) {
@@ -447,8 +475,10 @@ export class SuperTabStore {
return { id, revision: prior.revision }
}
const state = createSuperTab(id, name, { id: user.sub, email: user.email }, user.autonomousEnv, projectVisibility)
+ // Every new Swarm is in a Workspace, invite-only there until its owner or the Workspace's admins open it (workspaceStore.ts).
+ state.workspaceId = await workspaceForNewSwarm(tx, user, name, id, workspaceId)
// Born in parts: its state lives in the Swarm* parts, and `state` only fences older backends (schema.prisma).
- await tx.superTab.create({ data: { id, ownerId: user.sub, autonomousEnv: user.autonomousEnv, ...indexesOf(state), format: 2, state: { version: 2 } } })
+ await tx.superTab.create({ data: { id, ownerId: user.sub, autonomousEnv: user.autonomousEnv, workspaceId: state.workspaceId, ...indexesOf(state), format: 2, state: { version: 2 } } })
await insertParts(tx, split({ ...state, sequenceBase: 0 }, { tabId: id, version: 1, now: clock.next() }))
await tx.superTabOperation.create({ data: { id, tabId: id, actorKey: `person:${user.sub}`, requestHash, revision: 0, result: { id } } })
return { id, revision: 0 }
@@ -466,6 +496,43 @@ export class SuperTabStore {
}), next: rows.length > 100 ? rows[99]!.id : null }
}
+ async workspaceList(user: AuthUser) {
+ this.personOnly(user)
+ return { workspaces: await listWorkspaces(this.db, user) }
+ }
+
+ /** Opens a Swarm to its Workspace's members, or closes it again: its owner (not a guest) or the Workspace's owners and admins,
+ * who need not be in the Swarm. Closing it leaves everyone who joined. */
+ async setWorkspaceVisibility(user: AuthUser, tabId: string, visibility: 'invite-only' | 'workspace') {
+ this.personOnly(user)
+ return transaction(this.db, async tx => {
+ const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)
+ if (!state.workspaceId) fail('WORKSPACE_REQUIRED', `This Swarm has no ${WORKSPACE_LABEL} yet.`, 409)
+ const own = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })
+ if (!(state.ownerId === user.sub && own && !own.removedAt && own.role !== 'guest')) await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.manage')
+ state.workspaceVisibility = visibility
+ await this.save(tx, loaded, state, clock.next(), [{ kind: 'head', key: 'head' }])
+ return { id: tabId, workspaceVisibility: visibility }
+ })
+ }
+
+ /** A member or above joins a Swarm open to their Workspace, as a collaborator. A guest never does (design, Roles). */
+ async workspaceJoin(user: AuthUser, tabId: string, operationId: string) {
+ this.personOnly(user)
+ return transaction(this.db, async tx => {
+ const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)
+ if (!state.workspaceId || state.workspaceVisibility !== 'workspace') fail('FORBIDDEN', 'This Swarm is not open to its Workspace.', 403)
+ await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.joinOpen')
+ const existing = state.people.find(p => p.id === user.sub)
+ if (existing) return { id: tabId, role: existing.role, alreadyMember: true }
+ const member = { id: user.sub, email: authenticatedEmail(user.email)!, role: 'collaborator' as const, generation: stableId('workspace-join', tabId, user.sub, operationId) }
+ state.people.push(member)
+ // As a link join does: the open visibility it relied on lives on the head, so closing it at once conflicts.
+ await this.save(tx, loaded, state, clock.next(), [{ kind: 'head', key: 'head' }])
+ return { id: tabId, role: member.role, alreadyMember: false }
+ })
+ }
+
async invitations(user: AuthUser) {
this.personOnly(user)
const email = user.email.trim().toLowerCase()
@@ -548,6 +615,13 @@ export class SuperTabStore {
return { id: tabId, role: member.role, alreadyMember: result.alreadyMember === true }
}
const alreadyMember = !!member
+ if (!member && state.workspaceId) {
+ // A link or an email domain makes a guest of the Workspace, never higher. Someone the Workspace removed comes back only by
+ // an invitation, never by a general link (design, Roles).
+ const prior = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })
+ if (prior?.removedAt) fail(WORKSPACE_ACCESS_REVOKED, `You were removed from this Swarm's ${WORKSPACE_LABEL}. Ask its owner to invite you.`, 403)
+ await addMember(tx, state.workspaceId, { id: user.sub, email: user.email }, 'guest', state.ownerId, receiptId)
+ }
if (!member) {
member = { id: user.sub, email: authenticatedEmail(user.email)!, role: sharing.access.role, generation: receiptId }
state.people.push(member)
@@ -572,11 +646,12 @@ export class SuperTabStore {
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) : []
+ const otherWorkspace = visible.machines?.length ? await this.otherWorkspaceMachines(tx, state) : []
return { lastChangedAt: (await lastChangedAt(tx, [tabId])).get(tabId) ?? 0, 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), teamAccountRequired(state))
+ const refusal = teamWorkRefusal(stored, now, teamMachines.includes(pool.machineId), teamAccountRequired(state), otherWorkspace.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 } }
}) } }
@@ -626,7 +701,8 @@ export class SuperTabStore {
}
}
- private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {
+ private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
+ workspaceLeave = false) {
const { operationId, command } = operationSchema.parse(input)
let ended: WorkHold[] = []
const done = await transaction(this.db, async tx => {
@@ -649,11 +725,18 @@ export class SuperTabStore {
}
if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)
if (team !== null && !hostMachineId) this.teamCommand(original, team, user, command)
+ // Accepting a Swarm's invitation from outside its Workspace makes the person a guest of the Workspace first (design, Roles).
+ if (command.type === 'invite.accept' && !hostMachineId && original.workspaceId) {
+ const email = user.email.trim().toLowerCase()
+ const invite = original.invitations.find(i => i.id === command.inviteId && i.email === email && i.expiresAt > this.now())
+ // Only the Swarm's owner invites (invite.create), so the guest is added on the owner's authority.
+ if (invite) await addMember(tx, original.workspaceId, { id: user.sub, email }, 'guest', original.ownerId, stableId('workspace-guest', tabId, user.sub, operationId))
+ }
// A removed agent's or machine's host confirms its close or cleanup as the machine owner, who may have left the Swarm with it.
const actor: Actor = command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned' ? { kind: 'person', userId: user.sub, email: user.email }
: hostMachineId && 'startId' in command
? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
- : await this.actor(tx, user, original, asAgentId)
+ : await this.actor(tx, user, original, asAgentId, workspaceLeave && command.type === 'member.remove' && command.userId === user.sub && !asAgentId)
const receiptId = stableId(tabId, actorKey(actor), operationId)
const requestHash = hash(command)
const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })
@@ -756,8 +839,13 @@ export class SuperTabStore {
if ((command.type === 'member.avatar' || command.type === 'agent.avatar') && command.avatar?.kind === 'upload') {
context.avatarUpload = await this.avatarUpload(tx, tabId, actor, command.avatar.id)
}
+ if ((command.type === 'invite.create' || command.type === 'invite.revoke') && actor.kind === 'person' && original.workspaceId) {
+ const member = await activeMember(tx, original.workspaceId, actor.userId)
+ if (member) context.workspaceRole = member.role as WorkspaceRole
+ }
if (TEAM_WORK_COMMANDS.has(command.type)) {
context.teamMachines = await this.teamMachines(tx, original)
+ context.otherWorkspaceMachines = await this.otherWorkspaceMachines(tx, original)
if (this.hooks.teamAccountsIdle) context.teamAccountsIdle = true
}
if (command.type === 'agent.screen' || command.type === 'agent.input') {
@@ -1204,7 +1292,8 @@ export class SuperTabStore {
} else if (team !== null) {
// A team session is never the project's owner: it reads a text only for an agent its own machine hosts.
if (!await this.hostsProject(tx, state, user, project.id, team)) unavailable()
- } else if (!(user.sub === project.ownerId && state.people.some(p => p.id === user.sub)) && !await this.hostsProject(tx, state, user, project.id)) {
+ } else if (!(user.sub === project.ownerId && state.people.some(p => p.id === user.sub) && await hasWorkspaceAccess(tx, state, user.sub))
+ && !await this.hostsProject(tx, state, user, project.id)) {
unavailable()
}
const stored = await tx.superTabRoleText.findUnique({ where: { id: stableId(tabId, projectId, roleId) } })
@@ -1417,6 +1506,7 @@ export class SuperTabStore {
this.personOnly(user)
return transaction(this.db, async tx => {
const { state: tab } = await this.load(tx, user, tabId, { allGroups: true })
+ await this.actor(tx, user, tab)
return { mentions: await listMentions(tx, tabId, tab, { kind: 'person', userId: user.sub, email: user.email }, this.now(), state === 'waiting') }
})
}
@@ -1593,6 +1683,7 @@ export class SuperTabStore {
return await transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId)
person(state, user.sub)
+ await requireWorkspaceAccess(tx, state, user.sub)
const target = state.agents.find(a => a.machineId === machineId && a.harnessId === harnessId && a.machineOwnerId === machineOwnerId)
if (!target) return false
agent(state, target.id)
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index 24609ba52..833ec2014 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -12,6 +12,11 @@ export async function ensurePartExpiry(db: PrismaClient): Promise<void> {
for (const collection of ['SwarmHead', 'SwarmGroup', 'SwarmStart', 'SwarmProgress']) {
await db.$runCommandRaw({ createIndexes: collection, indexes: [{ key: { purgeAt: 1 }, name: 'part_purge', expireAfterSeconds: 0 }] })
}
+ // Workspaces (workspaceStore.ts): a removed person's row, a finished removal and a deleted Workspace 30 days on, an invitation when it expires.
+ for (const collection of ['SwarmWorkspace', 'SwarmWorkspaceMember', 'SwarmWorkspaceRemoval']) {
+ await db.$runCommandRaw({ createIndexes: collection, indexes: [{ key: { purgeAt: 1 }, name: 'workspace_purge', expireAfterSeconds: 0 }] })
+ }
+ await db.$runCommandRaw({ createIndexes: 'SwarmWorkspaceInvitation', indexes: [{ key: { expiresAt: 1 }, name: 'workspace_invitation_expiry', expireAfterSeconds: 0 }] })
}
/** A removed person, agent or machine keeps its tombstone after its 7 days, with its data dropped: the version it holds
@@ -117,9 +122,11 @@ export async function sweepSwarms(db: PrismaClient, now = Date.now()) {
tombstonesCompacted: await compactTombstones(db, now) }
}
-/** Runs the sweeps every hour in the singleton worker. */
-export function startSwarmSweeps(db: PrismaClient, everyMs = 3_600_000): () => void {
- const run = () => void sweepSwarms(db).then(result => logger.info('[swarm-sweeps] done', result))
+/** Runs the sweeps every hour in the singleton worker. `finishWorkspaceRemovals` finishes Workspace removals whose Swarm removals
+ * did not all run (workspaceStore.ts SwarmWorkspaces.finishRemovals); it needs the store, so the worker passes it in. */
+export function startSwarmSweeps(db: PrismaClient, everyMs = 3_600_000, finishWorkspaceRemovals?: () => Promise<number>): () => void {
+ const run = () => void sweepSwarms(db).then(async result => ({ ...result, workspaceRemovalsPending: await finishWorkspaceRemovals?.() }))
+ .then(result => logger.info('[swarm-sweeps] done', result))
.catch(error => logger.warn('[swarm-sweeps] failed', { error: error instanceof Error ? error.message : String(error) }))
run()
const timer = setInterval(run, everyMs)
diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.ts
index cdeced0df..8f2c15de6 100644
--- a/backend/src/superTabs/teamRouting.test.ts
+++ b/backend/src/superTabs/teamRouting.test.ts
@@ -601,3 +601,29 @@ describe('one machine: a Mac whose Harness Team account was made again', () => {
expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
})
})
+
+// A Harness Team account runs every teammate's work as one macOS user, so in Swarms of two Workspaces one Workspace's agents could
+// read the other's folders there (docs/plans/2026-10-27-swarm-workspaces.md, Audience). `otherWorkspaceMachines`: the machines this
+// Swarm's store found contributed to a Swarm of another Workspace.
+describe('a Team machine serving more than one Workspace', () => {
+ it('takes no teammate\'s work while it is in Swarms of another Workspace, and says why', () => {
+ const f = swarm(), group = f.group()
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, { ...f.pooled('mate-team'), otherWorkspaceMachines: ['mate-team'] })))
+ .toMatchObject({ code: 'MACHINE_IN_OTHER_WORKSPACE', status: 403,
+ message: 'The Harness Team account on MacBook Pro · Team also serves another Workspace\'s Swarms, so it runs only its owner\'s projects here.' })
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('still runs its owner\'s own projects there, and a teammate\'s work once it serves this Workspace alone', () => {
+ const f = swarm()
+ f.run({ type: 'agent.start', request: f.request(f.group(f.mine, mate), 'mate-team', f.mine) }, mate, { ...f.pooled('mate-team'), otherWorkspaceMachines: ['mate-team'] })
+ f.run({ type: 'agent.start', request: f.request(f.group(), 'mate-team') }, owner, { ...f.pooled('mate-team'), otherWorkspaceMachines: [] })
+ expect(f.state.starts).toHaveLength(2)
+ })
+
+ it('shows routing the reason, like any other refusal', () => {
+ const f = swarm()
+ expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true, true)?.code).toBe('MACHINE_IN_OTHER_WORKSPACE')
+ expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true, false)).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.ts
new file mode 100644
index 000000000..300aa480e
--- /dev/null
+++ b/backend/src/superTabs/workspaceStore.ts
@@ -0,0 +1,322 @@
+import type { Prisma, PrismaClient, SwarmWorkspaceMember, SwarmWorkspaceRemoval } from '@prisma/client'
+import type { AuthUser } from '../lib/ssoAuth.js'
+import { fail, stableId, type SuperTabState } from './model.js'
+import { mayAssignRole, mayManageMember, WORKSPACE_LABEL, workspaceCan, type WorkspaceAction, type WorkspaceRole } from './workspaces.js'
+import { logger } from '../utils/logger.js'
+
+type Transaction = Prisma.TransactionClient
+
+export const WORKSPACE_ACCESS_REVOKED = 'WORKSPACE_ACCESS_REVOKED'
+
+/** After the migration has given every Swarm a Workspace, a Swarm without one is refused rather than served by its own
+ * membership alone (design, Migration step 3). */
+export const workspacesRequired = (): boolean => process.env.SWARM_WORKSPACES_REQUIRED === '1'
+
+/** A person's own Workspace, made the first time they create a Swarm without naming one. The migration derives the same id. */
+export const personalWorkspaceId = (environment: string, userId: string): string => stableId('swarm-workspace', environment, userId)
+export const memberId = (workspaceId: string, userId: string): string => `${workspaceId}:${userId}`
+
+/** The person's current membership, or null when they are not in the Workspace or were removed from it. */
+export async function activeMember(tx: Transaction | PrismaClient, workspaceId: string, userId: string): Promise<SwarmWorkspaceMember | null> {
+ const row = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(workspaceId, userId) } })
+ return row && !row.removedAt ? row : null
+}
+
+/** Answers already read in a transaction: a host read checks every agent's contributor, mostly the same few people. */
+const checked = new WeakMap<object, Map<string, boolean>>()
+
+/** Whether the person is still in the Swarm's Workspace; a Swarm from before Workspaces passes until the switch is on. Read once
+ * per person per transaction, which reads one snapshot. */
+export async function hasWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string): Promise<boolean> {
+ if (!state.workspaceId) return !workspacesRequired()
+ const answers = checked.get(tx) ?? new Map<string, boolean>()
+ checked.set(tx, answers)
+ const key = memberId(state.workspaceId, userId)
+ const known = answers.get(key)
+ if (known !== undefined) return known
+ const answer = !!await activeMember(tx, state.workspaceId, userId)
+ answers.set(key, answer)
+ return answer
+}
+
+/** The one Workspace check of every Swarm read and command (design, Audience): the person must still be in the Swarm's Workspace.
+ * Reading the Swarm needs its own membership as well, which the caller checks as before. */
+export async function requireWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string): Promise<void> {
+ if (await hasWorkspaceAccess(tx, state, userId)) return
+ fail(WORKSPACE_ACCESS_REVOKED, state.workspaceId ? `You are no longer in this Swarm's ${WORKSPACE_LABEL}.` : `This Swarm has no ${WORKSPACE_LABEL} yet.`, 403)
+}
+
+/** The member, who must be allowed `action`. Not being in the Workspace at all reads as the Workspace being unavailable. */
+export async function requireWorkspaceRole(tx: Transaction, workspaceId: string, userId: string, action: WorkspaceAction): Promise<SwarmWorkspaceMember & { role: WorkspaceRole }> {
+ const member = await activeMember(tx, workspaceId, userId)
+ if (!member) fail('NOT_FOUND', `This ${WORKSPACE_LABEL} is unavailable.`, 404)
+ if (!workspaceCan(member.role as WorkspaceRole, action)) fail('WORKSPACE_ROLE_REQUIRED', `Your role in this ${WORKSPACE_LABEL} cannot do that.`, 403)
+ return member as SwarmWorkspaceMember & { role: WorkspaceRole }
+}
+
+/** Adds a person to a Workspace with `role`, or brings a removed one back with a new generation (old receipts stay refused).
+ * Someone already in it keeps their role. Nobody comes back while a removal of theirs is still open: they could still
+ * be in a Swarm of the Workspace that the removal has not left yet (SwarmWorkspaces.finishPending finishes it first). */
+export async function addMember(tx: Transaction, workspaceId: string, person: { id: string; email: string }, role: WorkspaceRole, addedBy: string,
+ generation: string): Promise<SwarmWorkspaceMember> {
+ const id = memberId(workspaceId, person.id)
+ checked.get(tx)?.delete(id)
+ const prior = await tx.swarmWorkspaceMember.findUnique({ where: { id } })
+ if (prior && !prior.removedAt) return prior
+ if (await tx.swarmWorkspaceRemoval.count({ where: { workspaceId, userId: person.id, finishedAt: null } })) {
+ fail('REMOVAL_PENDING', `An earlier removal from this ${WORKSPACE_LABEL} is still taking them out of its Swarms. Try again in a few minutes.`, 409)
+ }
+ const data = { email: person.email.trim().toLowerCase(), role, generation, addedBy, addedAt: new Date(), removedAt: null, removedBy: null, purgeAt: null }
+ return prior
+ ? tx.swarmWorkspaceMember.update({ where: { id }, data: { ...data, version: { increment: 1 } } })
+ : tx.swarmWorkspaceMember.create({ data: { id, workspaceId, userId: person.id, ...data } })
+}
+
+/** The Workspace a Swarm is created in: the one named, where the person may create Swarms, or else their own, made now. */
+export async function workspaceForNewSwarm(tx: Transaction, user: AuthUser, swarmName: string, generation: string, workspaceId?: string): Promise<string> {
+ if (workspaceId) {
+ await requireWorkspaceRole(tx, workspaceId, user.sub, 'swarm.create')
+ return workspaceId
+ }
+ const id = personalWorkspaceId(user.autonomousEnv, user.sub)
+ const workspace = await tx.swarmWorkspace.findUnique({ where: { id } })
+ if (!workspace) {
+ await tx.swarmWorkspace.create({ data: { id, autonomousEnv: user.autonomousEnv, name: swarmName, ownerId: user.sub, deletedAt: null, purgeAt: null } })
+ await addMember(tx, id, { id: user.sub, email: user.email }, 'owner', user.sub, generation)
+ return id
+ }
+ if (workspace.deletedAt) fail('WORKSPACE_REQUIRED', `Choose a ${WORKSPACE_LABEL} for this Swarm.`, 409)
+ await requireWorkspaceRole(tx, id, user.sub, 'swarm.create')
+ return id
+}
+
+export interface WorkspaceSummary {
+ id: string; name: string; role: WorkspaceRole; revision: number
+ /** `member`: the person is in it; otherwise it is open to the Workspace, or listed for its owners and admins. */
+ swarms: Array<{ id: string; name: string; workspaceVisibility: 'invite-only' | 'workspace'; member: boolean }>
+}
+
+/** The person's Workspaces, each with the Swarms they may see there: their own, those open to the Workspace (members and up), and
+ * every one for owners and admins (names only: reading still needs the Swarm's own membership). */
+export async function listWorkspaces(db: PrismaClient, user: AuthUser): Promise<WorkspaceSummary[]> {
+ const memberships = await db.swarmWorkspaceMember.findMany({ where: { userId: user.sub, removedAt: null }, take: 100 })
+ // Filtered here, not in the query: Prisma's `null` on Mongo misses a field that was never written.
+ const workspaces = (await db.swarmWorkspace.findMany({ where: { id: { in: memberships.map(m => m.workspaceId) }, autonomousEnv: user.autonomousEnv } })).filter(o => !o.deletedAt)
+ const rows = await db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, workspaceId: { in: workspaces.map(o => o.id) } },
+ select: { id: true, workspaceId: true, memberIds: true, format: true } })
+ const heads = await db.swarmHead.findMany({ where: { id: { in: rows.filter(r => r.format === 2).map(r => `${r.id}:head`) } }, select: { tabId: true, data: true } })
+ const headOf = new Map(heads.map(h => [h.tabId, h.data as { name?: string; workspaceVisibility?: 'invite-only' | 'workspace' }]))
+ return workspaces.map(workspace => {
+ const role = memberships.find(m => m.workspaceId === workspace.id)!.role as WorkspaceRole
+ const swarms = rows.filter(r => r.workspaceId === workspace.id).flatMap(row => {
+ const head = headOf.get(row.id)
+ if (!head) return []
+ const workspaceVisibility = head.workspaceVisibility ?? 'invite-only'
+ const member = row.memberIds.includes(user.sub)
+ const visible = member || workspaceCan(role, 'swarms.listAll') || (workspaceVisibility === 'workspace' && workspaceCan(role, 'swarm.joinOpen'))
+ return visible ? [{ id: row.id, name: head.name ?? '', workspaceVisibility, member }] : []
+ })
+ return { id: workspace.id, name: workspace.name, role, revision: workspace.revision, swarms }
+ })
+}
+
+/** How long a removed person's row and a deleted Workspace stay before they are purged (design, Growth). */
+export const WORKSPACE_PURGE_MS = 30 * 24 * 60 * 60 * 1000
+const INVITATION_MS = 14 * 24 * 60 * 60 * 1000
+
+interface WorkspaceDeps {
+ transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>
+ /** The person leaves one Swarm, as a leave of their own does (`member.remove` of themselves), past the Workspace check. */
+ leave(person: AuthUser, tabId: string, operationId: string): Promise<unknown>
+ now(): number
+}
+
+const personOf = (row: Pick<SwarmWorkspaceMember, 'userId' | 'email'>, environment: string): AuthUser =>
+ ({ sub: row.userId, email: row.email, autonomousEnv: environment as AuthUser['autonomousEnv'], role: 'user' })
+
+/** Workspace actions: people, roles, invitations, ownership. Every one is the signed-in person's own (design, Identity). */
+export class SwarmWorkspaces {
+ constructor(private readonly db: PrismaClient, private readonly deps: WorkspaceDeps) {}
+
+ private async workspace(tx: Transaction, user: AuthUser, workspaceId: string) {
+ const workspace = await tx.swarmWorkspace.findUnique({ where: { id: workspaceId } })
+ if (!workspace || workspace.deletedAt || workspace.autonomousEnv !== user.autonomousEnv) fail('NOT_FOUND', `This ${WORKSPACE_LABEL} is unavailable.`, 404)
+ return workspace
+ }
+
+ async create(user: AuthUser, operationId: string, name: string) {
+ const id = stableId('swarm-workspace', user.autonomousEnv, user.sub, operationId)
+ return this.deps.transaction(async tx => {
+ const prior = await tx.swarmWorkspace.findUnique({ where: { id } })
+ if (prior) {
+ if (prior.ownerId !== user.sub || prior.name !== name) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')
+ return { id }
+ }
+ await tx.swarmWorkspace.create({ data: { id, autonomousEnv: user.autonomousEnv, name, ownerId: user.sub, deletedAt: null, purgeAt: null } })
+ await addMember(tx, id, { id: user.sub, email: user.email }, 'owner', user.sub, id)
+ return { id }
+ })
+ }
+
+ async rename(user: AuthUser, workspaceId: string, name: string) {
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ await requireWorkspaceRole(tx, workspaceId, user.sub, 'workspace.rename')
+ const workspace = await tx.swarmWorkspace.update({ where: { id: workspaceId }, data: { name, revision: { increment: 1 } } })
+ return { id: workspace.id, name: workspace.name, revision: workspace.revision }
+ })
+ }
+
+ /** The Workspace's people for members and up; owners and admins also see open invitations. */
+ async members(user: AuthUser, workspaceId: string) {
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ const me = await requireWorkspaceRole(tx, workspaceId, user.sub, 'people.list')
+ const rows = await tx.swarmWorkspaceMember.findMany({ where: { workspaceId, removedAt: null }, orderBy: { addedAt: 'asc' }, take: 1000 })
+ const invitations = workspaceCan(me.role, 'workspace.invite')
+ ? (await tx.swarmWorkspaceInvitation.findMany({ where: { workspaceId }, take: 1000 })).filter(i => i.expiresAt.getTime() > this.deps.now())
+ .map(i => ({ email: i.email, role: i.role, expiresAt: i.expiresAt.getTime() }))
+ : []
+ return { members: rows.map(m => ({ userId: m.userId, email: m.email, role: m.role })), invitations }
+ })
+ }
+
+ async invite(user: AuthUser, workspaceId: string, email: string, role: WorkspaceRole) {
+ const address = email.trim().toLowerCase()
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ const me = await requireWorkspaceRole(tx, workspaceId, user.sub, 'workspace.invite')
+ if (!mayAssignRole(me.role, role)) fail('WORKSPACE_ROLE_REQUIRED', `Your role in this ${WORKSPACE_LABEL} cannot invite as ${role}.`, 403)
+ const id = `${workspaceId}:${address}`, expiresAt = new Date(this.deps.now() + INVITATION_MS)
+ await tx.swarmWorkspaceInvitation.upsert({ where: { id }, create: { id, workspaceId, email: address, role, invitedBy: user.sub, expiresAt },
+ update: { role, invitedBy: user.sub, expiresAt } })
+ return { email: address, role, expiresAt: expiresAt.getTime() }
+ })
+ }
+
+ /** Invitations waiting for the signed-in person. */
+ async invitationsFor(user: AuthUser) {
+ const rows = await this.db.swarmWorkspaceInvitation.findMany({ where: { email: user.email.trim().toLowerCase(), expiresAt: { gt: new Date(this.deps.now()) } }, take: 100 })
+ const workspaces = await this.db.swarmWorkspace.findMany({ where: { id: { in: rows.map(r => r.workspaceId) }, autonomousEnv: user.autonomousEnv } })
+ return { invitations: rows.flatMap(row => {
+ const workspace = workspaces.find(o => o.id === row.workspaceId && !o.deletedAt)
+ return workspace ? [{ workspaceId: workspace.id, name: workspace.name, role: row.role, expiresAt: row.expiresAt.getTime() }] : []
+ }) }
+ }
+
+ /** Accepting brings a person in with the invited role, or raises a guest to it; it never lowers a role. */
+ async accept(user: AuthUser, workspaceId: string) {
+ const address = user.email.trim().toLowerCase()
+ // An earlier removal still open is finished first; if it cannot be, addMember refuses below.
+ await this.finishPending(workspaceId, user.sub)
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ const invitation = await tx.swarmWorkspaceInvitation.findUnique({ where: { id: `${workspaceId}:${address}` } })
+ if (!invitation || invitation.expiresAt.getTime() <= this.deps.now()) fail('NOT_FOUND', 'This invitation is unavailable.', 404)
+ await tx.swarmWorkspaceInvitation.delete({ where: { id: invitation.id } })
+ const role = invitation.role as WorkspaceRole
+ const current = await activeMember(tx, workspaceId, user.sub)
+ if (current && current.role === 'guest' && role !== 'guest') {
+ await tx.swarmWorkspaceMember.update({ where: { id: current.id }, data: { role, version: { increment: 1 } } })
+ return { workspaceId, role }
+ }
+ const added = await addMember(tx, workspaceId, { id: user.sub, email: address }, role, invitation.invitedBy, stableId('workspace-accept', invitation.id, String(invitation.expiresAt.getTime())))
+ return { workspaceId, role: added.role }
+ })
+ }
+
+ /** Someone who owns one of the Workspace's Swarms stays at least a member, and cannot be removed until it moves. */
+ private async ownsWorkspaceSwarm(tx: Transaction, workspaceId: string, userId: string): Promise<boolean> {
+ return !!await tx.superTab.findFirst({ where: { workspaceId, ownerId: userId }, select: { id: true } })
+ }
+
+ async setRole(user: AuthUser, workspaceId: string, userId: string, role: WorkspaceRole) {
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ const me = await requireWorkspaceRole(tx, workspaceId, user.sub, 'people.list')
+ const target = await activeMember(tx, workspaceId, userId) ?? fail('NOT_FOUND', 'This person is not in the Workspace.', 404)
+ if (userId === user.sub || !mayManageMember(me.role, target.role as WorkspaceRole) || !mayAssignRole(me.role, role)) {
+ fail('WORKSPACE_ROLE_REQUIRED', `Your role in this ${WORKSPACE_LABEL} cannot give that role.`, 403)
+ }
+ if (role === 'guest' && await this.ownsWorkspaceSwarm(tx, workspaceId, userId)) {
+ fail('SWARM_OWNER', 'This person owns a Swarm of this Workspace, so they stay a member or above.', 409)
+ }
+ await tx.swarmWorkspaceMember.update({ where: { id: target.id }, data: { role, version: { increment: 1 } } })
+ return { userId, role }
+ })
+ }
+
+ /** Ownership moves to an admin at once; the old owner stays as an admin. */
+ async transfer(user: AuthUser, workspaceId: string, userId: string) {
+ return this.deps.transaction(async tx => {
+ await this.workspace(tx, user, workspaceId)
+ const me = await requireWorkspaceRole(tx, workspaceId, user.sub, 'workspace.transfer')
+ const target = await activeMember(tx, workspaceId, userId)
+ if (!target || target.role !== 'admin') fail('ADMIN_REQUIRED', `Ownership moves only to an admin of the ${WORKSPACE_LABEL}.`, 409)
+ await tx.swarmWorkspaceMember.update({ where: { id: target.id }, data: { role: 'owner', version: { increment: 1 } } })
+ await tx.swarmWorkspaceMember.update({ where: { id: me.id }, data: { role: 'admin', version: { increment: 1 } } })
+ await tx.swarmWorkspace.update({ where: { id: workspaceId }, data: { ownerId: userId, revision: { increment: 1 } } })
+ return { ownerId: userId }
+ })
+ }
+
+ /** Removes a person (or lets them leave), then from every Swarm of the Workspace. The Workspace check refuses them everywhere
+ * from the moment the first transaction commits; the Swarm removals follow, and `finishRemovals` retries any that
+ * failed (design, Concurrency). */
+ async remove(user: AuthUser, workspaceId: string, userId: string) {
+ const removed = await this.deps.transaction(async tx => {
+ const workspace = await this.workspace(tx, user, workspaceId)
+ const target = await activeMember(tx, workspaceId, userId) ?? fail('NOT_FOUND', 'This person is not in the Workspace.', 404)
+ if (target.role === 'owner') fail('OWNER_REQUIRED', `The ${WORKSPACE_LABEL}'s owner cannot leave it; transfer it first.`, 409)
+ if (userId !== user.sub) {
+ const me = await requireWorkspaceRole(tx, workspaceId, user.sub, 'people.list')
+ if (!mayManageMember(me.role, target.role as WorkspaceRole)) fail('WORKSPACE_ROLE_REQUIRED', `Your role in this ${WORKSPACE_LABEL} cannot remove them.`, 403)
+ }
+ if (await this.ownsWorkspaceSwarm(tx, workspaceId, userId)) fail('SWARM_OWNER', 'This person owns a Swarm of this Workspace. Move or delete it first.', 409)
+ const now = new Date(this.deps.now())
+ await tx.swarmWorkspaceMember.update({ where: { id: target.id }, data: { removedAt: now, removedBy: user.sub,
+ purgeAt: new Date(now.getTime() + WORKSPACE_PURGE_MS), version: { increment: 1 } } })
+ // The removal stays open until the person has left every Swarm of the Workspace, whatever happens to their row after.
+ return tx.swarmWorkspaceRemoval.create({ data: { id: `${target.id}:${target.generation}`, workspaceId, userId, email: target.email,
+ generation: target.generation, autonomousEnv: workspace.autonomousEnv, removedAt: now, removedBy: user.sub, finishedAt: null, purgeAt: null } })
+ })
+ return { userId, pending: await this.finish(removed) }
+ }
+
+ /** The removed person leaves each Swarm of the Workspace they are still in; the removal closes once none is left. Returns how
+ * many Swarms could not be left now. */
+ private async finish(removal: SwarmWorkspaceRemoval): Promise<number> {
+ const rows = await this.db.superTab.findMany({ where: { autonomousEnv: removal.autonomousEnv, workspaceId: removal.workspaceId, memberIds: { has: removal.userId } },
+ select: { id: true } })
+ let pending = 0
+ for (const row of rows) {
+ try { await this.deps.leave(personOf(removal, removal.autonomousEnv), row.id, stableId('workspace-removal', removal.id)) } catch (error) {
+ pending++
+ logger.warn('[swarm-workspaces] a removal could not leave a Swarm yet', { workspaceId: removal.workspaceId, tabId: row.id, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ if (!pending) {
+ const now = this.deps.now()
+ await this.db.swarmWorkspaceRemoval.update({ where: { id: removal.id }, data: { finishedAt: new Date(now), purgeAt: new Date(now + WORKSPACE_PURGE_MS) } })
+ }
+ return pending
+ }
+
+ /** Finishes the person's open removals from this Workspace, if it can. */
+ async finishPending(workspaceId: string, userId: string): Promise<number> {
+ let pending = 0
+ for (const removal of await this.db.swarmWorkspaceRemoval.findMany({ where: { workspaceId, userId, finishedAt: null } })) pending += await this.finish(removal)
+ return pending
+ }
+
+ /** The sweep: every open removal, oldest id first, a page at a time, so none is starved by the ones before it. */
+ async finishRemovals(): Promise<number> {
+ let pending = 0, after: string | undefined
+ for (;;) {
+ const page = await this.db.swarmWorkspaceRemoval.findMany({ where: { finishedAt: null, ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 200 })
+ for (const removal of page) pending += await this.finish(removal)
+ if (page.length < 200) return pending
+ after = page.at(-1)!.id
+ }
+ }
+}
diff --git a/backend/src/superTabs/workspaces.test.ts b/backend/src/superTabs/workspaces.test.ts
new file mode 100644
index 000000000..d7c8d5bb4
--- /dev/null
+++ b/backend/src/superTabs/workspaces.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import { mayAssignRole, mayManageMember, workspaceCan, type WorkspaceRole } from './workspaces.js'
+
+const roles: WorkspaceRole[] = ['owner', 'admin', 'member', 'guest']
+const allowed = (action: Parameters<typeof workspaceCan>[1]) => roles.filter(role => workspaceCan(role, action))
+
+describe('what each Workspace role may do (design: Roles)', () => {
+ it('shows the Workspace people list to members and above, never to guests', () => {
+ expect(allowed('people.list')).toEqual(['owner', 'admin', 'member'])
+ })
+
+ it('shows every Workspace Swarm name only to owners and admins', () => {
+ expect(allowed('swarms.listAll')).toEqual(['owner', 'admin'])
+ })
+
+ it('lets members and above create Swarms and join those open to the Workspace', () => {
+ expect(allowed('swarm.create')).toEqual(['owner', 'admin', 'member'])
+ expect(allowed('swarm.joinOpen')).toEqual(['owner', 'admin', 'member'])
+ expect(allowed('swarm.invite')).toEqual(['owner', 'admin', 'member'])
+ })
+
+ it('lets only owners and admins invite to the Workspace or manage any Swarm of it', () => {
+ expect(allowed('workspace.invite')).toEqual(['owner', 'admin'])
+ expect(allowed('swarm.manage')).toEqual(['owner', 'admin'])
+ })
+
+ it('keeps renaming, transferring and deleting the Workspace to its owner', () => {
+ for (const action of ['workspace.rename', 'workspace.transfer', 'workspace.delete'] as const) expect(allowed(action)).toEqual(['owner'])
+ })
+})
+
+describe('who may give a role or manage a person', () => {
+ it('lets an owner give any role but owner, and an admin only member or guest', () => {
+ expect(roles.filter(role => mayAssignRole('owner', role))).toEqual(['admin', 'member', 'guest'])
+ expect(roles.filter(role => mayAssignRole('admin', role))).toEqual(['member', 'guest'])
+ expect(roles.filter(role => mayAssignRole('member', role))).toEqual([])
+ expect(roles.filter(role => mayAssignRole('guest', role))).toEqual([])
+ })
+
+ it('lets an owner manage everyone but the owner, and an admin only members and guests', () => {
+ expect(roles.filter(role => mayManageMember('owner', role))).toEqual(['admin', 'member', 'guest'])
+ expect(roles.filter(role => mayManageMember('admin', role))).toEqual(['member', 'guest'])
+ expect(roles.filter(role => mayManageMember('member', role))).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/workspaces.ts b/backend/src/superTabs/workspaces.ts
new file mode 100644
index 000000000..d3f46ef44
--- /dev/null
+++ b/backend/src/superTabs/workspaces.ts
@@ -0,0 +1,31 @@
+/** Workspaces above Swarms (docs/plans/2026-10-27-swarm-workspaces.md). Not the Harness Team account (`team` in code), the
+ * macOS user for teammates' work. The on-screen word is WORKSPACE_LABEL, here alone. */
+export const WORKSPACE_LABEL = 'Workspace'
+
+export type WorkspaceRole = 'owner' | 'admin' | 'member' | 'guest'
+export type WorkspaceAction = 'people.list' | 'swarms.listAll' | 'swarm.create' | 'swarm.joinOpen' | 'swarm.invite' | 'swarm.manage' | 'workspace.invite'
+ | 'workspace.rename' | 'workspace.transfer' | 'workspace.delete'
+
+/** Deny by default: an action is allowed only to the roles listed. No role reads a Swarm it is not in. */
+const ALLOWED: Record<WorkspaceAction, readonly WorkspaceRole[]> = {
+ 'people.list': ['owner', 'admin', 'member'],
+ 'swarms.listAll': ['owner', 'admin'],
+ 'swarm.create': ['owner', 'admin', 'member'],
+ 'swarm.joinOpen': ['owner', 'admin', 'member'],
+ /** To a Swarm they are in. */
+ 'swarm.invite': ['owner', 'admin', 'member'],
+ 'swarm.manage': ['owner', 'admin'],
+ 'workspace.invite': ['owner', 'admin'],
+ 'workspace.rename': ['owner'],
+ 'workspace.transfer': ['owner'],
+ 'workspace.delete': ['owner'],
+}
+
+export const workspaceCan = (role: WorkspaceRole, action: WorkspaceAction): boolean => ALLOWED[action].includes(role)
+
+/** Roles each role may give. Ownership moves only by transfer, never by a role change. */
+const GIVES: Record<WorkspaceRole, readonly WorkspaceRole[]> = { owner: ['admin', 'member', 'guest'], admin: ['member', 'guest'], member: [], guest: [] }
+
+export const mayAssignRole = (actor: WorkspaceRole, role: WorkspaceRole): boolean => GIVES[actor].includes(role)
+/** Changing someone's role or removing them: an owner manages everyone else, an admin members and guests. */
+export const mayManageMember = (actor: WorkspaceRole, target: WorkspaceRole): boolean => GIVES[actor].includes(target)
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index 723aaef8b..33763105b 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -71,11 +71,12 @@ async function start(): Promise<void> {
machineBillingWorkerService.start()
productUsagePeopleRollupService.start()
- stopSweeps = startSwarmSweeps(prisma)
+ const swarms = new SuperTabStore(prisma)
+ stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals())
// Finished groups archive once GitHub says their pull requests are merged or closed; without the app, only groups that
// link none do (superTabs/archive.ts).
const githubConfig = githubAppConfig(env), githubApp = githubConfig ? new GitHubApp(githubConfig) : null
- stopArchive = startSwarmArchive(prisma, new SuperTabStore(prisma), () => githubApp ? appPullRequests(githubApp) : unknownPullRequests)
+ stopArchive = startSwarmArchive(prisma, swarms, () => githubApp ? appPullRequests(githubApp) : unknownPullRequests)
// PM2 wait_ready gates the singleton worker's "online" state on schema/catalog/backfill startup.
// Plain node/tsx runs do not provide process.send and simply continue.
process.send?.('ready')
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index d2646e017..af549c240 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,6 +1,6 @@
import { defineConfig } from 'vitest/config'
-export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts',
+export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
'integration/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',
'integration/superTabProfile.test.ts'], hookTimeout: 120000, testTimeout: 30000,
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/docs/naming-system.md b/docs/naming-system.md
index 80ad45fca..583f10f82 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -50,10 +50,11 @@ and **Browser**. Technical documentation may still call the terminal interface a
| **Agent** | The agent software chosen, or the AI doing the work. | Choose Codex; the agent is running tests. |
| **Model** | The model an agent uses. | Change the model while keeping the agent and project. |
| **Harness** in product copy | The software product. | Open Harness. |
-| **A harness** in the workspace | A running agent session with its own conversation and working context. | Start three Codex harnesses. |
+| **A harness** in a tab | A running agent session with its own conversation and working context. | Start three Codex harnesses. |
| **A harness** in the Store | A reusable setup containing agent instructions, tools, and an optional viewer. | Install the Blender harness. |
-| **Tab** | A workspace group of harnesses. | Frontend and Backend tabs. |
+| **Tab** | A group of harnesses in the window. | Frontend and Backend tabs. |
| **Swarm** | A collaborative tab containing projects, people, agents and contributed machines. Invite-only by default; its owner can enable joining by email domain or a shared link. | Open your company Swarm beside your regular tabs. |
+| **Workspace** | The level above Swarms: several Swarms on one account and the people who may be in them, each with a role (owner, admin, member or guest). A person can belong to several Workspaces. Not the Harness **Team account**, a Mac's privacy-checked account for teammates' work. System name: workspace. | Create the Swarm in your company Workspace. |
| **Project in a Swarm** | An initiative with its own product manager, repository, sharing and workgroups. | Discuss Lamp OS with its product manager; expand it to follow a workgroup. |
| **Instructions** | The visible name for a project's skill set and each role's text. System name: skill. | Open Instructions; edit Product Manager instructions. |
| **Product Manager** | The agent coordinating a Swarm project. Use **PM** in a compact role badge. System name: lead. | Message Product Manager. |
@@ -87,7 +88,7 @@ answers, lookups and work under 15 minutes itself, and routes the rest.
Use lowercase *harness* and *tab* in ordinary sentences. The action and context
distinguish the two uses of *harness*: install or update a package in the Store;
-start, pause, or stop a running harness in the workspace. Keep **agent** for choosing
+start, pause, or stop a running harness in a tab. Keep **agent** for choosing
the agent software and describing the AI's actions. Preserve **New Harness** as the
existing action name.
@@ -117,7 +118,7 @@ the Swarm has several (`Finn (web-2)`) and a count of new messages. Hovering say
**Chat with PM**, and ⇧⌘K opens the current project's.
**Your devices** opens the Devices dashboard and its existing agent conversation inside the
current Swarm, preserving project drafts and the selected workgroup. Ordinary tabs retain
-their standalone Devices workspace. The navigation, conversation and people panes have
+their standalone Devices view. The navigation, conversation and people panes have
draggable dividers; their default side widths are 300 and 280 pixels, respecting saved resizes.
The right pane is a stable directory of all humans and agents in the current Swarm that the
viewer can access. Selecting a project, workgroup or Devices does not filter that directory;
@@ -149,7 +150,7 @@ Cmd-S opens the existing lead creation form for a new Swarm and its first projec
reuses that form inside the current Swarm. Store uses Cmd-Control-S. Existing ordinary tabs keep
their behavior. The internal `superTab` identifiers, `harness super-tab` protocol and stored account
settings remain compatible; the older internal `Swarm` layout class still represents an ordinary
-workspace tab. The word *tab* can also name the keyboard key or a browser tab; context
+tab. The word *tab* can also name the keyboard key or a browser tab; context
distinguishes them.
A project belongs to a computer; identical paths on different computers do not
@@ -162,9 +163,9 @@ task form.
| Intent | Label |
| --- | --- |
| Start a running harness | **New Harness** |
-| Create a workspace group | **New Tab** |
+| Create a group of harnesses | **New Tab** |
| Open a shell | **New terminal** |
-| Manage a workspace group | **Rename Tab**, **Close Tab**, **Next Tab**, **Previous Tab** |
+| Manage a group of harnesses | **Rename Tab**, **Close Tab**, **Next Tab**, **Previous Tab** |
| Manage a running harness | **Rename Harness**, **Pause Harness**, **Resume Harness**, **Restart Harness**, **Stop Harness** |
| Author a reusable Store package | **Create Harness** |
| Start the bundled agent from the installed OS home | **Start OpenCode** |
@@ -183,7 +184,7 @@ configuration where it affects a decision.
| Disk unlock prompt | **Enter your password** |
| USB install action | **Install Harness** |
| USB startup | Open **Install Harness** directly; no trial choice or network step. |
-| First installed boot | **Connect to Wi-Fi** when disconnected, then the agent workspace. |
+| First installed boot | **Connect to Wi-Fi** when disconnected, then the agent window. |
| USB session label | Omit from the single installation footer. |
| Connect another execution machine | **Connect a computer** |
| Installer title | Omit the redundant heading; label the action. |
@@ -236,7 +237,7 @@ technical meanings. Use those terms where they help explain or diagnose behavior
| programmer or programmer-live as a default identity | **me**, **harness**, or **me@harness**, according to the field |
| hn or hn TUI as a product name | **Harness**; retain `hn` in command examples |
| New Swarm or Untitled Tab as an automatic group name | **New Tab** |
-| Swarm as a workspace group | **Tab** |
+| Swarm as a group of harnesses | **Tab** |
| TUI as the square device's mode label | **Harness** |
| DSH as a user-facing package name | The harness's actual name |
diff --git a/docs/plans/2026-10-27-swarm-workspaces.md b/docs/plans/2026-10-27-swarm-workspaces.md
new file mode 100644
index 000000000..9281ac25b
--- /dev/null
+++ b/docs/plans/2026-10-27-swarm-workspaces.md
@@ -0,0 +1,242 @@
+# Several workspaces on one account, with roles
+
+**Goal (roadmap, January):** three workspaces use Swarm side by side, a person can belong to several of them, and no workspace
+reads another's data. People in a workspace have roles: owner, admin, member, guest.
+
+**Status:** design, waiting for the Product Manager's approval. Nothing is built yet.
+
+## What is missing today
+
+Each Swarm is already its own audience: a Swarm reads only for the people in it (`SuperTab.memberIds`, `person()` in
+`superTabs/model.ts`). What is missing is the layer above a Swarm:
+
+- A person in several groups sees one flat list of every Swarm, with nothing to tell the groups apart or switch.
+- The only role above a project is the Swarm's own: owner, collaborator, viewer. Nobody but a Swarm's owner can manage
+ its people, and nobody can manage people across several Swarms.
+- Join by email domain is company-wide: two workspaces on `autonomous.ai` cannot keep each other out of their Swarms.
+- Swarms an outside customer will own (March) need a boundary for people, roles and, later, billing and an audit log.
+
+## Words
+
+It is a **Workspace**, on screen and in code (`SwarmWorkspace`, `workspaceId`): Ken's decision (2026-10-28), in place
+of the roadmap's **Team**. That word stays with the Harness **Team account** (a hidden macOS user for teammates' work,
+`sessionKind: 'team'`, `teamWorkCheck`, `teamHost`), a different thing. The naming system defines **Workspace**
+(docs/naming-system.md).
+
+## Model
+
+```
+Workspace (SwarmWorkspace) ── people with a workspace role (SwarmWorkspaceMember)
+ └─ Swarms (SuperTab.workspaceId) ── people with a Swarm role, as today (owner / collaborator / viewer)
+ └─ projects ── Public (everyone in the Swarm) or Private (invited), as today
+```
+
+- **`SwarmWorkspace`** `{ id, autonomousEnv, name, ownerId, revision, createdAt, deletedAt?, purgeAt? }`. Small, rarely
+ written.
+- **`SwarmWorkspaceMember`**, one document per person: `_id = workspaceId:userId`, `{ workspaceId, userId, email, role, generation,
+ version, addedBy, addedAt, removedAt? }`. Indexes `[workspaceId, removedAt]` and `[userId, removedAt]`.
+- **`SwarmWorkspaceInvitation`**, one per invited email: `{ workspaceId, email, role, invitedBy, expiresAt }`, 14 days.
+- **`SuperTab.workspaceId`** (new, nullable until migration) with index `[autonomousEnv, workspaceId]`, and the same id on the
+ Swarm's head part (`state.workspaceId`), which every load already reads. A Swarm belongs to exactly one Workspace, and never
+ moves between Workspaces in this version.
+- Swarm people, Swarm roles, project visibility and project members stay where they are (`SwarmMember` parts).
+
+A Swarm is reachable only by its Swarm's people, as today, **and** only while each of them is a current person of the
+Swarm's Workspace. The Workspace never grants access to a Swarm by itself; it limits who may be in one and who may manage it.
+
+## Roles
+
+| May… | Owner | Admin | Member | Guest |
+|---|---|---|---|---|
+| See the Workspace's people list | ✓ | ✓ | ✓ | only people in their own Swarms (as today) |
+| See the names of the Workspace's Swarms | all | all | Workspace-visible ones and their own | their own |
+| Read a Swarm | only if in it | only if in it | only if in it | only if in it |
+| Read a Private project | only if invited | only if invited | only if invited | only if invited |
+| Join a Workspace-visible Swarm by themselves | ✓ | ✓ | ✓ (as collaborator) | – |
+| Create a Swarm in the Workspace | ✓ | ✓ | ✓ | – |
+| Invite people to the Workspace | ✓ (any role) | ✓ (member, guest) | – | – |
+| Invite people to a Swarm they are in | ✓ | ✓ | ✓ (member, guest) | – |
+| Change roles, remove people | ✓ (anyone) | ✓ (members, guests) | – | – |
+| Delete a Workspace Swarm, or set its Workspace visibility | ✓ | ✓ | the Swarm's owner | – |
+| Contribute a machine to a Swarm they are in | ✓ | ✓ | ✓ | ✓ (as today) |
+| Rename the Workspace, transfer or delete it | ✓ | – | – | – |
+
+- **Deny by default.** Admins and owners manage people and Swarm metadata; they do **not** read a Swarm, a chat or a
+ Private project they are not in. Reading always needs the Swarm's own membership.
+- **Swarm roles stay.** Inside a Swarm a person is owner, collaborator or viewer, as today. A guest is never a
+ Swarm's owner.
+- **Workspace visibility of a Swarm:** `invite-only` (default, today's behavior) or `workspace` (every member and above sees its
+ name and can join it). Guests never see a Swarm they were not added to.
+- **Joining a Swarm from outside the Workspace** (an email invitation, a shared link or an email domain) also adds the person
+ to its Workspace as a **guest**, never higher. A domain join is limited to the Workspace that owns the Swarm.
+- **Removing someone from a Workspace** removes them from every Swarm of that Workspace (see Concurrency).
+- **Exactly one owner.** Ownership transfers only to an admin, at once (ruling while building: an admin is already
+ trusted, so no accept step; the old owner stays an admin).
+
+## Shown on each platform
+
+- **Desktop:** a Workspace menu at the top of the Swarm sidebar shows the current Workspace's name. It opens to the person's
+ Workspaces, each with its Swarms, then **Workspace settings** (people and roles, for owners and admins) and **New Workspace**.
+ Picking a Swarm opens its tab, as today. The tab bar keeps the Swarm tabs the person has opened, each with its
+ Workspace's name on hover. Cmd-S creates the new Swarm in the current Workspace.
+- **Web (account pages):** Workspace settings: people, roles, invitations, Workspace visibility of each Swarm. No Swarm
+ chat on the web in this version.
+- **Phone:** Swarm Home shows the Workspace's name over its projects and a switch when the person has more than one
+ Workspace. Tony decides the layout; the API is ready with the backend.
+- **CLI:** `harness super-tab workspaces` lists Workspaces and their Swarms. Commands by Swarm id keep working.
+
+## Design (docs/feature-design-rules.md)
+
+Reviewed revision: ______ Reviewer (another engine): ______
+
+1. **Growth.** Lifecycle, no empty cells:
+
+ | Record | Create | Update | Leave / removed | Delete | Purge | Recreated under the same key |
+ |---|---|---|---|---|---|---|
+ | SwarmWorkspace | New Workspace; migration; first Swarm created by a person with no Workspace | rename, `revision`+1 | – | owner deletes: only with no live Swarm; `deletedAt` | 30 days after `deletedAt` | ids are random, never reused |
+ | SwarmWorkspaceMember | invitation accepted; joining a Workspace Swarm; migration | role change, `version`+1 | `removedAt` set, Swarm removals follow | with its Workspace | 30 days after `removedAt` | rejoin writes a new `generation`, so old receipts and deliveries stay refused (the D12 rule) |
+ | SwarmWorkspaceRemoval | a removal from the Workspace | `finishedAt` once every Swarm of the Workspace is left | – | – | 30 days after `finishedAt` | keyed by the removed generation, so each removal is its own record |
+ | SwarmWorkspaceInvitation | invite | resend moves `expiresAt` | accepted or revoked: deleted | – | at `expiresAt` | a new invitation per send |
+ | SuperTab.workspaceId | Swarm create; migration | never (no moves in this version) | – | with the Swarm, as today | as today | – |
+
+ Readers of "all": the people list and the Workspace's Swarm list skip `removedAt` and `deletedAt`; the purge sweep
+ joins `sweeps.ts`. Without the purge, removed people grow by one small document per removal: nothing breaks
+ before about a million in one Workspace.
+
+2. **Concurrency.** A Workspace write locks one document: a role change or removal locks that person's
+ `SwarmWorkspaceMember` (version compare); a Workspace rename locks `SwarmWorkspace`. Invariants and their keepers:
+ - *A removed person never acts again in a Workspace Swarm.* Every Swarm read and command reads the caller's
+ `SwarmWorkspaceMember` in its transaction (`store.actor()`), so every request that starts after the removal commits is
+ refused. The person then leaves each Swarm of the Workspace through the existing leave (`member.remove` of
+ themselves), one Swarm transaction each, which writes their `SwarmMember` part; the hourly sweep finishes any
+ that failed, paging through every open removal record (`SwarmWorkspaceRemoval`) in id order. Nobody is brought back
+ into the Workspace while a removal of theirs is open: accepting an invitation finishes it first, or is refused, so
+ a Swarm the removal failed to leave never opens to them again under a new membership (review of #1811). Built: a request already in flight when the removal commits may still finish, the same window
+ as a request that arrived a moment earlier (ruling while building: touching every Swarm's member part in the
+ removal's transaction needs a write the parts layer has no no-op for).
+ - *Exactly one owner:* transfer writes both members in one transaction.
+ - *A guest is never a Swarm owner:* checked in Swarm ownership transfer and in Workspace role changes (demoting a
+ Swarm owner to guest is refused until that Swarm has another owner).
+ - *A machine serves teammates' work for one Workspace* (see Audience): checked in `teamWorkCheck`, which every start,
+ assignment, Reviewer add and route already passes through.
+ - Sweeps, liveness checks and machine reports act as the machine, not as a person, and do not read Workspace roles;
+ cleanup after a removal is the only Workspace sweep.
+ - Thin end-to-end slice before the build splits: two Workspaces, one person in both, a removal racing a post.
+
+3. **Read cost.**
+ - Every Swarm read and command: one point read of `SwarmWorkspaceMember` by `_id` (about 300 bytes loaded, nothing
+ sent), in `store.actor()`; the Workspace id comes from the head part already loaded. Tested by counting database
+ reads in the read fixture (`read/fixture.test-support.ts`).
+ - Workspaces list (Desktop menu, phone, CLI): the person's `SwarmWorkspaceMember` rows by `userId`, their Workspaces, and the
+ Swarms each shows them. At 10 Workspaces × 10 Swarms: about 3 KB sent, about 40 KB loaded. The Swarm list adds
+ `workspaceId` to each row (about 30 bytes).
+ - People list: one Workspace's members, 60 at 10x, about 12 KB, paged at 200.
+ - Removals reach readers: a removed person's next read is refused (`WORKSPACE_ACCESS_REVOKED`), and the Swarm's
+ own people see the existing person-removal change. The Workspaces list carries a `revision` per Workspace, so a client
+ learns that a Workspace or Swarm left its list.
+
+4. **Scale.** Today: 1 real Workspace (6 people, 1 main Swarm, about 25 agents). At 10x: 60 people per Workspace, 10 Swarms
+ per Workspace, 10 Workspaces per person. The membership point read stays one indexed read. The removal transaction touches
+ at most a Workspace's Swarm count of parts; first warning: the 95th percentile of that transaction's duration and the
+ count of Swarms per Workspace, logged on each removal. A Workspace over 100 Swarms makes removal batch across
+ transactions (the cleanup sweep already does). Measured on the thin slice: the read-count test, and the removal
+ timing with 10 Swarms.
+
+5. **Compatibility.** New fields: `SuperTab.workspaceId`, and `workspaceId` / `workspaceName` on Swarm list rows.
+ - Old Desktop and phone ignore the new list fields and show every Swarm as today. No Workspace menu, no break.
+ - Old CLI (`harness super-tab`) addresses Swarms by id; nothing changes for it.
+ - An old client creating a Swarm (no `workspaceId`) creates it in the person's default Workspace: their own owned Workspace, made
+ on first need. That is what Swarm creation does today.
+ - A person removed from a Workspace gets `WORKSPACE_ACCESS_REVOKED` (403) on an old client, which already shows a 403
+ Swarm as unavailable.
+ - During a rolling deploy, an old backend serving a Swarm ignores `workspaceId` and serves it by Swarm membership, as
+ today; the only gap is a removal whose Swarm cleanup has not run, which the removal's own transaction closes
+ by finishing the cleanup before it answers when there are 10 Swarms or fewer.
+ - Existing readers of `SuperTab` rows (from a search of `superTab.find*`/`update*` outside tests):
+ `store.ts` (row, list, invitations, create, host grids), `read/service.ts` (list, row), `read/host.ts` (host
+ changes: by machine, unchanged), `sweeps.ts` (unchanged), `migration/*` (state-parts migration: carries `workspaceId`
+ over), `parts/commit.ts` (writes the row; keeps `workspaceId`). The build re-runs this search and adds one line per
+ reader to the PR.
+
+6. **Migration and rollback.**
+ - Order: (1) deploy the backend that reads `workspaceId` when present and creates Workspaces for new Swarms; (2) run the
+ migration; (3) turn on `SWARM_WORKSPACES_REQUIRED`, after which a Swarm without `workspaceId` is refused, then (4) release
+ Desktop with the Workspace menu. Steps 2 and 3 on production only with Ken's go.
+ - Migration, additive: one Workspace per Swarm owner, named after their Swarm when they own one, else "Name's workspace".
+ The owner becomes the Workspace's owner. Everyone else in that owner's Swarms becomes a **guest**: they see exactly
+ what they see today, and the owner promotes people in Workspace settings. It writes `workspaceId` on each Swarm and creates
+ documents; it changes nothing that exists. Idempotent: ids are derived from the owner, so a second run finds
+ them.
+ - Rollback: the previous release ignores `workspaceId` and the three new collections, and serves every Swarm by Swarm
+ membership, as today. Workspace-visible joins made meanwhile are ordinary Swarm memberships and stay valid. A guest's
+ limits are not enforced by the old release, but a guest there has exactly a Swarm member's rights, as today.
+ Removals finish their Swarm cleanup before answering, so nobody removed regains a Swarm. Undo of the
+ migration: unset `workspaceId`, drop the three collections.
+ - Production data check: an isolated restore of the production backup before the branch merges, or Ken's no plus
+ read-only anomaly queries: Swarms without an owner in `people`, people in Swarms of several owners, and
+ sessions registered in Swarms of two owners.
+
+7. **Audience: the server enforces it.** One predicate, `workspaceAccess(tx, user, state, actor)`, called in
+ `store.actor()`, where every person and agent path already resolves its caller: commands, the read API's
+ parts, changes, groups and leaderboard, messages, mentions, decisions, starts, uploads, terminals, deliveries and
+ GitHub tokens. For a person it checks the person; for an agent, both the machine's owner and the agent's
+ contributor. Where private data can end up, and the guard:
+ - API reads, change feeds, dormant stubs: through `store.actor()`; a test per route that a person of Workspace A gets
+ 404 for a Swarm of Workspace B, and `WORKSPACE_ACCESS_REVOKED` after removal. Host routes (by machine) serve only a
+ machine's own pools and starts, as today; a removed person's contributions leave with the removal.
+ - Swarm and Workspace lists, invitations: filtered by the person's `SwarmWorkspaceMember` rows and role; guests see only their
+ own Swarms.
+ - Notifications, mentions, morning digest, phone push: built from Swarm membership; the digest and push skip a
+ person whose Workspace membership is removed (a test each).
+ - Agents' terminals and scrollback: delivered only inside a Swarm, as today; removal stops the removed person's
+ agents through the existing person-removal path.
+ - Shares (`mayOpenShare`) of a Swarm agent: also require the opener's Workspace membership. For an agent, the check is
+ on its contributor, not its machine's owner, who need not be in the Swarm today either.
+ - The same session in another Swarm: `SuperTabSessionScope` already keeps a confidential session to one Swarm; see
+ the next line for sessions in Swarms of two Workspaces.
+ - **The same machine for two Workspaces:** a Team account runs every teammate's work as one macOS user, so Workspace A's
+ agents could read Workspace B's worktrees there. A machine contributed to Swarms of two Workspaces takes teammates' work
+ in neither (`MACHINE_IN_OTHER_WORKSPACE`, and routing leaves it out with that reason) until it leaves one; its owner's
+ own projects run as the owner in any Workspace, as today. Ruling while building: neither Workspace wins, so nothing
+ depends on which was first; the migration's dry run lists such machines first. This also covers a teammate's
+ session in Swarms of two Workspaces, since teammates' sessions run in the Team account; a person's own session in two
+ Workspaces is their own choice, and is not refused.
+ - Logs and stored observations: Workspace ids and roles only, no emails in logs.
+ - A rolled-back release: see 6; it shows no more than today.
+
+8. **Identity.** Workspace actions are always the signed-in person's. A Team session (the macOS Team account) and an agent can
+ never change a Workspace, its people or roles: refused with `TEAM_SESSION_LIMITED` / 403. Agents keep running as their
+ contributor's grant, as today, and a machine's Team account never stands in for a person.
+
+9. **Failure.**
+ - A removal whose Swarm cleanup fails: the person is refused at once by the predicate; the cleanup sweep retries,
+ and owners and admins see "Removing from 1 Swarm…" in Workspace settings until it finishes.
+ - The last owner leaving: refused with a sentence asking to transfer first.
+ - Deleting a Workspace with Swarms in it: refused with the count.
+ - A refused join or invitation (guest limit, domain of another Workspace) says why in the dialog.
+ - A start refused by `MACHINE_IN_OTHER_WORKSPACE` fails with that reason in the group, and the route leaves the
+ machine out with the reason, as `teamWorkCheck` already does.
+
+10. **Platforms.** Backend (all clients). Desktop on macOS, Windows and Linux: the same Workspace menu. Web: Workspace
+ settings only. Phone: Workspace name and switch on Swarm Home, laid out by Tony. CLI: a Workspaces list. The
+ one-Workspace-per-machine rule concerns Team accounts, which are macOS only; dedicated agent machines (Linux, Windows)
+ follow the same rule.
+
+Review again when a Workspace passes 100 Swarms or 1,000 people, or when a cross-Workspace read needs a second patch.
+
+## Build, after approval
+
+1. Backend model and migration (red first): `SwarmWorkspace`, `SwarmWorkspaceMember`, `SwarmWorkspaceInvitation`, `SuperTab.workspaceId`;
+ create puts a new Swarm in a Workspace; the migration and its rollback, with a test on a fixture of today's Swarms.
+2. Permission checks: `workspaceAccess` in `store.actor()`, the lists, the digest, push and shares; one cross-Workspace test per
+ read path and per command family; the removal cascade with the in-flight race test.
+3. Workspace commands and API: create, rename, invite, accept, role change, remove, transfer, Workspace visibility, Workspaces list.
+4. Machine rule: one Workspace per machine for teammates' work, in `teamWorkCheck`.
+5. Desktop: Workspace menu and Workspace settings (`desktop/lib/super_tabs/`), CLI `harness super-tab workspaces`.
+
+## Open questions for the Product Manager
+
+1. Migrated people as **guests** (no new visibility; the owner promotes) or as **members** (they see the Workspace's
+ people list at once)? Recommended: guests.
+2. Name: decided. **Workspace** on screen and `workspace` in code (Ken, 2026-10-28); `team` keeps meaning the macOS Team account.
+3. Workspace visibility of a new Swarm: `invite-only` by default, as today? Recommended: yes.