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.

Backend: a Member per person and project, one task at a time, helpers by code (#4697) (#3575)

0xken15d8fda0c681a6
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 21a524416..67b9c4e87 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,6 +11,8 @@ import { requireRepositoryReach, unknownPushReason, type RepositoryReach } from
import { admitByRoom, admitMachineStart, AGENT_MEMORY_BYTES, noRepositoryStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamAccountPool, teamPoolsOf, teamWorkCheck, TEAM_ACCOUNTS_GONE, NOT_YOUR_COMPUTER, type ContributedMachine } from './machines.js'
import { movableEntry } from './computerMoves.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
+import { acceptedByRequester, ACCEPT_ALL_REFUSAL, askedByAnother, HELPER_REFUSALS, helperCheck, mayAcceptAll, memberMachine, memberOf, memberQueue } from './members.js'
+import { ownedPath, pathsOverlap } from './ownedPaths.js'
import { addedAgentName, newAgentName, renameAgentTo } from './agentRename.js'
import { addCrew, CREW_ROLE_MAX, removeCrew } from './crew.js'
import { noteIndex } from './processNotes.js'
@@ -424,6 +426,14 @@ export const commandSchema = z.discriminatedUnion('type', [
// A Member its person's Desktop starts itself through Cmd-N (task #4196): only its chat opens here; agent.add brings in the session.
local: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
+ // A Member for a waiting task's requester (members.ts, task #4697): sent by the dispatch pass as the project's coordinator.
+ z.object({ type: z.literal('member.start'), conversationId: id }).strict(),
+ // A helper for a waiting task while its Member is busy, only by the three checks (members.ts helperCheck): the dispatch pass's.
+ z.object({ type: z.literal('member.helper'), conversationId: id }).strict(),
+ // A Member's own host reports its project set up, with the commands it ran for a helper to repeat, or why it failed (#4698).
+ // ok true with its steps, ok false with its reason (checked in its handler).
+ z.object({ type: z.literal('agent.setUp'), projectId: id, ok: z.boolean(), steps: z.array(z.string().trim().min(1).max(300)).max(10).optional(),
+ reason: z.string().trim().min(1).max(500).optional() }).strict(),
z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration,
startedSession: z.object({ sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
// `configuration`: what the agent runs as its start last saw it, so work assigned after the settle records its model (CLI
@@ -561,6 +571,7 @@ export const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'member.username': ['username'],
'agent.add': ['name', 'initialMessage', 'roleName'],
'agent.new': ['name', 'projectName'],
+ 'agent.setUp': ['steps[]', 'reason'],
'buddy.create': ['name', 'setup.name'],
'agent.rename': ['name'],
'crew.add': ['role', 'lane'],
@@ -859,12 +870,6 @@ export function mayResumeStart(state: SuperTabState, actor: Actor, start: AgentS
return !!group && !isLeads(group) && !isSwarmBuddyChat(group) && ledProject(state, actor.agentId)?.id === groupProject(state, group).id
}
-/** The repo path an owns entry names, or null for anything else (a phrase, a glob), which is never compared. */
-function ownedPath(entry: string): string | null {
- const path = entry.trim().replace(/^\.\//, '').replace(/\/+$/, '')
- return /^[\w.@-]+(\/[\w.@-]+)*$/.test(path) ? path : null
-}
-const pathsOverlap = (a: string, b: string) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`)
/** A project's Lead (Product Manager) leaves only with its project: every other removal path refuses it. */
function protectLead(state: SuperTabState, agentId: string, actor: Actor): void {
@@ -1851,6 +1856,56 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
assignment: null, lastMessageSequence: 0, audience: { people: [{ id: me.id, generation: me.generation }] } })
return chatId
}
+ /** The first Accept of [personId] in [group]'s project starts their Member there (members.ts, task #4697): on their own
+ * computer and account, named "<name> · <project>", in a chat of its own with them. With no such computer the task's chat
+ * says so, and the task waits: nothing is refused, since the Accept stands. */
+ const startMember = (group: Conversation, personId: string) => {
+ const project = groupProject(state, group)
+ if (memberOf(state, personId, project.id)) return
+ const owner = person(state, personId)
+ const pool = memberMachine(state, personId, REGULAR_AGENT_CAPABILITY)
+ const who = owner.name ?? owner.email.split('@')[0]
+ const none = () => message(group.id, `${who} has no computer in this Swarm to run their agent for ${project.name}. This task waits until they open Harness on one.`, [], null, SYSTEM_ROW, undefined, undefined, undefined, stableId(operationId, 'member-line'))
+ if (!pool) return none()
+ const name = `${newAgentName(state, actor, undefined, stableId(operationId, 'member'))} · ${project.name}`
+ if ((state.starts ?? []).filter(s => !s.harnessId && !s.error).length >= 32) {
+ return message(group.id, `Too many agents are starting in this Swarm to start ${who}'s agent for ${project.name} now. This task waits, and the next pass tries again.`,
+ [], null, SYSTEM_ROW, undefined, undefined, undefined, stableId(operationId, 'member-line'))
+ }
+ const chatId = openAgentChat(owner, name)
+ const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: pool.engines[0]!, name,
+ // Its project's folder with a worktree, as any project agent's (machines.ts admitMachineStart reads `member`): its host
+ // copies a helper from it, and reopens it in place after a sleep (#4698).
+ cwd: projectFolder(pool, project), worktree: true, requirements: { ...BUDDY_REQUIREMENTS, memoryBytes: AGENT_MEMORY_BYTES },
+ regular: true, mainProjectId: project.id, member: { projectId: project.id } }
+ let admitted: ReturnType<typeof admitMachineStart>
+ try { admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines) } catch (error) {
+ if (!(error instanceof SuperTabError)) throw error
+ // Refused: its chat goes with it, so nothing is left behind for a start that never was.
+ state.conversations = state.conversations.filter(c => c.id !== chatId)
+ return message(group.id, `Could not start ${who}'s agent for ${project.name}: ${error.message}`, [], null, SYSTEM_ROW, undefined, undefined, undefined,
+ stableId(operationId, 'member-line'))
+ }
+ state.starts ??= []
+ const id = stableId(operationId, 'member')
+ state.starts.push({ poolGeneration: admitted!.generation, id, creationId: `super-${id}`, actorKey: actorKey(actor), contributorId: owner.id,
+ membershipGeneration: owner.generation, machineOwnerId: owner.id, hostGrant: null, request, harnessId: null, dispatched: false, error: null,
+ requestedAt: context.now })
+ }
+ /** [personId]'s Member's helpers that hold no task stop once that person's queue in [projectId] is empty (members.ts; review of
+ * #3575): whoever took the last task, a helper that finished earlier never sits idle on their computer. Its host closes it and
+ * drops its worktree (#4698). */
+ const stopIdleHelpers = (personId: string, projectId: string) => {
+ if (memberQueue(state, projectId, personId, context.now).length) return
+ const member = memberOf(state, personId, projectId)?.agent
+ if (!member) return
+ for (const helper of state.agents) {
+ if (helper.helperOf?.agentId !== member.id || helper.workDecision === 'stop') continue
+ if (state.conversations.some(c => c.assignment?.agentId === helper.id && occupiesAgent(c))) continue
+ helper.workDecision = 'stop'
+ helper.releaseId = stableId(operationId, helper.id)
+ }
+ }
const addBuddyMachine = (machineId: string, setup: NonNullable<Extract<Command, { type: 'buddy.create' }>['setup']>, me: { id: string; generation: string }) => {
// Its last Buddy's folders are still being deleted there: a new one would lose its own (machine.contribute does the same).
if (state.machineCleanups?.some(c => c.machineId === machineId)) {
@@ -1970,6 +2025,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
pausedTask(group)
if (activeWork(group)) fail('WORK_ACTIVE', 'The current assignment must finish or be reconciled before reassignment.')
+ // A person's accepted ask runs under their own login alone, by every path, a Lead's pick by hand included (members.ts
+ // askedByAnother; security review 2 of #3575), unless they approved that very agent when it was suggested to them
+ // (task.suggest, #4217): their own choice. Its review steps are anyone's to review, as before.
+ // A suggestion goes back to its person to approve, so only an assignment is refused.
+ if (!suggestion && !group.reviewOf && group.taskApproval?.suggestedAgentId !== worker.id && askedByAnother(state, group, worker)) {
+ fail('ASKED_BY_ANOTHER', 'This task is another person\'s accepted ask: only their own agents take it.', 403)
+ }
// A review step is never its task's builder's, and a security review never the other one's reviewer, by any path (task
// #4534: #3542 and #3545 each waited 20-30 minutes on a refused step). The refusal says who may take it now.
const task = isReview(group) ? state.conversations.find(c => c.id === group.reviewOf) : undefined
@@ -4113,6 +4175,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
: state.projects ? { projectId: groupProject(state, group).id } : {}),
...(start.request.buddyScope ? { buddyScope: start.request.buddyScope } : {}),
...(start.request.regular ? { regular: true as const } : {}),
+ ...(start.request.member ? { member: start.request.member } : {}),
+ // A private main project ties it there from its start, not its first task (security review 2 of #3575): it carries the
+ // project's name, so no other project's Lead sees it or gives it work once its person stops reading the project.
+ ...(start.request.mainProjectId && projectsOf(state).find(p => p.id === start.request.mainProjectId)?.visibility === 'private'
+ ? { privateProjectId: start.request.mainProjectId } : {}),
+ ...(start.request.helperOf ? { helperOf: start.request.helperOf } : {}),
...(start.request.mainProjectId ? { mainProjectId: start.request.mainProjectId } : {}),
...(start.request.buddyNarrow ? { buddyNarrow: true as const } : {}),
machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
@@ -4907,6 +4975,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
case 'member.approvalMode': {
if (actor.kind !== 'person') fail('TASK_APPROVAL_FORBIDDEN', 'Choose your mode as a person.', 403)
+ if (command.mode === 'autoApprove' && !mayAcceptAll(state, actor.userId)) fail('ACCEPT_ALL_SUBSCRIPTION', ACCEPT_ALL_REFUSAL, 409)
person(state, actor.userId).approvalMode = command.mode
break
}
@@ -4933,6 +5002,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
else {
approval.state = 'approved'
approval.decidedAt = context.now
+ // Their first Accept in this project starts their Member there; it is assigned as any agent is (work.assign).
+ startMember(group, approval.personId)
}
// This decision releases the gate; the ordinary work.assign path alone launches work, with all of the
// store's global session, repository, machine and account checks. Never introduce a second assignment path here.
@@ -4992,6 +5063,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
if (routeNote) effects.messages.push({ id: routeNote.id, conversationId: group.id, author: sender,
text: routeNote.text, replyTo: null, recipients: [], source: bookkeeping(group.id, routeNote.source) })
+ // This assignment may take its person's last waiting task: their idle helpers stop (review of #3575).
+ if (group.requesterId && !group.reviewOf) stopIdleHelpers(group.requesterId, groupProject(state, group).id)
break
}
case 'work.status': {
@@ -5120,6 +5193,75 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (waited && activeWork(group) && !waitingForReview(assignment)) restartQuietTime(assignment, context.now)
// A Ready ends its Reviewer's wait for this revision: the review counts its quiet time from now (liveness.ts revisionReady).
if (activeWork(group) && waitingForReview(assignment)) revisionReady(state, group, context.now)
+ // A Member sleeps between its person's tasks (members.ts, task #4697): its next assignment wakes it.
+ if (!activeWork(group)) {
+ const worker = state.agents.find(a => a.id === assignment.agentId)
+ if (worker?.regular && worker.mainProjectId && !memberQueue(state, worker.mainProjectId, worker.contributorId, context.now).length) {
+ if (!worker.helperOf) worker.asleep = { since: context.now }
+ // Helpers end once nothing waits, this one among them (stopIdleHelpers).
+ stopIdleHelpers(worker.contributorId, worker.mainProjectId)
+ }
+ }
+ break
+ }
+ case 'member.start': {
+ // The dispatch pass, as the task's project's coordinator, or the task's own requester: a Member for that requester alone.
+ const group = open(state, command.conversationId)
+ const project = groupProject(state, group)
+ const requester = state.people.find(p => p.id === group.requesterId) ?? fail('NO_REQUESTER', 'This task has no person to start a Member for.', 409)
+ const lead = actor.kind === 'agent' && ledProject(state, actor.agentId)?.id === project.id
+ if (!lead && !(actor.kind === 'person' && actor.userId === requester.id)) fail('FORBIDDEN', 'Only the project\'s coordinator or the task\'s requester starts its Member.', 403)
+ if (!acceptedByRequester(state, group)) fail('TASK_NOT_ACCEPTED', 'Its person accepts this task first.', 409)
+ startMember(group, requester.id)
+ break
+ }
+ case 'member.helper': {
+ const group = open(state, command.conversationId)
+ const project = groupProject(state, group)
+ const requester = state.people.find(p => p.id === group.requesterId) ?? fail('NO_REQUESTER', 'This task has no person to help.', 409)
+ const lead = actor.kind === 'agent' && ledProject(state, actor.agentId)?.id === project.id
+ if (!lead && !(actor.kind === 'person' && actor.userId === requester.id)) fail('FORBIDDEN', 'Only the project\'s coordinator or the task\'s requester asks for a helper.', 403)
+ if (!acceptedByRequester(state, group)) fail('TASK_NOT_ACCEPTED', 'Its person accepts this task first.', 409)
+ if (activeWork(group)) fail('WORK_ACTIVE', 'This task already has its agent.', 409)
+ const member = memberOf(state, requester.id, project.id)?.agent ?? fail('NO_MEMBER', 'Its person has no Member in this project yet.', 409)
+ // One helper per task: a second ask while it starts, or once it runs here, changes nothing.
+ if ((state.starts ?? []).some(s => s.request.helperOf && s.request.conversationId === group.id && !s.error && !s.poolSettled)
+ || state.agents.some(a => a.helperOf?.agentId === member.id && group.agentIds.includes(a.id) && a.workDecision !== 'stop')) {
+ ignored()
+ break
+ }
+ const check = helperCheck(state, member, group, context.now)
+ if (!check.ok) fail(`HELPER_${check.reason.toUpperCase()}`, HELPER_REFUSALS[check.reason], 409)
+ // On the Member's own computer and account, as the Member itself (v3: an agent starts only on its own person's computer).
+ const pool = memberMachine(state, requester.id, REGULAR_AGENT_CAPABILITY)
+ if (!pool || pool.machineId !== member.machineId) fail('HELPER_ROOM', HELPER_REFUSALS.room, 409)
+ const name = `${newAgentName(state, actor, undefined, stableId(operationId, 'helper'))} · ${project.name}`
+ const request: AgentStartRequest = { conversationId: group.id, machineId: pool.machineId, engine: member.configuration.engine, name,
+ cwd: projectFolder(pool, project), worktree: true, requirements: { ...BUDDY_REQUIREMENTS, memoryBytes: AGENT_MEMORY_BYTES },
+ regular: true, mainProjectId: project.id, helperOf: { agentId: member.id, harnessId: member.harnessId },
+ ...(member.setUp?.steps ? { setUpSteps: member.setUp.steps } : {}) }
+ const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!
+ state.starts ??= []
+ if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
+ const id = stableId(operationId, 'helper')
+ state.starts.push({ poolGeneration: admitted.generation, id, creationId: `super-${id}`, actorKey: actorKey(actor), contributorId: requester.id,
+ membershipGeneration: requester.generation, machineOwnerId: requester.id, hostGrant: null, request, harnessId: null, dispatched: false, error: null,
+ requestedAt: context.now })
+ result.startId = id
+ break
+ }
+ case 'agent.setUp': {
+ // Only the Member itself, of that project, from its own host.
+ if (actor.kind !== 'agent') fail('FORBIDDEN', 'A Member reports its own set-up.', 403)
+ const self = agent(state, actor.agentId)
+ if (!self.regular || self.mainProjectId !== command.projectId) fail('NOT_MEMBER', 'Only this project\'s Member reports its set-up.', 403)
+ if (command.ok ? !command.steps || command.reason !== undefined : !command.reason || command.steps !== undefined) {
+ fail('INVALID_SET_UP', 'Report the steps that set it up, or why it failed.', 400)
+ }
+ self.setUp = { projectId: command.projectId, at: context.now, ...(command.ok ? { steps: command.steps! } : { failed: command.reason! }) }
+ // A failed set-up is seen by its person, in their agent's chat (AGENTS.md: nothing fails silently).
+ const chat = state.conversations.find(c => c.kind === 'agent-chat' && c.agentIds.includes(self.id))
+ if (!command.ok && chat) message(chat.id, `Could not set up ${projectOf(state, command.projectId).name}: ${command.reason}`, [], null, SYSTEM_ROW)
break
}
case 'work.cancel': {
diff --git a/backend/src/superTabs/dispatch.ts b/backend/src/superTabs/dispatch.ts
index b4c68a472..c360f8b8f 100644
--- a/backend/src/superTabs/dispatch.ts
+++ b/backend/src/superTabs/dispatch.ts
@@ -4,6 +4,7 @@
* each free member gets, the two clocks and the capacity line. The store's pass (store.ts dispatchCrew) sends each pick
* through work.assign, whose own write refuses a second assignment.
*/
+import { askedByAnother } from './members.js'
import { SEED_RULES, type MachineRule, type ProjectRules } from './policy.js'
import { firstMachines, isReview, machineRuleRefusal } from './machineRules.js'
import { isBuddy } from './buddies.js'
@@ -189,6 +190,8 @@ export function candidatesFor(state: SuperTabState, member: Agent, rules: Dispat
const lane = open.filter(g => (!g.lane || !!laneNamed(rules.lanes, g.lane)) && !g.reviewOf && !pinned.includes(g) && !(pinOf(g) && members.has(pinOf(g)!.agentId)) && !lostByIt(g)
// Ordinary workers recover work; new tasks still need the PM's route or a standing crew lane.
&& (member.crew || (g.assignment?.status === 'lost' && g.lostAttempt))
+ // Another person's ask goes to their own Member (members.ts, task #4697), never to this agent on its own.
+ && !askedByAnother(state, g, member)
&& acceptsLane(laneOf(g, rules.lanes)) && (!needsStrongModel(g) || onStrongModel(member)))
// Team-written code goes to Team accounts only (teamWritten.ts); a pick refused this round is not sent again (store.ts).
const allowed = (group: Conversation) => (group.reviewOf ? steps.includes(group) : !refusesWork) && !barredFromTeamWritten(state, group, member) && !skip(group.id, member.id)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 409f12a32..74861151a 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -815,8 +815,9 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
// A person's one Buddy chat has no project (Dee, 10-31): its project session works in the one it names, and its main Buddy
// and plain sessions in none, in their own folder (buddyHomeFolder).
const group = forProject ? undefined : conversation(state, request.conversationId)
- // A Regular agent's own chat has none either (agent.new, task #4116): it starts in its person's home folder.
- const project = forProject ?? (isAgentChat(group!) ? undefined : !isSwarmBuddyChat(group!) ? groupProject(state, group!)
+ // A Regular agent's own chat has none either (agent.new, task #4116): it starts in its person's home folder. A Member's start
+ // names its project (members.ts, task #4697), and starts in that project's folder as any project agent does (#4698).
+ const project = forProject ?? (request.member ? projectOf(state, request.member.projectId) : isAgentChat(group!) ? undefined : !isSwarmBuddyChat(group!) ? groupProject(state, group!)
: request.buddySession?.projectId ? projectOf(state, request.buddySession.projectId) : undefined)
if (project && !pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
// Kept by its owner for other projects: a Product Manager too. A Buddy is its owner's own (commands.ts buddy.create).
diff --git a/backend/src/superTabs/mainProject.test.ts b/backend/src/superTabs/mainProject.test.ts
index 05d7e2629..a1e1996c5 100644
--- a/backend/src/superTabs/mainProject.test.ts
+++ b/backend/src/superTabs/mainProject.test.ts
@@ -128,13 +128,14 @@ describe('a main project\'s readers', () => {
expect(JSON.stringify(parts.agents)).not.toContain(secret)
})
- it('is cleared when the project is deleted, on agents and on starts still waiting', () => {
+ it('goes with its deleted project: the agent is removed, and a start still waiting loses it', () => {
const f = swarm()
const harness = f.project('harness')
const agentId = f.started(f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: harness }).result.startId as string, 'h-ada')
const waiting = f.newAgent({ kind: 'regular', name: 'Bo', mainProjectId: harness }).result.startId as string
f.run({ type: 'project.delete', projectId: harness }, owner)
- expect(f.state.agents.find(a => a.id === agentId)).not.toHaveProperty('mainProjectId')
+ // An idle Member is its main project's agent (task #4697), so it goes with the project, as the project's agents do.
+ expect(f.state.agents.find(a => a.id === agentId)).toBeUndefined()
expect(f.state.starts!.find(s => s.id === waiting)!.request).not.toHaveProperty('mainProjectId')
})
})
diff --git a/backend/src/superTabs/members.test.ts b/backend/src/superTabs/members.test.ts
new file mode 100644
index 000000000..df2331ec6
--- /dev/null
+++ b/backend/src/superTabs/members.test.ts
@@ -0,0 +1,441 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import type { ContributedMachine } from './machines.js'
+import { createSuperTab, SuperTabError, type Actor, type SuperTabState } from './model.js'
+import { helperCheck, memberPlan, memberQueue } from './members.js'
+import { dispatchPlan, DISPATCH_RULES } from './dispatch.js'
+import { touchesFor } from './parts/touches.js'
+import { canReadAgent } from './projects.js'
+import * as store from './parts/index.js'
+import { readerView } from './read/views.js'
+
+// Task #4697 (anh Dee 11-07 21:20, card #4693 part A): one Member per person and project, made on their first accepted task
+// there; that project's tasks they ask for go to it one at a time; helpers only by three checks; every asked task needs
+// its person's Accept, and Accept all is refused for subscription accounts.
+const NOW = 50_000_000
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const kai: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'kai', email: '[email protected]' }
+const resources = { cpuPercent: 1, memoryTotalBytes: 64e9, memoryUsedBytes: 1e9, diskFreeBytes: 500e9, diskTotalBytes: 1e12, projectDiskFreeBytes: 500e9,
+ deviceType: null, chip: null, os: null, gpuPercent: null }
+type Quota = { engine: string; known: boolean; windows: Array<{ name: string; usedPercent: number; resetsAt: null }> }
+const subscription = (usedPercent = 10): Quota => ({ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent, resetsAt: null }] })
+const api: Quota = { engine: 'claude', known: true, windows: [] }
+const unknown: Quota = { engine: 'claude', known: false, windows: [] }
+const code = (body: () => unknown): string | null => {
+ try { body(); return null } catch (error) { return error instanceof SuperTabError ? error.code : 'INVALID' }
+}
+
+export function swarm(quotas: Quota[] = [subscription()]) {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invited = run({ type: 'invite.create', email: kai.email, role: 'collaborator', conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, kai)
+ const machine = (machineId: string, contributorId: string, extra: Partial<ContributedMachine> = {}): ContributedMachine => ({
+ machineId, name: machineId, contributorId, membershipGeneration: state.people.find(p => p.id === contributorId)!.generation, generation: 'g1',
+ cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 4, paused: false,
+ observation: { generation: 'g1', receivedAt: NOW, sessionKind: 'computer', resources, tools: {}, quotas, runningHarnessIds: [], stoppedHarnessIds: [],
+ capabilities: ['regularAgent'] }, ...extra })
+ state.machines = [machine('kai-mac', 'kai'), machine('owner-mac', 'owner')]
+ const project = (name: string) => run({ type: 'project.create', name, visibility: 'public', brief: '' }).result.projectId as string
+ /** A task Kai asks for in [projectId], made by its Lead as an asked task is. */
+ const ask = (projectId: string, title: string, extra: Record<string, unknown> = {}) => {
+ const chat = state.projects!.find(p => p.id === projectId)!.leadConversationId
+ return run({ type: 'conversation.create', title, brief: 'Do it.', projectId, requesterId: 'kai', priority: 'P2',
+ task: { goal: title, changes: 'Change it.', constraints: 'None.', owns: ['src/a/'] }, checks: [{ description: 'Works.', independent: false }],
+ ...extra } as unknown as Command, owner).result.conversationId as string ?? chat
+ }
+ const group = (id: string) => state.conversations.find(c => c.id === id)!
+ return { run, machine, project, ask, group, get state() { return state }, set state(next: SuperTabState) { state = next } }
+}
+
+describe('Accept', () => {
+ it('stages the task of a person who asks to accept each one', () => {
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ expect(f.group(f.ask(lamp, 'Fix the boot logo')).taskApproval).toMatchObject({ personId: 'kai', state: 'proposal' })
+ })
+
+ it('refuses Accept all for a subscription account, or one whose kind is not known yet', () => {
+ for (const quota of [subscription(), unknown]) {
+ const f = swarm([quota])
+ expect(code(() => f.run({ type: 'member.approvalMode', mode: 'autoApprove' }, kai))).toBe('ACCEPT_ALL_SUBSCRIPTION')
+ }
+ // Ask me stays theirs to choose.
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ expect(f.state.people.find(p => p.id === 'kai')!.approvalMode).toBe('review')
+ })
+
+ it('allows Accept all for API accounts alone, and then does not stage their tasks', () => {
+ const f = swarm([api])
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ f.run({ type: 'member.approvalMode', mode: 'autoApprove' }, kai)
+ const lamp = f.project('lamp')
+ expect(f.group(f.ask(lamp, 'Fix the boot logo')).taskApproval).toBeUndefined()
+ })
+
+ it('still stages a task for an Accept all kept from before on a subscription account', () => {
+ const f = swarm()
+ f.state.people.find(p => p.id === 'kai')!.approvalMode = 'autoApprove'
+ const lamp = f.project('lamp')
+ expect(f.group(f.ask(lamp, 'Fix the boot logo')).taskApproval).toMatchObject({ state: 'proposal' })
+ })
+})
+
+describe('the first Accept', () => {
+ /** Kai, asking to accept each task, with a task asked in lamp and accepted. */
+ function accepted(f = swarm()) {
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ const first = f.ask(lamp, 'Fix the boot logo')
+ const approved = f.run({ type: 'task.approve', conversationId: first }, kai)
+ return { f, lamp, first, approved }
+ }
+ const memberStarts = (f: ReturnType<typeof swarm>) => (f.state.starts ?? []).filter(s => s.request.member)
+
+ it('starts the person\'s Member for that project on their own computer and account, named for it', () => {
+ const { f, lamp } = accepted()
+ const [start] = memberStarts(f)
+ expect(memberStarts(f)).toHaveLength(1)
+ expect(start).toMatchObject({ contributorId: 'kai', machineOwnerId: 'kai', hostGrant: null })
+ // In its project's folder with a worktree, as any project agent's (#4698: a helper copies from it, sleep reopens it in place).
+ expect(start!.request).toMatchObject({ machineId: 'kai-mac', regular: true, mainProjectId: lamp, member: { projectId: lamp },
+ cwd: `/swarm/${lamp}`, worktree: true })
+ expect(start!.request.name).toMatch(/^[A-Z][a-z]+ · lamp$/)
+ expect(f.group(start!.request.conversationId)).toMatchObject({ kind: 'agent-chat', title: start!.request.name })
+ })
+
+ // Two Accepts at once never take one free name or one slot: the start meets others on the head and its computer's ledger.
+ it('meets other starts on the head and on its computer\'s slots', () => {
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ const id = f.ask(lamp, 'Fix the boot logo')
+ const before = f.state
+ const command: Command = { type: 'task.approve', conversationId: id }
+ const effects = f.run(command, kai)
+ const touches = touchesFor(command, kai, before, effects)
+ expect(touches).toEqual(expect.arrayContaining([{ kind: 'head', key: 'head' }, { kind: 'machine', key: 'kai-mac' }]))
+ })
+
+ it('starts none for a later Accept in the same project', () => {
+ const { f, lamp } = accepted()
+ const second = f.ask(lamp, 'Fix the fan')
+ f.run({ type: 'task.approve', conversationId: second }, kai)
+ expect(memberStarts(f)).toHaveLength(1)
+ })
+
+ it('never uses another person\'s computer, a Team account or a Buddy-only one, and says why when it has none', () => {
+ const f = swarm()
+ f.state.machines = [f.machine('owner-mac', 'owner'), f.machine('kai-team', 'kai', { observation: { ...f.machine('x', 'kai').observation!, sessionKind: 'team' } }),
+ f.machine('kai-buddy', 'kai', { buddyOnly: true })]
+ const { first } = accepted(f)
+ expect(memberStarts(f)).toHaveLength(0)
+ expect(f.group(first).taskApproval?.state).toBe('approved')
+ expect(f.state.conversations.find(c => c.id === first)).toBeTruthy()
+ const said = f.run({ type: 'task.approve', conversationId: f.ask(f.state.projects!.find(p => p.name === 'lamp')!.id, 'Again') }, kai).messages
+ expect(said.map(m => m.text)).toContainEqual(expect.stringContaining('no computer in this Swarm'))
+ })
+})
+
+/** Kai's Member in lamp, started and running on Kai's computer, with [count] more of Kai's tasks there accepted. */
+export function withMember(f = swarm(), count = 1) {
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ const tasks = Array.from({ length: count + 1 }, (_, i) => f.ask(lamp, `Task ${i}`))
+ for (const id of tasks) f.run({ type: 'task.approve', conversationId: id }, kai)
+ const start = f.state.starts!.find(s => s.request.member)!
+ const own = { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }
+ f.run({ type: 'agent.startDispatch', startId: start.id }, kai, own)
+ const member = f.run({ type: 'agent.started', startId: start.id, harnessId: 'h-member',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, kai, own).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: start.id, warning: null }, kai, own)
+ return { f, lamp, tasks, member }
+}
+
+describe('the waiting queue', () => {
+ it('orders a person\'s tasks by priority, then age', () => {
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ const old2 = f.ask(lamp, 'Old P2', { priority: 'P2' }), p1 = f.ask(lamp, 'P1', { priority: 'P1' })
+ const new2 = f.ask(lamp, 'New P2', { priority: 'P2' }), p0 = f.ask(lamp, 'P0', { priority: 'P0' })
+ for (const id of [old2, p1, new2, p0]) f.run({ type: 'task.approve', conversationId: id }, kai)
+ expect(memberQueue(f.state, lamp, 'kai', NOW).map(g => g.id)).toEqual([p0, p1, old2, new2])
+ })
+
+ it('leaves out a task its person has not accepted', () => {
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ f.ask(lamp, 'Not accepted')
+ expect(memberQueue(f.state, lamp, 'kai', NOW)).toEqual([])
+ })
+})
+
+describe('the Member', () => {
+ it('is planned its person\'s next task when free, and nothing while it holds one', () => {
+ const { f, lamp, tasks, member } = withMember()
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([{ kind: 'assign', conversationId: tasks[0], agentId: member }])
+ f.run({ type: 'work.assign', conversationId: tasks[0]!, agentId: member }, owner)
+ expect(memberPlan(f.state, lamp, NOW).filter(p => p.kind === 'assign')).toEqual([])
+ })
+
+ it('is asked to start for a person whose waiting task has no Member yet, as Accept all\'s tasks have none', () => {
+ const f = swarm([api])
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ f.run({ type: 'member.approvalMode', mode: 'autoApprove' }, kai)
+ const lamp = f.project('lamp')
+ const id = f.ask(lamp, 'No Accept needed')
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([{ kind: 'start', conversationId: id }])
+ f.run({ type: 'member.start', conversationId: id }, kai)
+ expect(f.state.starts!.filter(s => s.request.member)).toHaveLength(1)
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ })
+
+ // The host contract of #4698 (Threadland): a host that says memberSetUp reports the project set up before work comes.
+ // Its mark names its project, which may be private: readers never get it, as its main project's id (read/views.ts).
+ // Security review 2 of #3575: its set-up record names that project too, with its commands or failure text.
+ it('keeps its mark and set-up out of what readers get, its host alone reads them', () => {
+ const { f, lamp, member } = withMember()
+ f.run({ type: 'agent.setUp', projectId: lamp, ok: true, steps: ['npm ci'] } as Command, { kind: 'agent', agentId: member, machineOwnerId: 'kai' })
+ const parts = readerView(store.split(f.state, { tabId: 'tab', version: 9_000, now: NOW }), owner, NOW, { teamMachines: [] }).parts
+ const row = parts.agents.find(a => a.key === member)?.data
+ expect(row).not.toHaveProperty('member')
+ expect(row).not.toHaveProperty('setUp')
+ })
+
+ it('waits for its set-up on a host that reports one, and is refused another agent\'s report', () => {
+ const f = swarm()
+ f.state.machines!.find(m => m.machineId === 'kai-mac')!.observation!.capabilities!.push('memberSetUp')
+ const { lamp, tasks, member } = withMember(f)
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ const me: Actor = { kind: 'agent', agentId: member, machineOwnerId: 'kai' }
+ expect(code(() => f.run({ type: 'agent.setUp', projectId: lamp, ok: true, steps: ['npm ci'] } as Command, owner))).not.toBeNull()
+ f.run({ type: 'agent.setUp', projectId: lamp, ok: true, steps: ['npm ci'] } as Command, me)
+ expect(f.state.agents.find(a => a.id === member)!.setUp).toMatchObject({ projectId: lamp, steps: ['npm ci'] })
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([{ kind: 'assign', conversationId: tasks[0], agentId: member }])
+ })
+
+ // Until the migration (#4693 part D) makes them Members, a person's own crew agents in the project take their asks as today.
+ it('is not started for a person whose own crew agent works in that project', () => {
+ const f = swarm([api])
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ f.run({ type: 'member.approvalMode', mode: 'autoApprove' }, kai)
+ const lamp = f.project('lamp')
+ const chat = f.state.projects!.find(p => p.id === lamp)!.leadConversationId
+ const config = { engine: 'claude' as const, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ const crew = f.run({ type: 'agent.add', conversationId: chat, machineId: 'kai-mac', harnessId: 'kai-crew', name: 'Kai crew', configuration: config, lead: false },
+ kai, { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }).result.agentId as string
+ f.state.agents.find(a => a.id === crew)!.crew = { role: 'engineer', at: NOW, by: 'owner' }
+ f.ask(lamp, 'Their own crew takes it')
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ })
+
+ it('sleeps once its task ends with nothing waiting, and wakes for its next one', () => {
+ const { f, tasks, member } = withMember(swarm(), 0)
+ const assigned = f.run({ type: 'work.assign', conversationId: tasks[0]!, agentId: member }, owner)
+ const assignmentId = f.group(tasks[0]!).assignment!.id
+ const me: Actor = { kind: 'agent', agentId: member, machineOwnerId: 'kai' }
+ f.run({ type: 'work.status', conversationId: tasks[0]!, assignmentId, status: 'done', result: 'Done at abc: https://github.com/o/r/pull/1' }, me)
+ expect(f.state.agents.find(a => a.id === member)!.asleep).toEqual({ since: NOW })
+ expect(assigned).toBeTruthy()
+ })
+})
+
+describe('a crew agent', () => {
+ it('is never planned a task another person asked for, and still gets work nobody asked for', () => {
+ const f = swarm()
+ const config = { engine: 'claude' as const, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ const add = (name: string, lead = false) => f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: name, name,
+ configuration: config, lead }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string
+ add('PM', true)
+ const ada = add('Ada')
+ f.run({ type: 'crew.add', agentId: ada, role: 'engineer', lane: 'backend' })
+ const task = (title: string, extra: Record<string, unknown>) => f.run({ type: 'conversation.create', title, brief: 'Do it.',
+ task: { goal: title, changes: 'Change it.', constraints: 'None.', owns: ['backend/src/a.ts'] }, checks: [], ...extra } as unknown as Command).result.conversationId as string
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const asked = task('Asked', { requesterId: 'kai' })
+ f.run({ type: 'task.approve', conversationId: asked }, kai)
+ const free = task('Free', {})
+ expect(dispatchPlan(f.state, 'lead', DISPATCH_RULES, NOW).map(p => p.conversationId)).toEqual([free])
+ })
+})
+
+describe('a helper', () => {
+ const owns = (paths: string[]) => ({ task: { goal: 'Do it.', changes: 'Change it.', constraints: 'None.', owns: paths } })
+ /** Kai's Member busy on a task owning src/a/, and a second task owning [second] waiting. */
+ function busy(paths: string[], f = swarm()) {
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const lamp = f.project('lamp')
+ const running = f.ask(lamp, 'Running', owns(['src/a/']))
+ const waiting = f.ask(lamp, 'Waiting', owns(paths))
+ for (const id of [running, waiting]) f.run({ type: 'task.approve', conversationId: id }, kai)
+ const start = f.state.starts!.find(s => s.request.member)!
+ const own = { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }
+ f.run({ type: 'agent.startDispatch', startId: start.id }, kai, own)
+ const member = f.run({ type: 'agent.started', startId: start.id, harnessId: 'h-member',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, kai, own).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: start.id, warning: null }, kai, own)
+ f.run({ type: 'work.assign', conversationId: running, agentId: member }, owner)
+ const agent = () => f.state.agents.find(a => a.id === member)!
+ return { f, lamp, running, waiting, member, agent }
+ }
+
+ it('starts when the task touches other code, the computer has room and the quota is above the floor', () => {
+ const { f, lamp, waiting, agent } = busy(['src/b/'])
+ expect(helperCheck(f.state, agent(), f.group(waiting), NOW)).toEqual({ ok: true })
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([{ kind: 'helper', conversationId: waiting }])
+ })
+
+ it('waits when the task touches the running work\'s code, or names no code to tell them apart', () => {
+ for (const paths of [['src/a/b.ts'], ['src'], ['the login screen']]) {
+ const { f, lamp, waiting, agent } = busy(paths)
+ expect(helperCheck(f.state, agent(), f.group(waiting), NOW)).toEqual({ ok: false, reason: 'overlap' })
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ }
+ })
+
+ it('waits when the computer has no room under its limit', () => {
+ const f = swarm()
+ const { waiting, agent } = busy(['src/b/'], f)
+ f.state.machines!.find(m => m.machineId === 'kai-mac')!.maxAgents = 1
+ expect(helperCheck(f.state, agent(), f.group(waiting), NOW)).toEqual({ ok: false, reason: 'room' })
+ })
+
+ it('waits when the quota is at the floor, or not known', () => {
+ for (const quota of [subscription(96), unknown]) {
+ const { f, waiting, agent } = busy(['src/b/'])
+ f.state.machines!.find(m => m.machineId === 'kai-mac')!.observation!.quotas = [quota]
+ expect(helperCheck(f.state, agent(), f.group(waiting), NOW)).toEqual({ ok: false, reason: 'quota' })
+ }
+ })
+
+ it('starts once, on the Member\'s computer and account, in its task\'s conversation', () => {
+ const { f, lamp, waiting, member } = busy(['src/b/'])
+ f.run({ type: 'member.helper', conversationId: waiting }, kai)
+ f.run({ type: 'member.helper', conversationId: waiting }, kai)
+ const helpers = f.state.starts!.filter(s => s.request.helperOf)
+ expect(helpers).toHaveLength(1)
+ expect(helpers[0]).toMatchObject({ contributorId: 'kai', machineOwnerId: 'kai', hostGrant: null })
+ expect(helpers[0]!.request).toMatchObject({ conversationId: waiting, machineId: 'kai-mac', mainProjectId: lamp, regular: true,
+ helperOf: { agentId: member, harnessId: 'h-member' } })
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ })
+
+ it('refuses a helper the checks refuse, whoever asks', () => {
+ const { f, waiting } = busy(['src/a/'])
+ expect(code(() => f.run({ type: 'member.helper', conversationId: waiting }, kai))).toBe('HELPER_OVERLAP')
+ // Nobody else asks for one.
+ expect(code(() => f.run({ type: 'member.helper', conversationId: waiting }, owner))).toBe('FORBIDDEN')
+ })
+
+ // Review of #3575 (Secrev7): a helper that finished while work waited, whose last task its Member then took, stops too.
+ it('stops, idle, once its person\'s queue empties, whoever took the last task', () => {
+ const { f, lamp, running, waiting, member } = busy(['src/b/'])
+ f.run({ type: 'member.helper', conversationId: waiting }, kai)
+ const start = f.state.starts!.find(s => s.request.helperOf)!
+ const own = { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }
+ f.run({ type: 'agent.startDispatch', startId: start.id }, kai, own)
+ const helper = f.run({ type: 'agent.started', startId: start.id, harnessId: 'h-helper',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, kai, own).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: start.id, warning: null }, kai, own)
+ f.run({ type: 'work.assign', conversationId: waiting, agentId: helper }, owner)
+ // A third task waits while the helper finishes its own: it stays.
+ const third = f.ask(lamp, 'Third', owns(['src/a/c.ts']))
+ f.run({ type: 'task.approve', conversationId: third }, kai)
+ const done = (id: string, agentId: string) => f.run({ type: 'work.status', conversationId: id, assignmentId: f.group(id).assignment!.id, status: 'done',
+ result: 'Done at abc: https://github.com/o/r/pull/3' }, { kind: 'agent', agentId, machineOwnerId: 'kai' })
+ done(waiting, helper)
+ expect(f.state.agents.find(a => a.id === helper)!.workDecision).not.toBe('stop')
+ // The Member frees and takes the last waiting task: the idle helper stops.
+ done(running, member)
+ f.run({ type: 'work.assign', conversationId: third, agentId: member }, owner)
+ expect(f.state.agents.find(a => a.id === helper)!.workDecision).toBe('stop')
+ })
+
+ it('takes its task, and stops once it ends with nothing waiting', () => {
+ const { f, lamp, waiting } = busy(['src/b/'])
+ f.run({ type: 'member.helper', conversationId: waiting }, kai)
+ const start = f.state.starts!.find(s => s.request.helperOf)!
+ const own = { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }
+ f.run({ type: 'agent.startDispatch', startId: start.id }, kai, own)
+ const helper = f.run({ type: 'agent.started', startId: start.id, harnessId: 'h-helper',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, kai, own).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: start.id, warning: null }, kai, own)
+ // Its host tells a Member and a helper from other agents by these, set by the server alone (#4698).
+ expect(f.state.agents.find(a => a.id === helper)!.helperOf).toEqual({ agentId: f.state.agents.find(a => a.member)!.id, harnessId: 'h-member' })
+ expect(f.state.agents.find(a => a.member)!.member).toEqual({ projectId: lamp })
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([{ kind: 'assign', conversationId: waiting, agentId: helper }])
+ f.run({ type: 'work.assign', conversationId: waiting, agentId: helper }, owner)
+ const assignmentId = f.group(waiting).assignment!.id
+ f.run({ type: 'work.status', conversationId: waiting, assignmentId, status: 'done', result: 'Done at abc: https://github.com/o/r/pull/2' },
+ { kind: 'agent', agentId: helper, machineOwnerId: 'kai' })
+ expect(f.state.agents.find(a => a.id === helper)!.workDecision).toBe('stop')
+ })
+})
+
+// Security review 1 of #3575: an agent starts on a person's computer only for work they accepted, whoever names them requester.
+describe('a task its requester never accepted', () => {
+ it('starts no Member or helper, and stays with the crew as before', () => {
+ const f = swarm()
+ const lamp = f.project('lamp')
+ // Kai never chose a mode: nothing is staged, and nothing is accepted either.
+ const id = f.ask(lamp, 'Named by someone else')
+ expect(f.group(id).taskApproval).toBeUndefined()
+ expect(memberQueue(f.state, lamp, 'kai', NOW)).toEqual([])
+ expect(memberPlan(f.state, lamp, NOW)).toEqual([])
+ expect(code(() => f.run({ type: 'member.start', conversationId: id }, kai))).toBe('TASK_NOT_ACCEPTED')
+ expect(code(() => f.run({ type: 'member.helper', conversationId: id }, kai))).toBe('TASK_NOT_ACCEPTED')
+ expect(f.state.starts ?? []).toEqual([])
+ })
+})
+
+// Security review 2 of #3575 (Secrev7): the rule holds for an assignment by hand too, not only for the dispatch pass.
+describe('an accepted ask assigned by hand', () => {
+ it('is refused to another person\'s agent, and taken by its person\'s own', () => {
+ const { f, lamp, tasks, member } = withMember()
+ const config = { engine: 'claude' as const, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ // Another person's agent in the same project: only the new check can refuse it.
+ const chat = f.state.projects!.find(p => p.id === lamp)!.leadConversationId
+ const other = f.run({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: 'owner-agent', name: 'Owner agent',
+ configuration: config, lead: false }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string
+ expect(code(() => f.run({ type: 'work.assign', conversationId: tasks[0]!, agentId: other }, owner))).toBe('ASKED_BY_ANOTHER')
+ f.run({ type: 'work.assign', conversationId: tasks[0]!, agentId: member }, owner)
+ expect(f.group(tasks[0]!).assignment?.agentId).toBe(member)
+ })
+})
+
+// Security review 2 of #3575 (Secrev8): a private project's Member is tied to it from its start, not from its first task, so
+// once its person stops reading the project no other project's Lead sees it, or the project's name in it, or gives it work.
+describe('a private project\'s Member', () => {
+ it('stays its project\'s alone after its person stops reading it', () => {
+ const f = swarm()
+ f.run({ type: 'member.approvalMode', mode: 'review' }, kai)
+ const secret = f.run({ type: 'project.create', name: 'secret', visibility: 'private', brief: '' }).result.projectId as string
+ f.run({ type: 'project.sharing', projectId: secret, visibility: 'private', memberIds: ['kai'] })
+ const id = f.ask(secret, 'Private work')
+ f.run({ type: 'task.approve', conversationId: id }, kai)
+ const start = f.state.starts!.find(s => s.request.member)!
+ const own = { contribution: { machineOwnerId: 'kai', contributorId: 'kai' } }
+ f.run({ type: 'agent.startDispatch', startId: start.id }, kai, own)
+ const member = f.run({ type: 'agent.started', startId: start.id, harnessId: 'h-secret',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, kai, own).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: start.id, warning: null }, kai, own)
+ expect(f.state.agents.find(a => a.id === member)!.privateProjectId).toBe(secret)
+ // Kai stops reading it; another project's Lead never sees the Member nor gives it work.
+ f.run({ type: 'project.sharing', projectId: secret, visibility: 'private', memberIds: [] })
+ const lamp = f.project('lamp')
+ const chat = f.state.projects!.find(p => p.id === lamp)!.leadConversationId
+ const config = { engine: 'claude' as const, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ const lead = f.run({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: 'lamp-lead', name: 'Lamp lead', configuration: config, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string
+ expect(canReadAgent(f.state, { kind: 'agent', agentId: lead, machineOwnerId: 'owner' }, f.state.agents.find(a => a.id === member)!)).toBe(false)
+ })
+})
diff --git a/backend/src/superTabs/members.ts b/backend/src/superTabs/members.ts
new file mode 100644
index 000000000..20415f8e2
--- /dev/null
+++ b/backend/src/superTabs/members.ts
@@ -0,0 +1,161 @@
+/**
+ * anh Dee's agent model (task #4697, card #4693 part A, 11-07 21:20): one Member per person and project, made on their first
+ * accepted task there, which takes that project's tasks they ask for one at a time and sleeps between them; helpers only by
+ * three checks; and every asked task needs its person's Accept.
+ */
+import { openTasks } from './dispatch.js'
+import { agentProjectId } from './projects.js'
+import { QUOTA_FLOOR_PERCENT } from './crewRules.js'
+import { availableSlots, downSince, machineSlots, type ContributedMachine } from './machines.js'
+import { ownedPath, pathsOverlap } from './ownedPaths.js'
+import { activeWork, occupiesAgent, type Agent, type AgentStart, type Conversation, type SuperTabState } from './model.js'
+
+/** Whether [personId] may choose Accept all: off for Claude and ChatGPT subscriptions until Anthropic and OpenAI confirm it in
+ * writing (anh Dee). Every engine on their own computers must be an API key, a known quota with no windows
+ * (costs/attempts.ts billingOf); an engine whose kind is not known yet counts as a subscription. */
+export function mayAcceptAll(state: SuperTabState, personId: string): boolean {
+ const engines = (state.machines ?? []).filter(m => m.contributorId === personId && !m.removal)
+ .flatMap(m => m.engines.map(engine => m.observation?.quotas.find(q => q.engine === engine)))
+ return engines.length > 0 && engines.every(q => !!q?.known && q.windows.length === 0)
+}
+
+/** Whether [group]'s requester accepted it (security review 1 of #3575): their Accept, or the Accept all they may choose (API
+ * accounts alone). Only then does their Member take it, or an agent start on their computer for it: anyone may name them
+ * requester, and a person who never chose a mode has nothing staged to accept. */
+export function acceptedByRequester(state: SuperTabState, group: Conversation): boolean {
+ const person = state.people.find(p => p.id === group.requesterId)
+ if (!person) return false
+ if (group.taskApproval) return group.taskApproval.state === 'approved' && group.taskApproval.personId === person.id
+ return person.approvalMode === 'autoApprove' && mayAcceptAll(state, person.id)
+}
+
+export const ACCEPT_ALL_REFUSAL = 'Accept all stays off for Claude and ChatGPT subscriptions until Anthropic and OpenAI confirm it in writing. Accept each task.'
+
+/** [personId]'s Member in [projectId] (task #4697): their running agent with that main project, else its start still pending.
+ * A helper is no Member, and nor is an agent that is stopping or from an earlier membership. */
+export function memberOf(state: SuperTabState, personId: string, projectId: string): { agent?: Agent; start?: AgentStart } | undefined {
+ const person = state.people.find(p => p.id === personId)
+ if (!person) return undefined
+ const agent = state.agents.find(a => a.regular && a.mainProjectId === projectId && a.contributorId === personId && !a.helperOf
+ && a.membershipGeneration === person.generation && a.workDecision !== 'stop')
+ if (agent) return { agent }
+ const start = (state.starts ?? []).find(s => s.request.member?.projectId === projectId && s.contributorId === personId
+ && !s.request.helperOf && !s.harnessId && !s.error)
+ return start ? { start } : undefined
+}
+
+/** The computer [personId]'s Member runs on: their own, listed, reporting and running Regular agents, never a Team account,
+ * a Buddy-only record or one shared with them (v3: an agent starts only on its own person's computer). */
+export function memberMachine(state: SuperTabState, personId: string, capability: string): ContributedMachine | undefined {
+ return (state.machines ?? []).find(m => m.contributorId === personId && !m.buddyOnly && !m.removal && !m.paused && !m.hostMachineId
+ && !!m.observation && m.observation.sessionKind !== 'team' && !!m.observation.capabilities?.includes(capability))
+}
+
+/** The host capability of #4698: its Member reports the project set up (agent.setUp) before it is handed work. */
+export const MEMBER_SET_UP_CAPABILITY = 'memberSetUp'
+
+const RANK: Record<string, number> = { P0: 0, P1: 1, P2: 2, P3: 3 }
+
+/** [personId]'s tasks waiting in [projectId], in the order their Member takes them: priority (P0 first, P2 when unset), then
+ * age (the lower task number). Only what may start now (dispatch.ts openTasks): accepted, not paused, nobody on it. */
+export function memberQueue(state: SuperTabState, projectId: string, personId: string, now: number): Conversation[] {
+ return openTasks(state, projectId, now).filter(g => !g.reviewOf && g.requesterId === personId && acceptedByRequester(state, g))
+ .sort((a, b) => (RANK[a.priority ?? 'P2'] ?? 2) - (RANK[b.priority ?? 'P2'] ?? 2) || (a.number ?? 0) - (b.number ?? 0))
+}
+
+/** Whether [group] is another person's accepted ask, never [agent]'s to take on its own (task #4697): it goes to its person's
+ * Member, so one person's work never runs under another person's login (AGENTS.md, Secure). An ask they have not accepted
+ * stays with the crew as before, until Accept on every task (follow-up of #4697). */
+export const askedByAnother = (state: SuperTabState, group: Conversation, agent: Agent): boolean =>
+ !!group.requesterId && group.requesterId !== agent.contributorId && acceptedByRequester(state, group)
+
+/** Whether [agent] holds no task now, and is not stopping, gone or still launching (an asleep one is free: its assignment wakes
+ * it). */
+export const freeAgent = (state: SuperTabState, agent: Agent, now: number): boolean =>
+ agent.workDecision !== 'stop' && (!!agent.asleep || !downSince(state, agent, now))
+ && !(state.starts ?? []).some(s => s.harnessId === agent.harnessId && s.request.machineId === agent.machineId && !s.poolSettled && !s.error)
+ && !state.conversations.some(c => c.assignment?.agentId === agent.id && occupiesAgent(c))
+
+/** Whether [agent] has set [projectId] up, on a host that reports it; any other host's Member is ready once it runs. */
+export function setUpReady(state: SuperTabState, agent: Agent, projectId: string): boolean {
+ const host = (state.machines ?? []).find(m => m.machineId === agent.machineId)
+ if (!host?.observation?.capabilities?.includes(MEMBER_SET_UP_CAPABILITY)) return true
+ return agent.setUp?.projectId === projectId && !agent.setUp.failed
+}
+
+const ownCrewIn = (state: SuperTabState, personId: string, projectId: string): boolean =>
+ state.agents.some(a => a.crew && a.contributorId === personId && a.workDecision !== 'stop' && agentProjectId(state, a) === projectId)
+
+export type MemberPick = { kind: 'assign'; conversationId: string; agentId: string } | { kind: 'start' | 'helper'; conversationId: string }
+
+export type HelperCheck = { ok: true } | { ok: false; reason: 'overlap' | 'room' | 'quota' }
+export const HELPER_REFUSALS: Record<'overlap' | 'room' | 'quota', string> = {
+ overlap: 'This task touches code its Member\'s work is on, or names none to tell: it waits for the Member.',
+ room: 'Its Member\'s computer has no room for another agent under its limit: it waits.',
+ quota: 'Its Member\'s quota is at the floor, or not known: it waits.',
+}
+
+/** The paths owned by the work [member] and its helpers have running, or null when one names none to compare. */
+function runningPaths(state: SuperTabState, member: Agent): string[] | null {
+ const team = new Set(state.agents.filter(a => a.id === member.id || a.helperOf?.agentId === member.id).map(a => a.id))
+ const paths = state.conversations.filter(c => activeWork(c) && team.has(c.assignment!.agentId)).map(c => (c.task?.owns ?? []).map(ownedPath))
+ return paths.some(p => !p.length || p.includes(null)) ? null : paths.flat() as string[]
+}
+
+/** Whether a helper may start for [task] while [member] is busy (anh Dee, task #4697), all three: the task's code overlaps none of
+ * the work running (a task naming no code to compare cannot be told apart, so it waits), the Member's computer has room under
+ * its limit, and its engine's quota there is known with every window above the floor. [planned]: what this pass already plans. */
+export function helperCheck(state: SuperTabState, member: Agent, task: Conversation, now: number,
+ planned: { paths: string[]; slots: number } = { paths: [], slots: 0 }): HelperCheck {
+ const mine = (task.task?.owns ?? []).map(ownedPath)
+ const running = runningPaths(state, member)
+ if (!mine.length || mine.includes(null) || running === null
+ || mine.some(p => [...running, ...planned.paths].some(r => pathsOverlap(p!, r)))) return { ok: false, reason: 'overlap' }
+ const pool = (state.machines ?? []).find(m => m.machineId === member.machineId)
+ if (!pool || availableSlots(state, pool, machineSlots(state, pool)) - planned.slots <= 0) return { ok: false, reason: 'room' }
+ const quota = pool.observation?.quotas.find(q => q.engine === member.configuration.engine)
+ if (!quota?.known || quota.windows.some(w => 100 - w.usedPercent <= QUOTA_FLOOR_PERCENT)) return { ok: false, reason: 'quota' }
+ return { ok: true }
+}
+
+const ownPaths = (task: Conversation): string[] => (task.task?.owns ?? []).map(ownedPath).filter((p): p is string => !!p)
+
+/** What [projectId]'s dispatch pass does for the people whose tasks wait there (store.ts), each person's tasks in queue order: a
+ * helper in a task's own conversation takes it; else the free, set-up Member takes the first; while it is busy, a free helper
+ * takes one touching no running code, or a helper is started where helperCheck allows; a person with no Member yet gets one
+ * started (Accept all on API accounts gives their tasks no Accept to start it from). Anything else waits. */
+export function memberPlan(state: SuperTabState, projectId: string, now: number): MemberPick[] {
+ const people = new Set(openTasks(state, projectId, now).filter(g => !g.reviewOf && g.requesterId && state.people.some(p => p.id === g.requesterId))
+ .map(g => g.requesterId!))
+ const out: MemberPick[] = []
+ for (const personId of people) {
+ const queue = memberQueue(state, projectId, personId, now)
+ if (!queue.length) continue
+ const member = memberOf(state, personId, projectId)
+ // A person whose own crew agent works in this project keeps it taking their asks (crew.ts), until the migration
+ // (#4693 part D) makes it their Member: never two agents of theirs racing for one task.
+ if (!member && ownCrewIn(state, personId, projectId)) continue
+ if (!member) { out.push({ kind: 'start', conversationId: queue[0]!.id }); continue }
+ const lead = member.agent
+ if (!lead) continue
+ const helpers = state.agents.filter(a => a.helperOf?.agentId === lead.id && a.workDecision !== 'stop')
+ const used = new Set<string>(), planned = { paths: [] as string[], slots: 0 }
+ const take = (task: Conversation, agent: Agent) => { out.push({ kind: 'assign', conversationId: task.id, agentId: agent.id }); used.add(agent.id); planned.paths.push(...ownPaths(task)) }
+ const memberFree = freeAgent(state, lead, now) && setUpReady(state, lead, projectId)
+ // Helpers are only for while the Member holds a task: one still setting up, or asleep, is not busy.
+ const memberBusy = state.conversations.some(c => c.assignment?.agentId === lead.id && occupiesAgent(c))
+ for (const task of queue) {
+ // Its helper is starting: it takes this task once it runs.
+ if ((state.starts ?? []).some(s => s.request.helperOf && s.request.conversationId === task.id && !s.error && (!s.harnessId || !s.poolSettled))) continue
+ const own = helpers.find(h => !used.has(h.id) && task.agentIds.includes(h.id) && freeAgent(state, h, now))
+ if (own) { take(task, own); continue }
+ if (memberFree && !used.has(lead.id)) { take(task, lead); continue }
+ const idle = helpers.find(h => !used.has(h.id) && freeAgent(state, h, now))
+ if (idle && memberBusy && helperCheck(state, lead, task, now, planned).ok) { take(task, idle); continue }
+ if (!idle && memberBusy && helperCheck(state, lead, task, now, planned).ok) {
+ out.push({ kind: 'helper', conversationId: task.id }); planned.slots++; planned.paths.push(...ownPaths(task))
+ }
+ }
+ }
+ return out
+}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index dd670c81c..0e578b963 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -163,6 +163,13 @@ export interface Agent {
* joined. Readers get it in the derived row, never in this part (read/views.ts), and only when they read that project. A
* Lead's is the project it leads, derived (agentKind.ts ledProjects). Cleared when the project is deleted. */
mainProjectId?: string
+ /** A Member's own mark (members.ts, task #4697), and a helper's: the Member it helps. Set by the server alone, at its start;
+ * its host reads them in the agent's row to reopen a woken one in its folder (#4698). */
+ member?: { projectId: string }
+ helperOf?: { agentId: string; harnessId: string }
+ /** Its project set up on its computer, as its own host reported (agent.setUp, #4698): the commands it ran, or why it failed.
+ * A Member on a host that reports it takes no task until it is set up (members.ts setUpReady). */
+ setUp?: { projectId: string; at: number; steps?: string[]; failed?: string }
/** The private project a Regular agent first worked in: its one conversation holds that project's content, so it takes tasks
* only there from then on (projects.ts regularMayWorkIn; security review 2 of #4116). Set at its assignment, never cleared. */
privateProjectId?: string
@@ -222,6 +229,14 @@ export interface AgentStartRequest {
regular?: true
/** The main project its person picked (agent.new, buddy.create; task #4540), kept on the agent when it starts. */
mainProjectId?: string
+ /** A Member's own start (members.ts, task #4697): its host sets the project up once in this folder. Written by the server
+ * alone, with `regular` and `mainProjectId`. */
+ member?: { projectId: string }
+ /** A helper's start (members.ts): made from its Member's ready setup on the Member's computer, for the task it starts
+ * in. Written by the server alone. */
+ helperOf?: { agentId: string; harnessId: string }
+ /** The commands its Member recorded setting the project up (agent.setUp), for a helper's host to repeat. */
+ setUpSteps?: string[]
/** A one-project Buddy's start (Agent.buddyNarrow), written by message.send alone. */
buddyNarrow?: true
/** The person's messages in an older project chat its start waits on, delivered when it joins (ids only). */
diff --git a/backend/src/superTabs/ownedPaths.ts b/backend/src/superTabs/ownedPaths.ts
new file mode 100644
index 000000000..f0c6dc103
--- /dev/null
+++ b/backend/src/superTabs/ownedPaths.ts
@@ -0,0 +1,11 @@
+/** A task's owned paths (WorkTask.owns), compared: cross-project overlap alerts (commands.ts alertOverlaps) and the helper
+ * check (members.ts helperCheck) read them alike. */
+
+/** The repo path an owns entry names, or null for anything else (a phrase, a glob), which is never compared. */
+export function ownedPath(entry: string): string | null {
+ const path = entry.trim().replace(/^\.\//, '').replace(/\/+$/, '')
+ return /^[\w.@-]+(\/[\w.@-]+)*$/.test(path) ? path : null
+}
+
+/** Whether two owned paths overlap: the same path, or one a folder of the other. */
+export const pathsOverlap = (a: string, b: string): boolean => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`)
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 49370bf4f..839a7385d 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -27,6 +27,13 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
const leadCheck = (projectId: string | undefined) => { if (actor.kind === 'agent') group(leadGroupOf(projectId)) }
const agentProject = (id: string) => { const a = before.agents.find(x => x.id === id); return a && agentProjectId(before, a) }
/** Every slot `machineSlots` counts for a start on this machine: the Mac and its team account share them (machines.ts). */
+ /** A Member's start, from the first Accept or the dispatch pass (members.ts, task #4697): its free name is claimed on the head,
+ * and its computer's slots counted as any start's. */
+ const newMemberStarts = () => {
+ for (const start of effects.state.starts ?? []) {
+ if ((start.request.member || start.request.helperOf) && !(before.starts ?? []).some(s => s.id === start.id)) { head(); slots(start.request.machineId) }
+ }
+ }
const slots = (machineId: string) => {
const pool = before.machines?.find(m => m.machineId === machineId)
const mac: ContributedMachine | undefined = pool?.hostMachineId ? before.machines?.find(m => m.machineId === pool.hostMachineId) : pool
@@ -76,6 +83,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
member(card?.taskApproval?.personId)
agent(card?.taskApproval?.suggestedAgentId)
leadCheck(card && groupProject(before, card).id)
+ newMemberStarts()
break
}
case 'proposal.close':
@@ -124,6 +132,9 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'agent.new':
head()
break
+ case 'member.start': case 'member.helper':
+ newMemberStarts()
+ break
case 'project.report': case 'project.repository':
// The coordinator's own writes check it leads the project, which a concurrent Lead change ends (review of phase 2).
case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'project.answers': case 'project.about':
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 970059cb4..d3113ffd4 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -209,7 +209,11 @@ export function agentProjectId(state: SuperTabState, target: Agent): string {
// A Regular agent (task #4116: "the task decides where it works") is its active task's project's while it works, else none.
if (target.regular) {
const work = state.conversations.find(c => c.assignment?.agentId === target.id && activeWork(c))
- return work ? groupProject(state, work).id : NO_PROJECT
+ if (work) return groupProject(state, work).id
+ // A Member is its main project's between tasks (task #4697), while its person still reads it: that project's Lead hands it
+ // the next task, and it reports its set-up there.
+ const main = target.mainProjectId ? projectsOf(state).find(p => p.id === target.mainProjectId) : undefined
+ return main && regularMayWorkIn(state, target, main) ? main.id : NO_PROJECT
}
return target.projectId ?? state.conversations.find(c => c.agentIds.includes(target.id))?.projectId ?? 'lead'
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index c50883b0a..010967402 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -93,8 +93,10 @@ export const seenIn = (parts: ReaderView['parts']): Set<string> =>
new Set([...parts.machines.map(m => m.key), ...parts.agents.map(a => a.data.machineId)])
export function agentView(agent: Agent): AgentView {
- // A main project goes in the derived row, to its project's readers only: a private one's id says the project exists.
- const { downNamed: _named, downSince: _since, limitedUntil: _limit, roleId: _role, mainProjectId: _main, ...rest } = agent
+ // A main project goes in the derived row, to its project's readers only: a private one's id says the project exists. A
+ // Member's mark and its set-up record name it too (members.ts; security review 2 of #3575), and are its host's alone
+ // (read/hostRows.ts sends the agent as stored).
+ const { downNamed: _named, downSince: _since, limitedUntil: _limit, roleId: _role, mainProjectId: _main, member: _member, setUp: _setUp, ...rest } = agent
return withAvatarView(rest) as AgentView
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index f45d0b254..822514576 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,3 +1,4 @@
+import { memberPlan } from './members.js'
import { legacyAsks } from './boardRights.js'
import { canReadProject } from './projects.js'
import { proposalMeasures, proposalMessageMeasures } from './proposalMetrics.js'
@@ -2769,6 +2770,25 @@ export class SuperTabStore {
if (openTasks(state, project.id, now).length) skipCode(PM_IN_TEAM_ACCOUNT)
continue
}
+ // Each person's asked tasks go to their own Member (members.ts, task #4697), before the crew's lanes: a free Member gets
+ // its person's next task, and a person with none yet gets one started. Sent as its PM, as crew picks are, once per round.
+ if (lead) {
+ const memberUser: AuthUser = { sub: lead.machineOwnerId, email: '', autonomousEnv: row.autonomousEnv as AuthUser['autonomousEnv'], role: 'user' }
+ for (const pick of memberPlan(state, project.id, now)) {
+ const group = state.conversations.find(c => c.id === pick.conversationId)!
+ const command = pick.kind === 'assign' ? { type: 'work.assign' as const, conversationId: group.id, agentId: pick.agentId }
+ : { type: pick.kind === 'start' ? 'member.start' as const : 'member.helper' as const, conversationId: group.id }
+ try {
+ await this.executeOnce(memberUser, tabId, { operationId: stableId('member-dispatch', pick.kind, group.id, roundOf(group)), command },
+ undefined, undefined, false, { asProjectPm: lead.id })
+ if (pick.kind === 'assign') out.assigned++
+ } catch (error) {
+ const code = error instanceof SuperTabError ? error.code : 'unknown'
+ if (code === 'unknown') throw error
+ skipCode(code)
+ }
+ }
+ }
const free = freeCrew(state, project.id, rules, now)
if (!free.length) continue
for (const lane of laneCapacity(state, project.id, rules, now)) {
diff --git a/backend/src/superTabs/taskApproval.test.ts b/backend/src/superTabs/taskApproval.test.ts
index 5f9ea0421..fb2b3c4a3 100644
--- a/backend/src/superTabs/taskApproval.test.ts
+++ b/backend/src/superTabs/taskApproval.test.ts
@@ -63,9 +63,9 @@ describe('personal approval enforced before work', () => {
expect(() => f.runCommand({ type: 'agent.add', conversationId: id, machineId: 'host', harnessId: 'external', name: 'External',
configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null }, lead: false }, owner,
{ contribution: { machineOwnerId: owner.userId, contributorId: owner.userId } })).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))
- f.mode('autoApprove')
+ // Accept all stays off without an API account (task #4697; members.test.ts covers one with): the task still waits.
+ expect(() => f.mode('autoApprove')).toThrow(expect.objectContaining({ code: 'ACCEPT_ALL_SUBSCRIPTION' }))
expect(f.card(id).taskApproval?.state).toBe('proposal')
- expect(f.card(f.create()).taskApproval).toBeUndefined()
})
it('lets the PM suggest, lets the requester change it, and assigns only their approved choice', () => {
const f = fixture(); f.mode('review'); const id = f.create()
@@ -148,8 +148,9 @@ describe('personal approval enforced before work', () => {
expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm))
.toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))
f.runCommand({ type: 'task.approve', conversationId: id })
- f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)
- expect(f.card(id).assignment?.agentId).toBe(f.candidate)
+ // Accepted, it is the requester's ask: another person's agent never takes it by hand (security review 2 of #3575).
+ expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm))
+ .toThrow(expect.objectContaining({ code: 'ASKED_BY_ANOTHER' }))
})
it('refuses attribution to a Review requester after assignment without changing the existing task', () => {
const f = fixture()
diff --git a/backend/src/superTabs/taskApproval.ts b/backend/src/superTabs/taskApproval.ts
index 5cbceae14..21a2d6eb2 100644
--- a/backend/src/superTabs/taskApproval.ts
+++ b/backend/src/superTabs/taskApproval.ts
@@ -1,4 +1,5 @@
import { author, fail, type Actor, type Conversation, type SuperTabState } from './model.js'
+import { mayAcceptAll } from './members.js'
import { groupProject, ledProject, readConversation } from './projects.js'
export type ApprovalMode = 'autoApprove' | 'review'
@@ -18,7 +19,11 @@ export const personalApprovalCommand = (type: string): boolean =>
export function stageTaskApproval(state: SuperTabState, group: Conversation, now: number): void {
if (group.taskApproval || group.kind || group.audience || group.reviewOf) return
const member = state.people.find(p => p.id === group.requesterId)
- if (member?.approvalMode === 'review') group.taskApproval = {
+ // Ask me stages it; so does an Accept all chosen on a subscription account (task #4697: it stays off there until the vendors
+ // confirm in writing, members.ts mayAcceptAll).
+ const review = member?.approvalMode === 'review' || (member?.approvalMode === 'autoApprove' && !mayAcceptAll(state, member.id))
+ if (!member || !review) return
+ group.taskApproval = {
personId: member.id, generation: member.generation, state: 'proposal', createdAt: now,
}
}
diff --git a/docs/plans/2026-11-07-member-model-backend-plan.md b/docs/plans/2026-11-07-member-model-backend-plan.md
new file mode 100644
index 000000000..dc1a3a8cf
--- /dev/null
+++ b/docs/plans/2026-11-07-member-model-backend-plan.md
@@ -0,0 +1,90 @@
+# Agent model A, backend: a Member per person and project: implementation plan
+
+> This plan is carried out by the project's Engineer way of working (test first, task by task, one pull request), not
+> subagent-driven-development. There is no execution handoff.
+
+**Goal:** Task #4697, part A of #4693 (anh Dee 11-07 21:20). A person's first accepted task in a project creates their
+Member for it. That project's tasks they ask for go to that Member one at a time, and it sleeps between them. A helper
+starts only when three checks hold; otherwise the task waits by priority, then age. Every task a person asks for needs
+their Accept, and Accept all is refused for subscription accounts.
+
+**Architecture:** One new file, `members.ts`, holds the rules as pure functions over the loaded state. Commands call
+them: `task.approve` (the first Accept starts the Member), `member.approvalMode` (Accept all refused), `work.status` (an
+ended task puts the Member to sleep, or ends a helper when nothing waits) and a new `member.helper` command. The store's
+dispatch pass (`store.ts dispatchCrew`) gains a Member pass: a free Member or helper gets its person's next task
+through `work.assign`, sent as the project's Lead as crew picks are, and a waiting task that passes the three checks
+gets a `member.helper`. A Member is a Regular agent (`regular`) with `mainProjectId` set and the person as contributor.
+A helper also carries `helperOf` (its Member) and `helperFor` (its first task). Both start only on the person's own
+listed computer, recorded with the person as machine owner, so the host's grant check at dispatch refuses any other.
+
+**Tech Stack:** TypeScript backend, vitest.
+
+**Spec:** Task #4697's brief; #4693; `docs/specs/2026-11-07-members-and-leads.md` (replaced in its Members part by
+#4693).
+
+## Global Constraints
+
+- A Member and its helpers run only on their person's own computer and account: a listed, own, non-Team machine of the
+ person, with the person as contributor and machine owner.
+- One Member per person and project. Its name is "<free agent name> · <project>".
+- One task at a time per agent (the existing `occupiesAgent`).
+- Helper checks, all three: the task's owned paths overlap none of the paths of the person's work running in that
+ project (no owned paths cannot be told apart, so no helper); the Member's computer has a free slot under its limit
+ (`availableSlots`); the engine's quota there is known and every window is above `QUOTA_FLOOR_PERCENT`.
+- Waiting order: priority (P0 first, P2 when unset), then age (lower task number first).
+- A person's tasks go to their Member and helpers, never to another person's crew agent.
+- Accept (River's call, option 2): Accept all is refused unless every engine account on the person's computers is an API key
+ (known quota with no windows), and a stored Accept all on a subscription account stages tasks. Accept on every task by
+ default, with the test sweep it needs, is its own follow-up pull request.
+- A person whose own crew agent works in the project keeps it taking their asks until the migration (#4693 part D).
+- Host contract with #4698 (Threadland): starts carry `member`, `helperOf` and `setUpSteps`; the agent keeps `member` and
+ `helperOf`; `agent.setUp` records the set-up, and a host saying `memberSetUp` gets work only after it.
+
+## Review Focus
+
+- A person with no computer in the Swarm accepts a task: no start is made, the task's chat says why, nothing breaks.
+- A helper is asked for while another helper for the same task is starting: never two.
+- A Member's computer goes offline: no helper is started there.
+- Another person's agent never gets a task someone else asked for, by dispatch or by a helper.
+- A task with no requester (found by the Lead) still goes to crew as before.
+
+---
+
+### Task 1: Accept all only for API accounts
+
+**Files:** `members.ts` (`mayAcceptAll`), `taskApproval.ts` (`stageTaskApproval`), `commands.ts`
+(`member.approvalMode`). Test: `members.test.ts`.
+
+- [ ] Failing tests: Ask me stages; Accept all is refused for a subscription or unknown account
+ (`ACCEPT_ALL_SUBSCRIPTION`) and allowed for API-only; a stored Accept all on a subscription account still stages.
+- [ ] Implement; run; commit.
+
+### Task 2: The first Accept starts the person's Member
+
+**Files:** `members.ts` (`memberOf`, `memberMachine`), `commands.ts` (`task.approve`, `agent.started` copies
+`helperOf`/`helperFor`), `model.ts` (fields). Test: `members.test.ts`.
+
+- [ ] Failing tests: the first Accept makes one start on the person's own computer, named "<name> · <project>",
+ `regular` with `mainProjectId`; a second Accept makes none; no own computer posts one line in the task's chat and
+ starts nothing; another person's or a Team machine is never used.
+- [ ] Implement; run; commit.
+
+### Task 3: The Member takes its person's tasks one at a time and sleeps between them
+
+**Files:** `members.ts` (`memberQueue`, `memberPlan`), `store.ts` (Member pass), `commands.ts` (`work.status`),
+`dispatch.ts` (crew skips asked tasks). Test: `members.test.ts`, `integration/crewDispatch.test.ts`.
+
+- [ ] Failing tests: the queue orders by priority then age; a free Member is planned its person's next task; a busy one
+ is not; a crew agent is never planned an asked task; an ended task with nothing waiting puts the Member to sleep, and
+ its next assignment wakes it.
+- [ ] Implement; run; commit.
+
+### Task 4: Helpers by the three checks, ended when nothing waits
+
+**Files:** `members.ts` (`helperCheck`), `commands.ts` (`member.helper`, `work.status`). Test: `members.test.ts`.
+
+- [ ] Failing tests: each check alone refuses (overlap, no room, quota at the floor or unknown); all three pass starts
+ one helper for that task, on the Member's computer and account; a second request while it starts makes none; a
+ helper's ended task with nothing waiting stops it; a free helper is planned the next task only when it overlaps no
+ running work.
+- [ ] Implement; run; commit.