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.

Merge batch 11-05 i1310: #3082 (#3106)

0xken15167e6f09fc85
diff --git a/backend/scripts/swarm-project-owners/migrate.ts b/backend/scripts/swarm-project-owners/migrate.ts
new file mode 100644
index 000000000..272e72927
--- /dev/null
+++ b/backend/scripts/swarm-project-owners/migrate.ts
@@ -0,0 +1,37 @@
+/**
+ * Gives every project from before ownerGeneration its owner's membership, and passes on each project whose owner already
+ * left (src/superTabs/migration/projectOwners.ts, task #3073). A dry run unless --apply: it prints each project it would
+ * fill and each handover (Swarm, project, old and new owner id; never a project's name), and writes nothing. Run
+ * right after the backend that knows ownerGeneration is deployed; production only with the owner's go. A second run finds
+ * nothing to do; a Swarm that failed (a command changed it meanwhile) is listed and taken again by the next run.
+ *
+ * DATABASE_URL=… node --import tsx scripts/swarm-project-owners/migrate.ts [--apply]
+ */
+import { parseArgs } from 'node:util'
+import { PrismaClient } from '@prisma/client'
+import { migrateProjectOwners } from '../../src/superTabs/migration/projectOwners.js'
+
+const USAGE = 'Usage: DATABASE_URL=… node --import tsx scripts/swarm-project-owners/migrate.ts [--apply]'
+/** The options, or null for anything else: an unknown flag or a positional. */
+function options(): { apply: boolean } | null {
+ try {
+ const { values } = parseArgs({ options: { apply: { type: 'boolean' } }, strict: true, allowPositionals: false })
+ return { apply: !!values.apply }
+ } catch {
+ return null
+ }
+}
+const parsed = options()
+if (!parsed || !process.env.DATABASE_URL) {
+ console.error(USAGE)
+ process.exit(2)
+}
+const db = new PrismaClient()
+try {
+ const report = await migrateProjectOwners(db, { apply: parsed.apply })
+ console.log(JSON.stringify(report, null, 2))
+ if (!report.apply) console.log(`Dry run: ${report.filled.length} projects would be filled and ${report.handovers.length} passed on. Nothing was written; add --apply to write them.`)
+ if (report.failed.length) process.exitCode = 1
+} finally {
+ await db.$disconnect()
+}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 08ad693e8..9ee891804 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -46,7 +46,7 @@ import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged }
import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, setTimeZone, statusSchema, type AvatarUpload } from './profile.js'
import { cancelledTags, cancelReason, switchExpired, unfinishedWork } from './tidy.js'
import { namedDefault } from './catalog.js'
-import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deleteProject, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
+import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deletableProject, deleteProject, markConfidential, onTeamAccount, ownsProject, admitPerson, dismissPeople, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
import { recordClosing, sessionClosed } from './closedAgents.js'
import { declinedWith, declinedWithout } from './sharing.js'
import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'
@@ -698,7 +698,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
fail('BUDDY_CHAT_EARLIER', 'This is an earlier chat, kept to read. Talk to your Buddy in # buddy.', 403)
}
}
- if ('projectId' in command && command.projectId) readProject(state, actor, command.projectId)
+ // A project nobody owns is the Swarm owner's to delete though they read nothing of it: its delete checks that (deletableProject).
+ if ('projectId' in command && command.projectId && command.type !== 'project.delete') readProject(state, actor, command.projectId)
if ('agentId' in command) readAgent(state, actor, command.agentId)
if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)
if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
@@ -880,7 +881,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const lost = new Set((context.workspaceLost ?? []).filter(id => id !== state.ownerId))
if (lost.size) {
const emails = new Set(state.people.filter(p => lost.has(p.id)).map(p => p.email))
- state.people = state.people.filter(p => !lost.has(p.id))
+ dismissPeople(state, lost)
state.invitations = state.invitations.filter(i => !emails.has(i.email))
}
result.restored = true
@@ -895,7 +896,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (invite.expiresAt <= context.now) fail('EXPIRED', 'This invitation expired.', 410)
const existing = state.people.find(p => p.id === actor.userId)
if (!existing) {
- state.people.push({ id: actor.userId, email: invite.email, role: invite.role, generation: invite.id })
+ // A project from before ownerGeneration whose owner left is settled before they come back, never matched to them again.
+ admitPerson(state, { id: actor.userId, email: invite.email, role: invite.role, generation: invite.id })
}
state.invitations = state.invitations.filter(i => i.id !== invite.id)
// Back on purpose: auto-join may add them again if they leave and the owner invites them once more (spec, Leaving is final).
@@ -1595,7 +1597,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const project = readProject(state, actor, command.projectId)
author(state, actor, true)
const group = conversation(state, project.leadConversationId)
- if (!(actor.kind === 'person' && actor.userId === project.ownerId) && !(actor.kind === 'agent' && group.leadId === actor.agentId)) {
+ if (!(actor.kind === 'person' && ownsProject(state, actor.userId, project)) && !(actor.kind === 'agent' && group.leadId === actor.agentId)) {
fail('PROJECT_OWNER_REQUIRED', 'Only the project owner or its lead can share its repository.', 403)
}
// On a tab from before projects this is `state.project` itself (projectsOf).
@@ -1613,7 +1615,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (projects.length >= 100) fail('PROJECTS_FULL', 'A swarm can have up to 100 projects.')
const leadConversationId = `project-${operationId}`
// It starts on a copy of the built-in instructions as revision 1, the team's own to change (design, The built-in template).
- projects.push({ id: operationId, name: command.name, ownerId: actor.userId, leadConversationId,
+ projects.push({ id: operationId, name: command.name, ownerId: actor.userId, ownerGeneration: person(state, actor.userId).generation, leadConversationId,
visibility: command.visibility, members: [], updateMinutes: 5, skillMode: 'default', ...FIRST_INSTRUCTIONS })
effects.instructions = { projectId: operationId, revision: 1, hash: FIRST_INSTRUCTIONS.instructionsHash, text: INSTRUCTIONS_TEMPLATE,
summary: FIRST_SUMMARY, writtenBy: { kind: 'person', id: actor.userId }, askedBy: actor.userId, at: context.now }
@@ -1673,7 +1675,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// On its machine: the project's owner, or the owner of the machine the PM runs on (not whoever contributed it: a lent
// machine's borrower). To another machine: only the project's owner, as a new PM start (security reviews of #2705).
const moving = command.machineId !== undefined && command.machineId !== pm?.machineId
- if (!moving && pm?.machineOwnerId === actor.userId && actor.userId !== project.ownerId) author(state, actor, true)
+ if (!moving && pm?.machineOwnerId === actor.userId && !ownsProject(state, actor.userId, project)) author(state, actor, true)
else manageProject(state, actor, project.id)
const name = coordinatorNameOf(project)
if (!pm || !pool) fail('NO_LEAD', `This project has no running ${name}.`)
@@ -1735,8 +1737,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
case 'project.delete': {
// Its owner confirmed a permanent delete, so the project takes its own agents with it, its Lead included, and their
- // hosts close their sessions.
- const project = manageProject(state, actor, command.projectId)
+ // hosts close their sessions. The Swarm's owner deletes one nobody owns (task #3073).
+ const project = deletableProject(state, actor, command.projectId)
// Read before its agents go: a contributed start still settling whose agent is already gone never settles (projects.ts).
const orphaned = new Set((state.starts ?? []).filter(s => s.poolGeneration && s.harnessId && !s.poolSettled && !s.error
&& !state.agents.some(a => a.machineId === s.request.machineId && a.harnessId === s.harnessId)).map(s => s.id))
@@ -2216,7 +2218,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// Its requester may close it once it is lost or stopped (work.cancel), so among people only an owner names who asked;
// anyone else could name themselves and cancel a task they never asked for (security review 2 of #2907). Agents name
// the person they opened it for, as before.
- if (actor.kind === 'person' && ![state.ownerId, groupProject(state, group).ownerId].includes(actor.userId)) {
+ if (actor.kind === 'person' && actor.userId !== state.ownerId && !ownsProject(state, actor.userId, groupProject(state, group))) {
fail('FORBIDDEN', 'Among people, only the Swarm owner or the project\'s owner names who asked for a task.', 403)
}
if (command.personId) group.requesterId = requester(state, groupProject(state, group), command.personId)
@@ -2247,8 +2249,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const group = conversation(state, command.conversationId)
// It awards points, so among people only an owner records it; reading the group is not enough. Any agent of the
// project may (project instructions, phase 4), on any task, a linked one included.
- const owners = [state.ownerId, groupProject(state, group).ownerId]
- if (actor.kind === 'person' && !owners.includes(actor.userId)) fail('FORBIDDEN', 'Among people, only an owner records a merge.', 403)
+ if (actor.kind === 'person' && actor.userId !== state.ownerId && !ownsProject(state, actor.userId, groupProject(state, group))) fail('FORBIDDEN', 'Among people, only an owner records a merge.', 403)
const mergedAt = command.mergedAt === undefined ? context.now : Date.parse(command.mergedAt)
if (mergedAt > context.now || mergedAt <= context.now - (LEDGER_WEEKS - 1) * WEEK_MS) {
fail('MERGE_TIME', 'Record a merge from the last four weeks, not one still to come.', 400)
@@ -3195,7 +3196,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
for (const target of state.agents.filter(a => a.contributorId === member.id || a.buddyOf?.personId === member.id)) {
if (state.agents.some(a => a.id === target.id)) removeAgent(target)
}
- state.people = state.people.filter(p => p.id !== member.id)
+ // Their projects pass to a remaining member, or are nobody's: rejoining gives none of them back (task #3073).
+ dismissPeople(state, new Set([member.id]))
state.invitations = state.invitations.filter(i => i.email !== member.email)
// Leaving, or being removed, is final for auto-join: only an invitation or a link brings them back (spec 2026-11-03).
state.autoJoinDeclined = declinedWith(state, member.id)
@@ -3655,7 +3657,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// good where most people are not the Swarm owner (Diego, 2026-11-04, #2639). Live work stays the project's agents' and
// the Swarm owner's.
const ended = lost || stopped || assignment.status === 'cancelled'
- const closes = ended && actor.kind === 'person' && [group.requesterId, project.ownerId].includes(actor.userId)
+ const closes = ended && actor.kind === 'person' && (actor.userId === group.requesterId || ownsProject(state, actor.userId, project))
if (!allowed && !closes) fail('FORBIDDEN', ended ? WHO_CANCELS_ENDED : WHO_CANCELS_LIVE, 403)
// A retry after the cancel keeps the first reason and tells the worker once.
if (assignment.status === 'cancelled') break
@@ -3715,7 +3717,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// now, not the task's lead: a replaced PM's removal clears its lead on every task it led (review of #2916).
const project = groupProject(state, group)
const accountable = actor.kind === 'agent' ? ledProject(state, actor.agentId)?.id === project.id
- : [state.ownerId, project.ownerId].includes(actor.userId)
+ : actor.userId === state.ownerId || ownsProject(state, actor.userId, project)
const departed = (key: string) => key.startsWith('agent:') ? !state.agents.some(a => `agent:${a.id}` === key)
: key.startsWith('person:') && !state.people.some(p => `person:${p.id}` === key)
const name = actor.kind === 'agent' ? agentDisplayName(state.agents, actor.agentId) ?? agent(state, actor.agentId).name : actor.email
diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.ts
index 801b0e512..74bb9004a 100644
--- a/backend/src/superTabs/leadStart.ts
+++ b/backend/src/superTabs/leadStart.ts
@@ -7,7 +7,7 @@
import { admitMachineStart, contributedEngines, failTeamWork, machineContribution, projectFolder, projectsOnMachine, teamAccountPool, teamPoolOf,
slotCounter, teamWorkRefusal, ownAccountWork, type ContributedMachine } from './machines.js'
import { actorKey, fail, person, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'
-import { BUILT_IN_ROLE_DEFAULTS, projectsOf, type SwarmProject } from './projects.js'
+import { BUILT_IN_ROLE_DEFAULTS, ownsProject, projectsOf, type SwarmProject } from './projects.js'
import { failureNotice, publicReason } from './startFailure.js'
import { coordinatorNameOf } from './instructions.js'
@@ -98,7 +98,7 @@ export function leadHost(state: SuperTabState, project: SwarmProject, machineId:
const refusal = (pool: ContributedMachine) => teamWorkRefusal(pool, context.now, teamMachines.includes(pool.machineId), true,
(context.otherWorkspaceMachines ?? []).includes(pool.machineId))
let candidates: ContributedMachine[]
- if (named.contributorId === project.ownerId) candidates = [named]
+ if (ownsProject(state, named.contributorId, project)) candidates = [named]
else if (teamAccountPool(named)) {
if (!teamsWork) fail('TEAM_ACCOUNT_REQUIRED', `Harness Team accounts take no work in this Swarm yet, so ${named.name} runs only its owner's projects.`, 403)
const why = refusal(named)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index f9b47eb1f..5ab585f50 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -5,7 +5,7 @@ import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'
import { activeWork, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'
import { WORKSPACE_LABEL } from './workspaces.js'
import { startFinished } from './parts/write.js'
-import { agentProjectId, canReadAgent, canReadProject, groupProject, ledProject, projectOf, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'
+import { agentProjectId, canReadAgent, canReadProject, groupProject, ledProject, ownsProject, projectOf, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'
import { isSwarmBuddyChat } from './buddies.js'
export { teamAccountPool } from './projects.js'
import { conversation } from './model.js'
@@ -375,8 +375,8 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contribut
const pool = state.machines?.find(m => m.machineId === machineId)
// A Buddy-only machine is its person's alone: an agent they added there takes their own projects' work and no other's,
// whatever the Team account switches say (security re-check 1 of #2234). New starts there are refused in admitMachineStart.
- if (pool?.buddyOnly) return project.ownerId === pool.contributorId ? null : { code: 'NOT_SWARM_MACHINE', reason: NOT_SWARM_MACHINE }
- if (project.ownerId === contributorId) return null
+ if (pool?.buddyOnly) return ownsProject(state, pool.contributorId, project) ? null : { code: 'NOT_SWARM_MACHINE', reason: NOT_SWARM_MACHINE }
+ if (ownsProject(state, contributorId, project)) return null
if (!pool) {
// Off the Machines list nothing reports a team account (store.ts teamMachines), so this is the switch alone.
if (!teamAccountRequired()) return null
@@ -502,7 +502,7 @@ export function teamMachineFor(state: SuperTabState, machineId: string, project:
if (idle) return machineId
const pool = state.machines?.find(m => m.machineId === machineId)
// [teamWritten]: code a Team agent wrote takes the Team account even in its owner's own project (teamWritten.ts, audit H2).
- if (!pool || (!teamWritten && project.ownerId === pool.contributorId)) return machineId
+ if (!pool || (!teamWritten && ownsProject(state, pool.contributorId, project))) return machineId
if (!teamWritten && ownAccountWork(pool)) return machineId
return teamPoolOf(state, pool, live)?.machineId ?? machineId
}
diff --git a/backend/src/superTabs/migration/projectOwners.test.ts b/backend/src/superTabs/migration/projectOwners.test.ts
new file mode 100644
index 000000000..f9d3ea146
--- /dev/null
+++ b/backend/src/superTabs/migration/projectOwners.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import { createSuperTab, type SuperTabState } from '../model.js'
+import type { SwarmProject } from '../projects.js'
+import { ownersPlan } from './projectOwners.js'
+
+// Task #3073: projects from before ownerGeneration get their owner's membership, and those whose owner already left pass on.
+const project = (id: string, ownerId: string, extra: Partial<SwarmProject> = {}): SwarmProject =>
+ ({ id, name: id.toUpperCase(), ownerId, leadConversationId: `project-${id}`, visibility: 'private', members: [], updateMinutes: 5, ...extra })
+
+function legacy(): SuperTabState {
+ const state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ state.people.push({ id: 'c', email: '[email protected]', role: 'collaborator', generation: 'c-first' })
+ state.projects = [
+ { ...project('lead', 'owner'), visibility: 'public' },
+ project('stayed', 'c'),
+ project('handed', 'gone', { members: [{ id: 'c', generation: 'c-first' }] }),
+ project('orphan', 'gone'),
+ { ...project('open', 'gone'), visibility: 'public' },
+ ]
+ return state
+}
+
+describe('the migration of project owners', () => {
+ it('fills the membership of owners still in the Swarm and changes nothing else of theirs', () => {
+ const plan = ownersPlan(legacy())
+ expect(plan.projects.find(p => p.id === 'lead')).toEqual({ ...project('lead', 'owner'), visibility: 'public', ownerGeneration: 'swarm' })
+ expect(plan.projects.find(p => p.id === 'stayed')).toEqual({ ...project('stayed', 'c'), ownerGeneration: 'c-first' })
+ expect(plan.filled).toEqual([{ projectId: 'lead', ownerId: 'owner' }, { projectId: 'stayed', ownerId: 'c' }])
+ })
+
+ it('passes on each project whose owner already left: to a member, the Swarm owner for a public one, else nobody', () => {
+ const plan = ownersPlan(legacy())
+ expect(plan.handovers).toEqual([
+ { projectId: 'handed', from: 'gone', to: 'c' },
+ { projectId: 'orphan', from: 'gone', to: '' },
+ { projectId: 'open', from: 'gone', to: 'owner' },
+ ])
+ expect(plan.projects.find(p => p.id === 'handed')).toMatchObject({ ownerId: 'c', ownerGeneration: 'c-first', members: [] })
+ expect(plan.projects.find(p => p.id === 'orphan')!.ownerId).toBe('')
+ })
+
+ it('finds nothing to do on a second run', () => {
+ const state = legacy()
+ state.projects = ownersPlan(state).projects
+ expect(ownersPlan(state)).toMatchObject({ filled: [], handovers: [], changed: false })
+ })
+
+ it('leaves a Swarm from before projects alone: its one project is the Swarm owner\'s, who never leaves', () => {
+ const state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ delete state.projects
+ expect(ownersPlan(state)).toMatchObject({ filled: [], handovers: [], changed: false })
+ })
+
+ it('never changes the state it plans from', () => {
+ const state = legacy(), before = structuredClone(state)
+ ownersPlan(state)
+ expect(state).toEqual(before)
+ })
+})
diff --git a/backend/src/superTabs/migration/projectOwners.ts b/backend/src/superTabs/migration/projectOwners.ts
new file mode 100644
index 000000000..8c72f978d
--- /dev/null
+++ b/backend/src/superTabs/migration/projectOwners.ts
@@ -0,0 +1,76 @@
+/**
+ * Gives every project from before ownerGeneration its owner's membership, and passes on each project whose owner already
+ * left (task #3073, projects.ts settleOwners). Never run by the server: scripts/swarm-project-owners/migrate.ts runs it, a
+ * dry run unless `--apply`, right after the backend that knows ownerGeneration is deployed. Until then such a project's owner
+ * matches by id, as before; member.remove and invite.accept settle a Swarm's projects themselves.
+ *
+ * Rollback: the backend before it ignores ownerGeneration. A handover is not undone: undoing it gives a project back to an
+ * owner who left. The report lists each one (Swarm, project, old and new owner id) as its record. A second run finds
+ * nothing to do; a Swarm that failed (a command changed it meanwhile) is listed and taken again by the next run.
+ */
+import type { Prisma, PrismaClient } from '@prisma/client'
+import { clock, guardedWrite, loadAll, reassemble } from '../parts/index.js'
+import { swarmTransaction } from '../cache.js'
+import type { SuperTabState } from '../model.js'
+import { settleOwners, type SwarmProject } from '../projects.js'
+
+type Transaction = Prisma.TransactionClient
+const TRANSACTION = { maxWait: 5_000, timeout: 60_000 }
+
+export interface ProjectOwnersReport {
+ apply: boolean
+ swarms: number
+ /** Projects whose owner, still in the Swarm, got their membership: an owner who left and came back before the deploy is
+ * filled at their new membership (nothing stored tells them apart), so each is listed to be checked. Ids only. */
+ filled: Array<{ tabId: string; projectId: string; ownerId: string }>
+ /** Projects that passed on: to a member's or the Swarm owner's id, or '' when nobody owns them now. Ids only, never names. */
+ handovers: Array<{ tabId: string; projectId: string; from: string; to: string }>
+ skipped: string[]
+ failed: Array<{ tabId: string; error: string }>
+}
+
+/** What settling [state]'s projects would change, on a copy: [state] is left as it was. A Swarm from before projects has
+ * one, the Swarm owner's, who never leaves: nothing to do. */
+export function ownersPlan(state: SuperTabState): { projects: SwarmProject[]; filled: Array<{ projectId: string; ownerId: string }>; handovers: Array<{ projectId: string; from: string; to: string }>; changed: boolean } {
+ if (!state.projects) return { projects: [], filled: [], handovers: [], changed: false }
+ const copy = structuredClone(state)
+ const unfilled = new Set(copy.projects!.filter(p => p.ownerGeneration === undefined).map(p => p.id))
+ const handovers = settleOwners(copy)
+ const moved = new Set(handovers.map(h => h.projectId))
+ const filled = copy.projects!.filter(p => unfilled.has(p.id) && !moved.has(p.id) && p.ownerGeneration !== undefined)
+ .map(p => ({ projectId: p.id, ownerId: p.ownerId }))
+ return { projects: copy.projects!, filled, handovers, changed: filled.length > 0 || handovers.length > 0 }
+}
+
+/** Settles one Swarm's projects in [tx], writing its head guarded by the version it read: a command in between wins, and the
+ * Swarm is failed and retried on the next run. A handover moves the visibility epoch, so every reader reloads once. */
+async function settleSwarm(tx: Transaction, tabId: string, apply: boolean) {
+ const parts = await loadAll(tx, tabId)
+ const plan = ownersPlan(reassemble(parts) as SuperTabState)
+ if (apply && plan.changed) {
+ const projects = plan.projects.map(({ progress: _progress, ...project }) => project)
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'head', key: 'head', seen: parts.head.version, data: { ...parts.head.data!, projects },
+ head: { groupCounter: parts.groupCounter, visibilityEpoch: parts.visibilityEpoch + (plan.handovers.length ? 1 : 0), sequenceBase: parts.sequenceBase } },
+ clock.next())
+ }
+ return plan
+}
+
+export async function migrateProjectOwners(db: PrismaClient, opts: { apply: boolean }): Promise<ProjectOwnersReport> {
+ const report: ProjectOwnersReport = { apply: opts.apply, swarms: 0, filled: [], handovers: [], skipped: [], failed: [] }
+ const rows = await db.superTab.findMany({ select: { id: true, format: true }, orderBy: { id: 'asc' } })
+ for (const row of rows) {
+ if (row.format !== 2) { report.skipped.push(row.id); continue }
+ report.swarms++
+ try {
+ const plan = opts.apply
+ ? await swarmTransaction(db, tx => settleSwarm(tx, row.id, true), TRANSACTION)
+ : await settleSwarm(db as unknown as Transaction, row.id, false)
+ report.filled.push(...plan.filled.map(f => ({ tabId: row.id, ...f })))
+ report.handovers.push(...plan.handovers.map(h => ({ tabId: row.id, ...h })))
+ } catch (error) {
+ report.failed.push({ tabId: row.id, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return report
+}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 85bf000e3..2a8d47f87 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -10,7 +10,7 @@ import { swarmUsernames } from './usernames.js'
import { downSince, expireRemovals, startPreparing } from './machines.js'
import { publicReason, readsRawReason } from './startFailure.js'
import { FIRST_INSTRUCTIONS } from './instructions.js'
-import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, groupProject, ledProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
+import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, groupProject, ledProject, ownerlessProjects, ownsProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
export type Role = 'owner' | 'collaborator' | 'viewer'
export interface Person {
@@ -479,6 +479,8 @@ export interface SuperTabState {
overlapAlerts?: string[]
/** Read-only, for a Lead's own reads (visibleState): the active work of the other projects it may know about. */
otherProjectsWork?: OtherProjectWork[]
+ /** Read-only, for the Swarm owner's reads (visibleState): the projects nobody owns, by name and size (projects.ts). */
+ ownerlessProjects?: Array<{ id: string; name: string; conversations: number }>
ownerId: string
/** The Workspace it belongs to (workspaceStore.ts); absent on a Swarm from before Workspaces until the migration gives it one. */
workspaceId?: string
@@ -926,6 +928,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
assignAgentDisplayNames(visible.agents)
const led = actor.kind === 'agent' ? ledProject(visible, actor.agentId) : undefined
if (led) visible.otherProjectsWork = otherProjectsWork(visible, led)
+ const ownerless = ownerlessProjects(state, actor)
+ if (ownerless) visible.ownerlessProjects = ownerless
for (const target of visible.agents) {
const since = downSince(state, target, now)
if (since) target.downSince = since
@@ -946,7 +950,7 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
const there = state.agents.filter(a => a.machineId === pool.machineId)
const owners = new Set(there.length ? there.map(a => a.machineOwnerId) : [pool.contributorId])
const mayMove = actor.kind === 'person' && (owners.has(actor.userId) ||
- there.some(a => projectsOf(state).some(p => p.ownerId === actor.userId && state.conversations.some(c => c.id === p.leadConversationId && c.leadId === a.id))))
+ there.some(a => projectsOf(state).some(p => ownsProject(state, actor.userId, p) && state.conversations.some(c => c.id === p.leadConversationId && c.leadId === a.id))))
if (!mayMove) delete pool.observation.profiles
}
expireRemovals(visible, now)
diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.ts
index fd140bf9a..99e0a4810 100644
--- a/backend/src/superTabs/parts/commit.ts
+++ b/backend/src/superTabs/parts/commit.ts
@@ -59,11 +59,11 @@ export function sameData(a: unknown, b: unknown): boolean {
}
/**
- * Who sees what changed (design section 4.2): a project's visibility or members, a person removed or rejoined, the set of
+ * Who sees what changed (design section 4.2): a project's visibility, owner or members, a person removed or rejoined, the set of
* Leads (the Leads conversation's members), a conversation's audience, or a project removed. Readers reload in full.
*/
export function visibilityChanged(before: SuperTabState, after: SuperTabState): boolean {
- const projects = (state: SuperTabState) => canonical((state.projects ?? []).map(p => [p.id, p.visibility, p.members]))
+ const projects = (state: SuperTabState) => canonical((state.projects ?? []).map(p => [p.id, p.visibility, p.ownerId, p.members]))
const people = (state: SuperTabState) => canonical(state.people.map(p => [p.id, p.generation, p.role]))
const leads = (state: SuperTabState) => canonical(state.conversations.filter(isLeads).map(c => c.agentIds))
const audiences = (state: SuperTabState) => new Map(state.conversations.map(c => [c.id, canonical(c.audience ?? null)]))
diff --git a/backend/src/superTabs/projectOwners.test.ts b/backend/src/superTabs/projectOwners.test.ts
new file mode 100644
index 000000000..89f34cbf8
--- /dev/null
+++ b/backend/src/superTabs/projectOwners.test.ts
@@ -0,0 +1,278 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import type { AgentStart } from './model.js'
+import { createSuperTab, visibleState, type Actor, type SuperTabState } from './model.js'
+import { admitPerson, ownerAccount, ownsProject, projectOf, projectsOf, readConversation, settleOwners } from './projects.js'
+import { teamWorkCheck } from './machines.js'
+import type { ContributedMachine } from './machines.js'
+import { visibilityChanged } from './parts/commit.js'
+
+// Task #3073 (Diego, 11-05): a private project's owner who leaves the Swarm, or is removed, loses it, and the project stays
+// manageable. Ownership is a membership (id and generation), as a project member's is, never the account id alone.
+const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const p: Actor = { kind: 'person', userId: 'p', email: '[email protected]' }
+const c: Actor = { kind: 'person', userId: 'c', email: '[email protected]' }
+const d: Actor = { kind: 'person', userId: 'd', email: '[email protected]' }
+
+function setup() {
+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ state.people.push({ id: 'p', email: '[email protected]', role: 'collaborator', generation: 'p-first' },
+ { id: 'c', email: '[email protected]', role: 'collaborator', generation: 'c-first' },
+ { id: 'd', email: '[email protected]', role: 'collaborator', generation: 'd-first' })
+ let next = 0
+ const run = (command: Command, actor = owner, context: Partial<CommandContext> = {}) => {
+ const effect = applyCommand(state, actor, command, { operationId: `op${next++}`, now: 1000,
+ contribution: { machineOwnerId: 'host', contributorId: actor.kind === 'person' ? actor.userId : 'owner' }, ...context })
+ state = effect.state
+ return effect.result
+ }
+ const create = (actor: Actor, visibility: 'private' | 'public' = 'private') =>
+ run({ type: 'project.create', name: 'X', visibility, brief: '' }, actor) as { projectId: string; conversationId: string }
+ const reads = (actor: Actor, projectId: string) => (visibleState(state, actor).projects ?? []).some(item => item.id === projectId)
+ /** Invites [actor] back to the Swarm and has them accept: a new membership of the same account. */
+ const rejoin = (actor: Extract<Actor, { kind: 'person' }>, role: 'viewer' | 'collaborator') => {
+ const invite = run({ type: 'invite.create', email: actor.email, role, conversationId: 'lead' }).inviteId as string
+ run({ type: 'invite.accept', inviteId: invite }, actor)
+ }
+ return { run, create, reads, rejoin, get state(): SuperTabState { return state }, set state(next: SuperTabState) { state = next } }
+}
+
+describe('a project owner\'s membership', () => {
+ it('is stored when the project is created', () => {
+ const f = setup(), x = f.create(p)
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'p', ownerGeneration: 'p-first' })
+ })
+
+ it('keeps an owner who stayed reading and managing their project, as today', () => {
+ const f = setup(), x = f.create(p)
+ expect(f.reads(p, x.projectId)).toBe(true)
+ expect(ownsProject(f.state, 'p', projectOf(f.state, x.projectId))).toBe(true)
+ f.run({ type: 'project.rename', projectId: x.projectId, name: 'Renamed' }, p)
+ expect(projectOf(f.state, x.projectId).name).toBe('Renamed')
+ })
+
+ it('does not let the same account at a later membership read or manage the project', () => {
+ const f = setup(), x = f.create(p)
+ // Left and came back: the same account, a new membership.
+ f.state.people.find(person => person.id === 'p')!.generation = 'p-second'
+ expect(ownsProject(f.state, 'p', projectOf(f.state, x.projectId))).toBe(false)
+ expect(f.reads(p, x.projectId)).toBe(false)
+ expect(() => f.run({ type: 'project.rename', projectId: x.projectId, name: 'Mine again' }, p)).toThrow('unavailable')
+ expect(() => f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'public', memberIds: [] }, p)).toThrow('unavailable')
+ })
+
+ it('matches by account alone for a project from before the membership was stored, until it is settled', () => {
+ const f = setup(), x = f.create(p)
+ delete projectOf(f.state, x.projectId).ownerGeneration
+ f.state.people.find(person => person.id === 'p')!.generation = 'p-second'
+ expect(ownsProject(f.state, 'p', projectOf(f.state, x.projectId))).toBe(true)
+ expect(f.reads(p, x.projectId)).toBe(true)
+ })
+
+ it('is no one\'s once its owner is not in the Swarm', () => {
+ const f = setup(), x = f.create(p)
+ f.state.people = f.state.people.filter(person => person.id !== 'p')
+ expect(ownsProject(f.state, 'p', projectOf(f.state, x.projectId))).toBe(false)
+ })
+})
+
+describe('a project whose owner leaves or is removed', () => {
+ // Diego's case, as he reported it on 1da94962a.
+ it('passes to its remaining member, and its former owner invited back reads and manages nothing of it', () => {
+ const f = setup(), x = f.create(p)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['c'] }, p)
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'c', ownerGeneration: 'c-first' })
+ // C manages it now: renames it and shares it.
+ f.run({ type: 'project.rename', projectId: x.projectId, name: 'C\'s now' }, c)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['d'] }, c)
+ expect(f.reads(d, x.projectId)).toBe(true)
+ expect(f.reads(c, x.projectId)).toBe(true)
+ f.rejoin(p, 'viewer')
+ expect(f.reads(p, x.projectId)).toBe(false)
+ expect(() => f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'public', memberIds: [] }, p)).toThrow()
+ expect(projectOf(f.state, x.projectId).visibility).toBe('private')
+ })
+
+ it('passes on the same way when its owner leaves by themselves', () => {
+ const f = setup(), x = f.create(p)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['c'] }, p)
+ f.run({ type: 'member.remove', userId: 'p' }, p)
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'c', ownerGeneration: 'c-first' })
+ f.rejoin(p, 'collaborator')
+ expect(f.reads(p, x.projectId)).toBe(false)
+ expect(() => f.run({ type: 'project.rename', projectId: x.projectId, name: 'Back' }, p)).toThrow('unavailable')
+ })
+
+ it('passes to the earliest listed member who can manage it, never a stale listing or a viewer while another can', () => {
+ const f = setup(), x = f.create(p)
+ f.state.people.push({ id: 'v', email: '[email protected]', role: 'viewer', generation: 'v-first' })
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['v', 'c', 'd'] }, p)
+ // C left and came back since: their listing is of an earlier membership.
+ f.state.people.find(person => person.id === 'c')!.generation = 'c-second'
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'd', ownerGeneration: 'd-first' })
+ // The new owner is no longer listed as a member too; the others stay as they were.
+ expect(projectOf(f.state, x.projectId).members.map(m => m.id)).toEqual(['v', 'c'])
+ })
+
+ it('passes to a viewer when only viewers remain, who still reads it', () => {
+ const f = setup(), x = f.create(p)
+ f.state.people.push({ id: 'v', email: '[email protected]', role: 'viewer', generation: 'v-first' })
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['v'] }, p)
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'v', ownerGeneration: 'v-first' })
+ })
+
+ it('passes a public project with no member listed to the Swarm owner', () => {
+ const f = setup(), x = f.create(p, 'public')
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'owner', ownerGeneration: f.state.people[0]!.generation })
+ f.run({ type: 'project.rename', projectId: x.projectId, name: 'Kept' })
+ f.rejoin(p, 'collaborator')
+ expect(f.reads(p, x.projectId)).toBe(true)
+ expect(() => f.run({ type: 'project.rename', projectId: x.projectId, name: 'Mine' }, p)).toThrow('Only the project owner')
+ })
+
+ it('leaves the projects of owners who stayed as they were', () => {
+ const f = setup(), mine = f.create(c), theirs = f.create(p)
+ f.run({ type: 'project.sharing', projectId: mine.projectId, visibility: 'private', memberIds: ['p'] }, c)
+ const before = structuredClone(projectOf(f.state, mine.projectId))
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(projectOf(f.state, mine.projectId)).toEqual(before)
+ expect(f.reads(c, mine.projectId)).toBe(true)
+ expect(projectOf(f.state, theirs.projectId).ownerId).not.toBe('p')
+ })
+
+ it('tells readers to reload when only its owner changed', () => {
+ const f = setup(), x = f.create(p)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['c'] }, p)
+ const before = structuredClone(f.state), after = structuredClone(f.state)
+ expect(settleOwners(after)).toEqual([])
+ after.people.find(person => person.id === 'p')!.generation = 'p-second'
+ before.people.find(person => person.id === 'p')!.generation = 'p-second'
+ expect(settleOwners(after)).toEqual([{ projectId: x.projectId, from: 'p', to: 'c' }])
+ expect(visibilityChanged(before, after)).toBe(true)
+ })
+})
+
+describe('a private project left with no member', () => {
+ const configuration = { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null }
+ /** P's private X, with a task worked by an agent on D's machine, and P removed by the Swarm's owner. */
+ function ownerless() {
+ const f = setup(), x = f.create(p)
+ const task = f.run({ type: 'conversation.create', projectId: x.projectId, title: 'Secret task', brief: 'Secret', checks: [] }, p).conversationId as string
+ const agentId = f.run({ type: 'agent.add', conversationId: task, harnessId: 'h', machineId: 'd-mac', name: 'Worker', configuration, lead: false }, p,
+ { contribution: { machineOwnerId: 'd', contributorId: 'd' } }).agentId as string
+ f.run({ type: 'work.assign', conversationId: task, agentId }, p)
+ f.run({ type: 'member.remove', userId: 'p' })
+ return { f, x, task, agentId }
+ }
+
+ it('is nobody\'s: not its former owner\'s back, nor the Swarm owner\'s, nor another member\'s', () => {
+ const { f, x, task } = ownerless()
+ expect(projectOf(f.state, x.projectId).ownerId).toBe('')
+ expect(projectOf(f.state, x.projectId).ownerGeneration).toBeUndefined()
+ expect(f.reads(owner, x.projectId)).toBe(false)
+ expect(f.reads(c, x.projectId)).toBe(false)
+ expect(() => readConversation(f.state, owner, task)).toThrow('unavailable')
+ expect(() => readConversation(f.state, owner, x.conversationId)).toThrow('unavailable')
+ f.rejoin(p, 'collaborator')
+ expect(f.reads(p, x.projectId)).toBe(false)
+ expect(() => readConversation(f.state, p, task)).toThrow('unavailable')
+ })
+
+ it('shows the Swarm\'s owner only that it exists, its name and size, and nobody else even that', () => {
+ const { f, x } = ownerless()
+ expect(visibleState(f.state, owner).ownerlessProjects).toEqual([{ id: x.projectId, name: 'X', conversations: 2 }])
+ expect(visibleState(f.state, c).ownerlessProjects).toBeUndefined()
+ const agent: Actor = { kind: 'agent', agentId: f.state.agents[0]!.id, machineOwnerId: 'd' }
+ expect(visibleState(f.state, agent).ownerlessProjects).toBeUndefined()
+ })
+
+ it('cannot be renamed, reshared or taken by the Swarm\'s owner', () => {
+ const { f, x } = ownerless()
+ expect(() => f.run({ type: 'project.rename', projectId: x.projectId, name: 'Mine' })).toThrow('unavailable')
+ expect(() => f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'public', memberIds: [] })).toThrow('unavailable')
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ name: 'X', visibility: 'private', ownerId: '' })
+ })
+
+ it('is deleted by the Swarm\'s owner with its chats and agents, its live work included, and by no one else', () => {
+ const { f, x, task, agentId } = ownerless()
+ expect(() => f.run({ type: 'project.delete', projectId: x.projectId }, c)).toThrow('unavailable')
+ f.run({ type: 'project.delete', projectId: x.projectId })
+ expect(projectsOf(f.state).some(item => item.id === x.projectId)).toBe(false)
+ expect(f.state.conversations.some(group => group.id === task || group.id === x.conversationId)).toBe(false)
+ expect(f.state.agents.some(a => a.id === agentId)).toBe(false)
+ expect(visibleState(f.state, owner).ownerlessProjects).toBeUndefined()
+ })
+
+ it('refuses the delete while an agent is still starting there, naming nothing in it', () => {
+ const { f, x, task } = ownerless()
+ f.state.starts = [{ id: 'start', creationId: 'start', actorKey: 'person:d', contributorId: 'd', membershipGeneration: 'd-first', machineOwnerId: 'd',
+ hostGrant: null, harnessId: null, dispatched: true, dispatchedAt: 1000, requestedAt: 1000, error: null,
+ request: { conversationId: task, name: 'Secret starter', machineId: 'd-mac' } } as unknown as AgentStart]
+ let message = ''
+ try { f.run({ type: 'project.delete', projectId: x.projectId }) } catch (error) { message = (error as Error).message }
+ expect(message).toMatch(/still starting/)
+ expect(message).not.toMatch(/Secret/)
+ })
+})
+
+// Self-review of #3082: an agent still working in a project nobody owns asks for its GitHub token or prepares a start, and the
+// store looks its owner's account up. '' is no ObjectId: Prisma throws on it (P2023), a 500, where the token is refused by name.
+describe('the account of a project\'s owner', () => {
+ const users = { findUnique: async ({ where }: { where: { id: string } }) => {
+ if (!/^[0-9a-f]{24}$/.test(where.id)) throw new Error('Malformed ObjectID')
+ return { name: 'Olive', email: '[email protected]' }
+ } }
+ it('is looked up for an owned project and is nobody for one nobody owns, without a lookup', async () => {
+ const f = setup(), x = f.create(p)
+ expect(await ownerAccount(users, { ...projectOf(f.state, x.projectId), ownerId: '200000000000000000000001' })).toEqual({ name: 'Olive', email: '[email protected]' })
+ f.run({ type: 'member.remove', userId: 'p' })
+ expect(await ownerAccount(users, projectOf(f.state, x.projectId))).toBeNull()
+ })
+})
+
+// Security reviews 1 and 2 of #3082: every way into and out of the Swarm settles its projects, not only invite.accept and
+// member.remove. A project from before ownerGeneration whose owner left is never matched to them again by a link, domain or
+// Workspace join, and a person a restore drops passes their projects on.
+describe('every way in and out of the Swarm', () => {
+ it('settles a project whose owner left before a person comes back in, by any join', () => {
+ const f = setup(), x = f.create(p)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['c'] }, p)
+ // From before ownerGeneration, its owner removed by a backend that did not settle.
+ delete projectOf(f.state, x.projectId).ownerGeneration
+ f.state.people = f.state.people.filter(person => person.id !== 'p')
+ admitPerson(f.state, { id: 'p', email: '[email protected]', role: 'collaborator', generation: 'p-link' })
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'c', ownerGeneration: 'c-first' })
+ expect(f.reads(p, x.projectId)).toBe(false)
+ expect(() => f.run({ type: 'project.rename', projectId: x.projectId, name: 'Mine' }, p)).toThrow('unavailable')
+ })
+
+ it('passes on the projects of people a restore leaves out because the Workspace lost them', () => {
+ const f = setup(), x = f.create(p), alone = f.create(p)
+ f.run({ type: 'project.sharing', projectId: x.projectId, visibility: 'private', memberIds: ['c'] }, p)
+ f.state.deletion = { at: new Date(0).toISOString(), by: 'owner', purgeAt: new Date(10_000_000).toISOString() }
+ f.run({ type: 'swarm.restore' }, owner, { workspaceLost: ['p'] })
+ expect(f.state.people.some(person => person.id === 'p')).toBe(false)
+ expect(projectOf(f.state, x.projectId)).toMatchObject({ ownerId: 'c', ownerGeneration: 'c-first' })
+ expect(projectOf(f.state, alone.projectId).ownerId).toBe('')
+ })
+
+ it('has no other place that adds or drops people without settling', () => {
+ for (const file of ['commands.ts', 'store.ts']) {
+ const source = readFileSync(new URL(`./${file}`, import.meta.url), 'utf8')
+ expect(source, file).not.toMatch(/state\.people\.push\(|state\.people = state\.people\.filter/)
+ }
+ })
+
+ it('places work on a machine as its owner\'s own only for its owner now, not the same account at a later membership', () => {
+ const f = setup(), x = f.create(p)
+ f.state.machines = [{ machineId: 'p-mac', contributorId: 'p', buddyOnly: true } as unknown as ContributedMachine]
+ expect(teamWorkCheck(f.state, 'p-mac', 'p', projectOf(f.state, x.projectId), 1000)).toBeNull()
+ f.state.people.find(person => person.id === 'p')!.generation = 'p-second'
+ expect(teamWorkCheck(f.state, 'p-mac', 'p', projectOf(f.state, x.projectId), 1000)).toMatchObject({ code: 'NOT_SWARM_MACHINE' })
+ })
+})
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 909fc3ad2..90e8b593d 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -33,7 +33,12 @@ export const roleVersion = (text: string): string => createHash('sha256').update
export interface SwarmProject {
id: string
name: string
+ /** The owner's id; '' for a private project whose owner left with no member left to take it (settleOwners): nobody's. */
ownerId: string
+ /** The owner's membership generation when they became its owner (task #3073): the same account at a later membership
+ * owns nothing, as a member's listing works. Absent on projects from before 2026-11-05 until settleOwners fills it; until
+ * then the owner matches by id, as before. */
+ ownerGeneration?: string
leadConversationId: string
/** Public means every member of this swarm, never anonymous internet access. */
visibility: ProjectVisibility
@@ -160,6 +165,47 @@ export function ledProject(state: SuperTabState, agentId: string): SwarmProject
return led.size ? projectsOf(state).find(p => led.has(p.leadConversationId)) : undefined
}
+/** Gives each project whose owner is gone a new owner (task #3073, River's ruling 2026-11-05): its owner left or was
+ * removed, or is in the Swarm at a later membership. It passes to the earliest listed member still in the Swarm at the
+ * membership they were listed with, who reads it already (one who can manage it first, else a viewer); else, for a public
+ * project, to the Swarm's owner, who reads it too; else it is nobody's ('' owner): nobody reads it, and the Swarm's owner
+ * sees only that it exists and may delete it (deletableProject). A project from before ownerGeneration whose owner is still
+ * here gets their membership now, which is how the migration fills it. Each project that changed hands, in order. */
+export function settleOwners(state: SuperTabState): Array<{ projectId: string; from: string; to: string }> {
+ const changed: Array<{ projectId: string; from: string; to: string }> = []
+ const people = new Map(state.people.map(p => [p.id, p]))
+ for (const project of state.projects ?? []) {
+ if (!project.ownerId) continue
+ const current = people.get(project.ownerId)
+ if (current && project.ownerGeneration === undefined) project.ownerGeneration = current.generation
+ if (current && project.ownerGeneration === current.generation) continue
+ const listed = project.members.filter(m => m.id !== project.ownerId && people.get(m.id)?.generation === m.generation)
+ const next = listed.find(m => people.get(m.id)!.role !== 'viewer') ?? listed[0]
+ const swarmOwner = people.get(state.ownerId)
+ const to = next ? people.get(next.id)! : project.visibility === 'public' && swarmOwner ? swarmOwner : undefined
+ changed.push({ projectId: project.id, from: project.ownerId, to: to?.id ?? '' })
+ project.ownerId = to?.id ?? ''
+ if (to) project.ownerGeneration = to.generation
+ else delete project.ownerGeneration
+ if (next) project.members = project.members.filter(m => m !== next)
+ }
+ return changed
+}
+
+/** Adds [member] to the Swarm by any way in (invitation, link, domain or Workspace join): its projects are settled first, so
+ * a project from before ownerGeneration whose owner left is never matched to them again (security reviews of #3082). */
+export function admitPerson(state: SuperTabState, member: Person): void {
+ settleOwners(state)
+ state.people.push(member)
+}
+
+/** Takes the people [leaving] out of the Swarm (a removal, a leave, a restore that keeps out those the Workspace lost), and
+ * passes their projects on (settleOwners). */
+export function dismissPeople(state: SuperTabState, leaving: ReadonlySet<string>): void {
+ state.people = state.people.filter(p => !leaving.has(p.id))
+ settleOwners(state)
+}
+
/** Whose active work other projects' Leads see and are alerted about. A private project's work stays with its own people. */
export const sharedWithLeads = (project: SwarmProject): boolean => project.visibility !== 'private'
@@ -172,10 +218,19 @@ export function canReadProject(state: SuperTabState, actor: Actor, project: Swar
return agentProjectId(state, target) === project.id
}
const member = state.people.find(p => p.id === actor.userId)
- return !!member && (project.visibility === 'public' || project.ownerId === member.id ||
+ return !!member && (project.visibility === 'public' || ownsProject(state, member.id, project) ||
project.members.some(p => p.id === member.id && p.generation === member.generation))
}
+/** Whether [userId] owns [project] now: its owner, in the Swarm at the membership they owned it in (task #3073). A former
+ * owner who left or was removed and came back owns nothing, as a former member reads nothing. A project from before the
+ * generation was stored matches by id until settleOwners fills it. */
+export function ownsProject(state: SuperTabState, userId: string, project: SwarmProject): boolean {
+ if (!userId || project.ownerId !== userId) return false
+ const member = state.people.find(p => p.id === userId)
+ return !!member && (project.ownerGeneration === undefined || project.ownerGeneration === member.generation)
+}
+
/** Whom a group's work is for, as its pull requests say (`requestedByLine`): the person who asked for it (`requesterId`) while
* they can still read its project, else the project's owner. Until 11-01 it was always the owner, and agents on Tony's Mac
* opened Tony's pull requests as Ken's (#2486, #2488, #2491). It names a person only: the GitHub App's token, who gets one
@@ -421,7 +476,7 @@ export function wordsOf(source: unknown): 'author' | 'none' | 'unknown' | { agen
*/
export function teamSessionAccess(state: SuperTabState, actor: Actor, target: Agent, elsewhere = false): 'watch' | 'none' | 'member' | null {
if (!onTeamAccount(state, target) || actor.kind !== 'person' || !isConfidential(state, target, elsewhere)) return null
- if (actor.userId === projectOf(state, agentProjectId(state, target)).ownerId) return 'watch'
+ if (ownsProject(state, actor.userId, projectOf(state, agentProjectId(state, target)))) return 'watch'
if (actor.userId === target.machineOwnerId) return 'none'
return watchClosed(state, target, elsewhere) ? 'none' : 'member'
}
@@ -492,13 +547,43 @@ export function mutableProjects(state: SuperTabState): SwarmProject[] {
export function manageProject(state: SuperTabState, actor: Actor, projectId: string): SwarmProject {
const project = readProject(state, actor, projectId)
author(state, actor, true)
- if (actor.kind !== 'person' || actor.userId !== project.ownerId) {
+ if (actor.kind !== 'person' || !ownsProject(state, actor.userId, project)) {
fail('PROJECT_OWNER_REQUIRED', 'Only the project owner can manage this project.', 403)
}
mutableProjects(state)
return projectOf(state, projectId)
}
+/** The project [actor] may delete: one they manage, or, for the Swarm's owner, one that is nobody's (settleOwners), which they
+ * may delete but never read (task #3073). */
+export function deletableProject(state: SuperTabState, actor: Actor, projectId: string): SwarmProject {
+ author(state, actor)
+ const project = projectsOf(state).find(p => p.id === projectId)
+ if (!project || !isOwnerless(project) || actor.kind !== 'person' || actor.userId !== state.ownerId) return manageProject(state, actor, projectId)
+ author(state, actor, true)
+ mutableProjects(state)
+ return projectOf(state, projectId)
+}
+
+/** The account of [project]'s owner, which the GitHub token and a start's preparation name the work for: nobody for a project
+ * nobody owns, never looked up by its empty id, which is no ObjectId (the lookup would throw). */
+export async function ownerAccount(users: { findUnique(args: { where: { id: string }; select: { name: true; email: true } }): Promise<{ name: string | null; email: string } | null> },
+ project: SwarmProject): Promise<{ name: string | null; email: string } | null> {
+ return project.ownerId ? users.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } }) : null
+}
+
+/** A project nobody owns: its owner left with no member left to take it (settleOwners). */
+export const isOwnerless = (project: SwarmProject): boolean => !project.ownerId
+
+/** What the Swarm's owner reads of each project nobody owns (task #3073): that it exists, its name and its size (its chats in
+ * this read), never what is in it. Anyone else reads nothing of them. */
+export function ownerlessProjects(state: SuperTabState, actor: Actor): Array<{ id: string; name: string; conversations: number }> | undefined {
+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) return undefined
+ const ownerless = projectsOf(state).filter(isOwnerless)
+ return ownerless.length ? ownerless.map(p => ({ id: p.id, name: p.name,
+ conversations: state.conversations.filter(c => c.projectId === p.id).length })) : undefined
+}
+
/** How long a start may stay pending before a project delete treats it as stuck: well past the 15 minutes the sweep gives a
* dispatched start to prepare (liveness.ts START_PREPARE_MS). */
export const STUCK_START_MS = 60 * 60_000
@@ -509,7 +594,10 @@ export const STUCK_START_MS = 60 * 60_000
* and it closed that agent's session when it was removed, so none of them ever settles (2026-11-04: 17 such starts on four
* Macs, from agents stopped while a project was cleaned up, kept its owner from deleting it). */
export function deleteProject(state: SuperTabState, actor: Actor, projectId: string, orphaned: ReadonlySet<string> = new Set(), now?: number): void {
- const project = manageProject(state, actor, projectId)
+ const project = deletableProject(state, actor, projectId)
+ // A project nobody owns is deleted by the Swarm's owner, who reads nothing of it: no refusal names what is in it, and its
+ // work, which nobody can resolve, goes with it.
+ const ownerless = isOwnerless(project)
// A person's one Buddy chat belongs to no project and stays; that project's sessions in it go with their agents.
const groups = state.conversations.filter(c => !isLeads(c) && !isSwarmBuddyChat(c) && groupProject(state, c).id === project.id)
const groupIds = new Set(groups.map(c => c.id))
@@ -526,11 +614,12 @@ export function deleteProject(state: SuperTabState, actor: Actor, projectId: str
(!s.harnessId || s.poolGeneration && !s.poolSettled && !orphaned.has(s.id)))
// Each refusal names what holds it, so its owner can act on it: the ones before named nothing, and no read showed them.
const titled = (id: string) => groups.find(c => c.id === id)?.title || 'the project chat'
+ if (pending.length && ownerless) fail('STARTS_PENDING', 'Agents of this project are still starting. Delete it once they have started or failed, within the hour.')
if (pending.length) {
fail('STARTS_PENDING', `Resolve this project’s pending agent starts before deleting it: ${pending.slice(0, 3)
.map(s => `${s.request.name} in “${titled(s.request.conversationId)}”`).join(', ')}${pending.length > 3 ? ` and ${pending.length - 3} more` : ''}.`)
}
- const active = groups.filter(activeWork)
+ const active = ownerless ? [] : groups.filter(activeWork)
if (active.length) {
fail('WORK_ACTIVE', `Resolve this project’s active work before deleting it: ${active.slice(0, 3).map(c => `“${titled(c.id)}”`).join(', ')}${
active.length > 3 ? ` and ${active.length - 3} more` : ''}.`)
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 226ca0ae8..11c835f1f 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -73,6 +73,8 @@ export interface Derived {
lead?: Record<string, { machineId: string } | { refused: string }> }>
/** A Lead agent only. */
otherProjectsWork?: OtherProjectWorkView[]
+ /** The Swarm's owner only: projects nobody owns, which they may delete but never read (projects.ts ownerlessProjects). */
+ ownerlessProjects?: Array<{ id: string; name: string; conversations: number }>
/** A person only. */
mentionsWaiting?: number
/** A person only: a digest of which tags wait, moving when they change though the count may not. */
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 63f386370..05cd90fd1 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -149,6 +149,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
roleName: roleNameOf(state, state.agents.find(a => a.id === seen.id)!) }])),
machines: Object.fromEntries((visible.machines ?? []).map(machine)),
...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),
+ ...(visible.ownerlessProjects ? { ownerlessProjects: visible.ownerlessProjects } : {}),
...(actor.kind === 'person' && extras.mentionsWaiting !== undefined ? { mentionsWaiting: extras.mentionsWaiting } : {}),
...(actor.kind === 'person' && extras.mentionsDigest !== undefined ? { mentionsDigest: extras.mentionsDigest } : {}),
...(actor.kind === 'person' && extras.decisionsWaiting !== undefined ? { decisionsWaiting: extras.decisionsWaiting } : {}),
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 0cd45958c..ba1c0c825 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -40,7 +40,7 @@ import { retryTransient } from './retry.js'
import { recordReload } from './retryStats.js'
import { buddyChatId, shownBefore, swarmBuddyChatId, type ChosenBuddyName } from './buddies.js'
import { cleanPullRequestLinks } from './cards.js'
-import { accountOf, wordsOf, buddyInstructionsProject, canReadAgent, canReadGroup, groupRepositoryUrl, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey, GITHUB_SEEN, type GitHubSeen, type SwarmProject } from './projects.js'
+import { accountOf, wordsOf, buddyInstructionsProject, canReadAgent, canReadGroup, groupRepositoryUrl, canWatchAgent, groupProject, ledProject, onTeamAccount, ownerAccount, ownsProject, admitPerson, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey, GITHUB_SEEN, type GitHubSeen, type SwarmProject } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { SESSION_ENDED_KIND, sessionContext, sessionReadsRow, type ContextRow } from './buddySessions.js'
import { DELETED_TEXT, type MessageChangeTarget } from './messageEdits.js'
@@ -1138,7 +1138,7 @@ export class SuperTabStore {
if (await removedFromWorkspace(tx, state.workspaceId, user.sub)) return 'revoked' as const
await addMember(tx, state.workspaceId, { id: user.sub, email }, 'guest', state.ownerId, generation)
}
- state.people.push({ id: user.sub, email, role: state.sharing!.access.role, generation, joinedVia: 'domain' })
+ admitPerson(state, { id: user.sub, email, role: state.sharing!.access.role, generation, joinedVia: 'domain' })
await this.save(tx, loaded, state, stamp, [{ kind: 'head', key: 'head' }])
// People per Swarm is what warns first at scale (spec, Design 4).
logger.info('[super-tab] auto-join', { tabId, userId: user.sub, people: state.people.length })
@@ -1187,7 +1187,7 @@ export class SuperTabStore {
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)
+ admitPerson(state, 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 }
@@ -1289,7 +1289,7 @@ export class SuperTabStore {
}
if (!member) {
member = { id: user.sub, email: authenticatedEmail(user.email)!, role: sharing.access.role, generation: receiptId }
- state.people.push(member)
+ admitPerson(state, member)
}
// A join by link or domain link is coming back on purpose: it clears a decline (spec 2026-11-03, Leaving is final).
if (state.autoJoinDeclined?.includes(user.sub)) state.autoJoinDeclined = declinedWithout(state, user.sub)
@@ -2113,7 +2113,7 @@ export class SuperTabStore {
&& c.assignment.execution.machineId === target.machineId && c.assignment.execution.machineOwnerId === target.machineOwnerId)
?? fail('NO_ASSIGNMENT', 'This agent has no task in progress. A GitHub token is only for an agent working on a task.')
const project = groupProject(state, group)
- const owner = await tx.user.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } })
+ const owner = await ownerAccount(tx.user, project)
const requester = owner ?? { name: null, email: state.people.find(p => p.id === project.ownerId)?.email ?? '' }
if (!requester.email) fail('NOT_FOUND', 'This project\'s owner is unavailable.', 404)
const contributed = state.machines?.find(m => m.machineId === target.machineId)?.name
@@ -2147,10 +2147,10 @@ export class SuperTabStore {
}
// A Swarm-wide Buddy's folder is made of checkouts already on its machine: there is no repository to fetch for it.
const project = startProject(state, start.request) ?? fail('NOT_FOUND', 'This start has no project folder to prepare.', 404)
- const owner = await tx.user.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } })
+ const owner = await ownerAccount(tx.user, project)
const email = owner?.email ?? state.people.find(p => p.id === project.ownerId)?.email ?? ''
return { tabId, projectId: project.id, repositoryUrl: project.repository?.repositoryUrl ?? null, approvalRequired: teamAccountRequired(),
- startId, own: project.ownerId === start.machineOwnerId,
+ startId, own: ownsProject(state, start.machineOwnerId, project),
requester: { name: owner?.name?.trim() || null, email } }
})
}
@@ -2587,7 +2587,7 @@ 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 hasWorkspaceAccess(tx, state, user.sub))
+ } else if (!(ownsProject(state, user.sub, project) && await hasWorkspaceAccess(tx, state, user.sub))
&& !await this.hostsProject(tx, state, user, project.id)) {
unavailable()
}
diff --git a/docs/plans/2026-11-05-project-owner-generation-plan.md b/docs/plans/2026-11-05-project-owner-generation-plan.md
new file mode 100644
index 000000000..d85da6482
--- /dev/null
+++ b/docs/plans/2026-11-05-project-owner-generation-plan.md
@@ -0,0 +1,146 @@
+# Project Ownership Follows Membership Implementation Plan
+
+> Implemented task by task, test first, by the project's Engineer workflow (no subagent hand-off).
+
+**Goal:** A private project's owner who leaves the Swarm or is removed from it loses the project. Ownership passes to a
+remaining member, and the project stays manageable.
+
+**Architecture:** Each project stores its owner's membership generation (`ownerGeneration`). Every owner check goes
+through one helper (`ownsProject`) that matches id and generation, as member checks already do. One pure function
+(`settleOwners`) gives a project whose owner is gone a new owner: the earliest-listed remaining member, else the Swarm
+owner for a public project, else nobody (ownerless). `member.remove` (removal and leave), `invite.accept` and the one-off
+migration job all call it. An ownerless project is readable by nobody. The Swarm owner sees only its id, name and number
+of chats, and may delete it.
+
+**Tech Stack:** TypeScript, vitest, Prisma (MongoDB) for the migration job.
+
+**Spec:** Task #3073 (River's ruling, 2026-11-05) and Diego's proposal in the openharness project chat (current main
+1da94962a).
+
+## Global Constraints
+
+- PR body first line: "Requested by diego through Harness."
+- Access and private data: two independent security reviews.
+- A project whose owner never left works exactly as today.
+- A rejoining former owner gets nothing back unless invited to the project again.
+- Nobody reads an ownerless private project, the Swarm owner included. The Swarm owner sees its name and size only, and
+ may delete it.
+- Swarm code stays out of cli/src/core. Temporary files only in mktemp -d folders.
+
+## Design
+
+- Growth: one optional string per project (at most 100 projects per Swarm). An ownerless project is deleted by the
+ Swarm owner, and its delete removes the field with it.
+- Concurrency: the same Swarm command lock as every command. The migration writes the head guarded by its version, as
+ the instructions migration does: a command in between wins, and the Swarm is retried on the next run.
+- Read cost: no new read. `visibleState` adds a list for the Swarm owner built from projects already loaded.
+ `visibilityChanged` gains `ownerId`, so a handover reloads readers once, the same as the removal it comes with.
+- Scale: O(projects × members) per settle, and settle runs only on member.remove and invite.accept: at most 100 × 200.
+ The first warning would be member.remove latency in the command timing logs.
+- Compatibility: `ownerGeneration` is an added field. Older clients ignore it and `ownerlessProjects`. An ownerless
+ project never reaches a client's project list (no one reads it), so its empty `ownerId` is never shown.
+- Migration + rollback: `scripts/swarm-project-owners/migrate.ts` is a dry run unless `--apply`. It fills
+ `ownerGeneration` from the owner's current membership and hands over projects whose owner is already gone, printing
+ each handover (project, old owner id, new owner id). Rollback: the previous backend ignores `ownerGeneration`. A
+ handover is not reverted, because reverting it restores the bug; the printed report is the record. Until the job runs,
+ a project without `ownerGeneration` keeps today's id-only owner check. `member.remove` and `invite.accept` settle such
+ projects on their own.
+- Audience: the server decides who owns and reads (`ownsProject`, `canReadProject`, `manageProject`). The Swarm owner's
+ ownerless list carries id, name and chat count only.
+- Identity: ownership is a membership (id + generation), never a login: the same account rejoining is a new membership.
+- Failure: a refused manage or delete says why (PROJECT_OWNER_REQUIRED or NOT_FOUND, as today). A delete of an ownerless
+ project with agents still starting is refused in words that name nothing inside it.
+- Platforms: backend only. Clients read the new owner from `ownerId` as today.
+
+## Review Focus
+
+- A former owner rejoining by link, domain or Workspace join (store.ts) before the migration job runs keeps today's
+ id-only check for a project without `ownerGeneration`. The job closes that window. Run it right after deploy.
+- The earliest remaining member is a viewer: they become owner but cannot manage (READ_ONLY). Settle prefers the
+ earliest non-viewer member, then any member.
+- A stale member entry of the old owner (an earlier generation) must never be picked as the next owner.
+- Refusals when the Swarm owner deletes an ownerless project must not name its chats, tasks or agents.
+- Other raw `project.ownerId` checks (repository, task closing, buddy moves, machine accounts, team terminals) must use
+ the generation-checked helper.
+
+---
+
+### Task 1: Owner checks match the owner's membership
+
+**Files:**
+- Modify: `backend/src/superTabs/projects.ts` (`SwarmProject.ownerGeneration`, `ownsProject`, `canReadProject`,
+ `manageProject`, `teamSessionAccess`)
+- Modify: `backend/src/superTabs/commands.ts` (`project.create`, and the raw owner checks at project.repository,
+ agent moves, decisions/closes)
+- Modify: `backend/src/superTabs/model.ts` (machine accounts `mayMove`)
+- Test: `backend/src/superTabs/projectOwners.test.ts`
+
+**Interfaces:**
+- Produces: `ownsProject(state: SuperTabState, userId: string, project: SwarmProject): boolean`. It is true when
+ `ownerId === userId`, the person is in the Swarm and `ownerGeneration` is absent (legacy) or equals their generation.
+
+- [ ] Write the failing test: P creates private X. P's generation changes (left and rejoined). P no longer reads X
+ (`visibleState(state, P).projects` lacks X), `project.sharing`/`project.rename` by P are refused, and `ownsProject` is
+ false. P with the same generation still reads and manages X. A project with no `ownerGeneration` still matches by id.
+ `project.create` stores the creator's generation.
+- [ ] Run it and watch it fail.
+- [ ] Implement it, routing every owner check through `ownsProject`.
+- [ ] Run projectOwners.test.ts, projects.test.ts and commands.test.ts. Commit.
+
+### Task 2: Ownership passes to the earliest remaining member
+
+**Files:**
+- Modify: `backend/src/superTabs/projects.ts` (`settleOwners`)
+- Modify: `backend/src/superTabs/commands.ts` (`member.remove`, `invite.accept`)
+- Modify: `backend/src/superTabs/parts/commit.ts` (`visibilityChanged` includes `ownerId`)
+- Test: `backend/src/superTabs/projectOwners.test.ts`, `backend/src/superTabs/parts/commit.test.ts`
+
+**Interfaces:**
+- Produces: `settleOwners(state: SuperTabState): Array<{ projectId: string; from: string; to: string }>` (to is '' when
+ ownerless). It fills a missing `ownerGeneration` for an owner still in the Swarm, and hands over a project whose owner is
+ gone or whose generation is stale.
+
+- [ ] Write the failing tests:
+ - Diego's case: P creates private X with member C. The Swarm owner removes P. C now owns and manages X (renames it). P,
+ invited again as viewer and accepted, doesn't see X and can't reshare it.
+ - P leaves by itself: the same handover.
+ - The earliest non-viewer member is chosen, and a stale entry is skipped.
+ - A public project with no member goes to the Swarm owner.
+ - A project whose owner stayed is unchanged.
+ - `visibilityChanged` is true when only `ownerId` changed.
+- [ ] Run them and watch them fail.
+- [ ] Implement it.
+- [ ] Run the tests above. Commit.
+
+### Task 3: An ownerless project: nobody reads it, the Swarm owner may delete it
+
+**Files:**
+- Modify: `backend/src/superTabs/projects.ts` (`deletableProject`, `deleteProject`)
+- Modify: `backend/src/superTabs/commands.ts` (`project.delete`)
+- Modify: `backend/src/superTabs/model.ts` (`visibleState` `ownerlessProjects` for the Swarm owner, type on `SuperTabState`)
+- Test: `backend/src/superTabs/projectOwners.test.ts`
+
+- [ ] Write the failing test: P creates private X with no member. The Swarm owner removes P. X's `ownerId` is ''.
+ Nobody reads X: not the Swarm owner, not P re-invited. The Swarm owner's `visibleState.ownerlessProjects` is
+ `[{ id, name, conversations }]` and no one else gets it. The Swarm owner can't rename or reshare X, and
+ `readConversation` is refused, but `project.delete` removes it with its chats and agents. A collaborator can't delete
+ it. Pending starts refuse the delete without naming them.
+- [ ] Run it and watch it fail.
+- [ ] Implement it.
+- [ ] Run the tests. Commit.
+
+### Task 4: Migration job for existing projects
+
+**Files:**
+- Create: `backend/src/superTabs/migration/projectOwners.ts` (`migrateProjectOwners(db, { apply })`)
+- Create: `backend/scripts/swarm-project-owners/migrate.ts`
+- Test: `backend/src/superTabs/projectOwners.test.ts` (migration cases through `settleOwners` on legacy states)
+
+- [ ] Write the failing tests: on a legacy state (no `ownerGeneration`), settle fills the present owner's generation and
+ changes nothing else. A project whose owner already left is handed over, or made ownerless. A second settle changes
+ nothing.
+- [ ] Run them and watch them fail.
+- [ ] Implement the job as `migration/instructions.ts` does: load each format-2 Swarm, settle, and write the head guarded
+ by its version (visibility epoch +1 when an owner changed). Report swarms, projects filled, handovers and failures.
+ It is a dry run without `--apply`.
+- [ ] Run the tests and typecheck. Commit.