The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Swarm v3: personal task approval and Tasks feed (#3449)
harness-for-autonomous[bot]7356cf6330bd
diff --git a/backend/integration/superTabProposalCards.test.ts b/backend/integration/superTabProposalCards.test.tsindex 73b687426..cbc24252f 100644--- a/backend/integration/superTabProposalCards.test.ts+++ b/backend/integration/superTabProposalCards.test.ts@@ -45,6 +45,87 @@ async function fixture() {}describe('durable proposal cards', () => {+ it('persists personal Review decisions, enforces direct identity before replay, and reads only changed task summaries', async () => {+ const f = await fixture()+ const read = new SwarmReads(f.store)+ await f.execute({ type: 'member.approvalMode', mode: 'review' }, peer)+ const initial = await read.firstLoad(peer, f.tab)+ expect(initial.personalTasks).toMatchObject({ approvalMode: 'review', reset: true, upserts: [], removed: [] })+ f.clock.now += 100+ const id = String((await f.execute({ type: 'conversation.create', title: 'Own task', requesterId: peer.sub, priority: 'P2',+ task: { goal: 'Keep edits', changes: 'Restore drafts', constraints: 'No login reads', owns: ['backend/src/superTabs/'] },+ checks: [{ description: 'Restores draft', independent: false }] }, owner, f.pm)).result.conversationId)+ expect((await f.card(id)).taskApproval).toMatchObject({ personId: peer.sub, state: 'proposal' })+ f.clock.now += 100+ const changed = await read.changes(peer, f.tab, initial.cursor)+ expect(changed).toMatchObject({ reload: false, personalTasks: { reset: false, upserts: [{ id, status: 'proposal' }] } })+ const decision = { type: 'task.reject', conversationId: id, reason: 'Do later' }, operationId = randomUUID()+ await expect(f.execute(decision, owner, f.pm, operationId)).rejects.toThrow()+ await f.execute(decision, peer, undefined, operationId)+ expect((await f.card(id)).taskApproval).toMatchObject({ state: 'rejected', reason: 'Do later' })+ await expect(f.execute(decision, owner, undefined, operationId)).rejects.toThrow()+ f.clock.now = Date.now() + 60_000 // Existing cursors intentionally overlap writes by thirty seconds.+ const latest = await read.firstLoad(peer, f.tab)+ expect(latest.personalTasks!.upserts).toContainEqual(expect.objectContaining({ id, status: 'rejected', reason: 'Do later' }))+ f.clock.now += 100+ expect(await read.changes(peer, f.tab, latest.cursor)).toMatchObject({ personalTasks: { upserts: [], removed: [] } })+ const actorRead = await read.firstLoad(owner, f.tab, f.pm)+ expect(actorRead.personalTasks).toBeUndefined()+ // Revocation must invalidate a cursor before any private rows can be served again.+ await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })+ expect(await read.changes(peer, f.tab, latest.cursor)).toMatchObject({ reload: true })+ expect((await read.firstLoad(peer, f.tab)).personalTasks!.upserts).toEqual([])+ })++ it('keeps legacy Buddy delivery, carries its person gate to one task, and rejects conversion after the mirror is dormant', async () => {+ const f = await fixture()+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: false })+ await f.execute({ type: 'member.approvalMode', mode: 'review' })+ const added = await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', setup: { name: 'Fixture Mac', cwd: '/fixture', engines: ['codex'] } })+ const startId = String(added.result.startId), chatId = String(added.result.conversationId)+ const host = (command: unknown) => f.store.execute(owner, f.tab, { operationId: randomUUID(), command: commandSchema.parse(command) }, undefined, 'proposal-mac')+ await host({ type: 'agent.startDispatch', startId })+ const buddyId = String((await host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)+ await host({ type: 'agent.startSettled', startId, warning: null })+ const text = 'Keep offline drafts'+ const ask = await f.execute({ type: 'message.send', conversationId: chatId, text, recipientIds: [buddyId], replyTo: null })+ const sent = await f.execute({ type: 'buddy.propose', conversationId: chatId, projectId: 'lead', ownerMessageId: ask.result.messageId,+ text, goal: text, scope: 'Drafts', priority: 'normal' }, owner, buddyId)+ const messageId = String(sent.result.messageId)+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: f.pm, messageId } })).toBe(1)+ const create = { type: 'conversation.create', title: text, priority: 'P2', proposalMessageId: messageId,+ task: { goal: text, changes: 'Restore drafts', constraints: 'No login', owns: ['backend/src/superTabs/'] },+ checks: [{ description: 'Draft returns', independent: false }] }+ const id = String((await f.execute(create, owner, f.pm)).result.conversationId)+ expect((await f.card(id)).taskApproval).toMatchObject({ state: 'proposal', personId: owner.sub })+ const { legacyProposalId } = await import('../src/superTabs/proposalCards.js')+ const mirrorId = legacyProposalId('lead', messageId)+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: mirrorId } } })+ await db.swarmGroup.update({ where: { id: row.id }, data: { dormant: true, data: { ...(row.data as object), dormant: true }, version: { increment: 1 } } })+ await expect(f.execute(create, owner, f.pm)).rejects.toThrow()+ expect((await new SwarmReads(f.store).firstLoad(owner, f.tab)).personalTasks!.upserts.map(r => r.id)).toEqual([id])+ })+ it('keeps Auto approve automatic, then hands an approved Review choice through the normal store assignment', async () => {+ const f = await fixture(), read = new SwarmReads(f.store)+ const create = () => f.execute({ type: 'conversation.create', title: 'Keep drafts', requesterId: owner.sub, priority: 'P2',+ task: { goal: 'Keep drafts', changes: 'Restore', constraints: 'No login', owns: ['backend/src/superTabs/'] },+ checks: [{ description: 'Draft returns', independent: false }] }, owner, f.pm)+ const auto = String((await create()).result.conversationId)+ expect((await f.card(auto)).taskApproval).toBeUndefined()+ expect((await read.firstLoad(owner, f.tab)).personalTasks).toMatchObject({ approvalMode: 'autoApprove', upserts: [{ id: auto, status: 'planned' }] })+ const worker = String((await f.execute({ type: 'agent.add', conversationId: auto, machineId: 'proposal-mac', harnessId: randomUUID(), name: 'Worker', configuration: config, lead: false })).result.agentId)+ await f.execute({ type: 'member.approvalMode', mode: 'review' })+ const review = String((await create()).result.conversationId)+ await expect(f.execute({ type: 'work.assign', conversationId: review, agentId: worker }, owner, f.pm)).rejects.toThrow()+ await f.execute({ type: 'task.suggest', conversationId: review, agentId: worker }, owner, f.pm)+ const approve = { type: 'task.approve', conversationId: review }, operation = randomUUID()+ await f.execute(approve, owner, undefined, operation)+ await f.execute(approve, owner, undefined, operation)+ expect((await f.card(review))).toMatchObject({ assignment: null, taskApproval: { state: 'approved', suggestedAgentId: worker } })+ await f.execute({ type: 'work.assign', conversationId: review, agentId: worker }, owner, f.pm)+ expect((await f.card(review)).assignment).toMatchObject({ agentId: worker, status: 'working' })+ expect((await read.firstLoad(owner, f.tab)).personalTasks!.upserts).toContainEqual(expect.objectContaining({ id: review, status: 'working', agent: { id: worker, name: expect.any(String) } }))+ })it('turns verified unanswered original messages into cards once on switch, preserving words and ownership', async () => {const f = await fixture()await f.execute({ type: 'project.boardMode', projectId: 'lead', on: false })diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex 096dde250..cc0608e8d 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -195,7 +195,8 @@ describe('first load (design 4.3)', () => {const { status, body } = await get(`/api/super-tabs/${s.tabId}/parts`, peer)expect(status).toBe(200)expect(Object.keys(body.data).sort()).toEqual(['agents', 'cursor', 'derived', 'derivedEtag', 'epoch', 'format', 'groups', 'head', 'lastChangedAt',- 'machines', 'members', 'progress', 'serverTime', 'starts', 'steps', 'tabId'].sort())+ 'machines', 'members', 'personalTasks', 'progress', 'serverTime', 'starts', 'steps', 'tabId'].sort())+ expect(body.data.personalTasks).toEqual({ approvalMode: 'autoApprove', reset: true, upserts: [], removed: [] })expect(body.data).toMatchObject({ format: 2, tabId: s.tabId, serverTime: NOW, epoch: 1, lastChangedAt: MIGRATED, steps: true,head: { key: 'head', version: R, changedAt: MIGRATED, data: { id: s.tabId, name: 'Pilot' } } })expect(JSON.parse(Buffer.from(body.data.cursor, 'base64url').toString())).toEqual({ v: 2, t: NOW - 30_000, e: 1 })diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex be36abe78..2d38b3a70 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -782,10 +782,10 @@ describe('a Buddy\'s proposal to the PM', () => {})it('gives a task opened from it the proposal\'s goal, scope and priority as its brief, unless the PM writes one', () => {- const { f, propose } = asked()- const root = propose().messages[0]!- const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }const open = (brief: string) => {+ const { f, propose } = asked()+ const root = propose().messages[0]!+ const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }const id = f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline drafts', brief, checks: [{ description: 'Done', independent: false }], proposalMessageId: root.id },agentActor(f.pm), context).result.conversationIdreturn group(f, id as string)@@ -795,17 +795,20 @@ describe('a Buddy\'s proposal to the PM', () => {})it('gives a task opened from it the proposal\'s priority on the one P0-P3 scale, unless the PM gives one (task #3117)', () => {- const { f, propose } = asked()- const root = propose().messages[0]!- const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }- const open = (fields: Record<string, unknown> = {}) => f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline drafts',- brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: root.id, ...fields } as Command, agentActor(f.pm), context).result+ const open = (fields: Record<string, unknown> = {}) => {+ const { f, propose } = asked()+ const root = propose().messages[0]!+ const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }+ const result = f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline drafts',+ brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: root.id, ...fields } as Command, agentActor(f.pm), context).result+ return { result, task: group(f, result.conversationId as string) }+ }// Its Buddy said high: a P1, with no warning that none was given.- const opened = open()+ const { result: opened, task } = open()expect(opened).toMatchObject({ priority: 'P1' })expect(opened.warnings ?? []).not.toContainEqual(expect.stringContaining('No priority given'))- expect(group(f, opened.conversationId as string).priority).toBe('P1')- expect(group(f, open({ priority: 'P0' }).conversationId as string).priority).toBe('P0')+ expect(task.priority).toBe('P1')+ expect(open({ priority: 'P0' }).task.priority).toBe('P0')})it('counts as shown only the Buddy\'s own lines in the ask\'s lane, since its owner\'s previous message', () => {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex d930ed20e..1e4189fe1 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,5 +1,6 @@+import { authorizeTaskApproval, pendingTaskApproval, personalApprovalCommand, requireTaskApproval, stageTaskApproval } from './taskApproval.js'import type { PullRequestFilesRead } from './pullRequestFiles.js'-import { migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'+import { legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'import { applyPushOrigin, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'import { crewMoveFailed, takeOverCrewMember, wakeCrewMember } from './crewKeep.js'@@ -431,6 +432,10 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('invite.accept'), inviteId: id }).strict(),z.object({ type: z.literal('member.remove'), userId: id }).strict(),z.object({ type: z.literal('member.status'), status: statusSchema.nullable() }).strict(),+ z.object({ type: z.literal('member.approvalMode'), mode: z.enum(['autoApprove', 'review']) }).strict(),+ z.object({ type: z.literal('task.suggest'), conversationId: id, agentId: id }).strict(),+ z.object({ type: z.literal('task.approve'), conversationId: id }).strict(),+ z.object({ type: z.literal('task.reject'), conversationId: id, reason: z.string().trim().min(1).max(2000) }).strict(),z.object({ type: z.literal('member.timeZone'), timeZone: z.string().min(1).max(64).nullable() }).strict(),z.object({ type: z.literal('member.avatar'), avatar: avatarChoice }).strict(),z.object({ type: z.literal('member.username'), username: z.string().max(64).nullable() }).strict(),@@ -528,6 +533,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'conversation.rename': ['title'],'buddy.rename': ['name'],'proposal.close': ['reason'],+ 'task.reject': ['reason'],'work.define': ['brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'task.review.focus', 'checks[].description'],'work.assign': ['overrideReason'],'work.status': ['result'],@@ -848,6 +854,11 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma// So does choosing one's own username (usernames.ts) or name (personNames.ts), and one's app telling one's time zone.if (command.type === 'mention.done' || command.type === 'decision.answer' || command.type === 'member.username'|| command.type === 'member.name' || command.type === 'member.timeZone') return void author(state, actor)+ if (personalApprovalCommand(command.type)) {+ authorizeTaskApproval(state, actor, command.type, 'conversationId' in command ? command.conversationId : undefined)+ if ('agentId' in command) readAgent(state, actor, command.agentId)+ return+ }const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userIdauthor(state, actor, !leaving && !viewerProposal(state, actor, command))const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined@@ -1152,7 +1163,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (command.type === 'swarm.delete' && (actor.kind !== 'person' || actor.userId !== state.ownerId)) notThere()const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userIdconst sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username'- && command.type !== 'member.name' && command.type !== 'member.timeZone' && !viewerProposal(state, actor, command))+ && command.type !== 'member.name' && command.type !== 'member.timeZone' && !personalApprovalCommand(command.type) && !viewerProposal(state, actor, command))authorizeCommandAccess(state, actor, command, context)/** A machine's owner said so: they sent the command, or the Lead of the chat [askedIn] names passes on a message they wrote* there in the last day, as routing rules are (machine.engineResume, machine.projects). */@@ -1794,8 +1805,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,/** Every check work.assign makes before [worker] takes [group]'s work, throwing its refusal; nothing changes here, so a* caller trying candidates in turn (openReviewSteps) catches the refusal and tries the next. */- const assignRefusal = (group: Conversation, worker: Agent) => {- if (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '')) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before assigning work.', 409)+ const assignRefusal = (group: Conversation, worker: Agent, suggestion = false) => {+ if (!suggestion) requireTaskApproval(group, worker.id)+ if (!suggestion && group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '')) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before assigning work.', 409)if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === worker.machineId && s.harnessId === worker.harnessId)) {fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')}@@ -2750,6 +2762,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!reviewed || isLeads(reviewed) || reviewed.kind || reviewed.audience || reviewed.id === project.leadConversationId|| groupProject(state, reviewed).id !== project.id) fail('NOT_FOUND', 'This conversation is unavailable.', 404)open(state, reviewed.id)+ requireTaskApproval(reviewed)// One level: a step's own work is a task's step, never a task with steps of its own (task steps design).if (command.step && isStep(reviewed)) fail('STEP_OF_STEP', 'A step belongs to a task, not to another step.', 400)// Never doubled (task #3602: #3561 got its server's Security reviews and Test, then its Engineer's review, review and@@ -2809,6 +2822,17 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,})stampLane(state.conversations.at(-1)!, (context.projectRules?.rules ?? SEED_RULES).lanes)recordAsked(state.conversations.at(-1)!, requesterId, context.now)+ const created = state.conversations.at(-1)!+ if (proposal) {+ const mirror = state.conversations.find(c => c.id === legacyProposalId(project.id, proposal.messageId))+ if (mirror?.proposal?.mergedInto) fail('PROPOSAL_DECIDED', 'This proposal already became a task.', 409)+ if (mirror?.taskApproval) {+ if (requesterId !== mirror.taskApproval.personId) fail('TASK_APPROVAL_FORBIDDEN', 'Keep the proposal’s requesting person.', 403)+ created.taskApproval = { ...mirror.taskApproval }+ }+ if (mirror?.proposal) { mirror.proposal.mergedInto = created.id; mirror.archived = true }+ }+ stageTaskApproval(state, created, context.now)if (command.reviewOf) listStep(conversation(state, command.reviewOf), operationId)// The reason stands only where nobody is named, and is shown in the task's first row beside its goal.const noRequester = !requesterId && actor.kind === 'agent' ? command.noRequesterReason : undefined@@ -2863,13 +2887,22 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,chatOnly(command.conversationId)projectChatWork(command.conversationId)const group = open(state, command.conversationId)+ if (group.taskApproval && command.personId !== group.taskApproval.personId) fail('TASK_APPROVAL_FORBIDDEN', 'Keep the original requesting person on a task with an approval decision.', 403)// 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' && 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)+ if (command.personId) {+ const next = requester(state, groupProject(state, group), command.personId)+ if (next !== group.requesterId) {+ group.requesterId = next+ stageTaskApproval(state, group, context.now)+ if (group.assignment && group.taskApproval?.state === 'proposal')+ fail('TASK_APPROVAL_REQUIRED', 'Cannot attribute assigned work to a person who must approve it first.', 409)+ }+ }else delete group.requesterIdbreak}@@ -3028,6 +3061,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,break}case 'agent.add': {+ requireTaskApproval(conversation(state, command.conversationId), state.agents.find(a => a.machineId === command.machineId && a.harnessId === command.harnessId)?.id ?? null)if (!['claude', 'codex'].includes(command.configuration.engine)) fail('SWARM_ENGINE', 'A Swarm agent runs only Claude Code or Codex.', 400)// A person shares a session already running (Desktop sends this as its person); an agent starts a new one. From an// agent it re-added a person's Buddy to a task, added to the project chat, and registered any session of its@@ -3123,6 +3157,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,break}case 'agent.start': {+ requireTaskApproval(conversation(state, command.request.conversationId), null)const proposed = conversation(state, command.request.conversationId).proposalif (proposed && !['accept', 'reshape'].includes(proposed.decision?.kind ?? '')) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before starting work.', 409)chatOnly(command.request.conversationId)@@ -3279,6 +3314,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,break}if (!['low', 'normal', 'high'].includes(command.priority)) fail('BOARD_MODE_REQUIRED', 'P0–P3 proposal priorities require proposal cards.', 409)+ const mirror = createProposalCard(state, project, { personId: owner.id, generation: owner.generation, buddyId: self.id }, {+ title: command.title ?? command.goal.slice(0, 160), text: words, goal: command.goal,+ why: command.why ?? command.scope, doneWhen: command.doneWhen ?? 'The PM prepares the acceptance checks.',+ evidence: command.evidence ?? ['Consented Buddy request'], priority: proposalPriority(command.priority),+ }, legacyProposalId(project.id, operationId), context.now, true)+ mirror.proposal!.legacyMessageId = operationId+ mirror.proposal!.scope = command.scope// One message, its owner's, delivered to the PM: its goal, scope and priority ride in its source for the PM and the task's// brief (proposalBrief), with no reply from the Buddy in the chat (anh Dee, task #2926).message(home.id, words, home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [], null,@@ -3296,6 +3338,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const project = readProject(state, actor, command.projectId)if (actor.kind === 'agent') coordinatorOf(project)const { messageId } = proposalOf(state, project, proposalNamed(context.proposal))+ const mirror = state.conversations.find(c => c.id === legacyProposalId(project.id, messageId))+ if (mirror?.proposal && !mirror.proposal.mergedInto) {+ mirror.archived = true+ mirror.proposal.decision = { kind: 'no', reason: command.reason, at: context.now, by: sender.id }+ }effects.closedProposal = { messageId, conversationId: project.leadConversationId, reason: command.reason }result.proposalId = messageIdbreak@@ -4402,6 +4449,37 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,marking(group, () => applyPushOrigin(state, group, 'team', context.pushOriginPulls))break}+ case 'member.approvalMode': {+ if (actor.kind !== 'person') fail('TASK_APPROVAL_FORBIDDEN', 'Choose your mode as a person.', 403)+ person(state, actor.userId).approvalMode = command.mode+ break+ }+ case 'task.suggest': case 'task.approve': case 'task.reject': {+ const group = authorizeTaskApproval(state, actor, command.type, command.conversationId)!+ const approval = command.type === 'task.suggest' && group.taskApproval?.state === 'approved' && !group.assignment+ ? group.taskApproval : pendingTaskApproval(group)+ if (group.archived) fail('ARCHIVED', 'Reopen this conversation before deciding its work.')+ if (command.type === 'task.suggest') {+ const worker = readAgent(state, actor, command.agentId)+ assignRefusal(group, worker, true)+ approval.suggestedAgentId = worker.id+ // A new worker choice never inherits an earlier decision, even before the first assignment.+ approval.state = 'proposal'+ delete approval.decidedAt+ } else {+ approval.state = command.type === 'task.approve' ? 'approved' : 'rejected'+ approval.decidedAt = context.now+ if (command.type === 'task.reject') approval.reason = command.reason+ // 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.+ if (command.type === 'task.approve' && approval.suggestedAgentId)+ assignRefusal(group, readAgent(state, actor, approval.suggestedAgentId), true)+ message(group.id, command.type === 'task.approve' ? 'Approved. Prepare and route this task using its chosen agent, if any.' : `Rejected: ${command.reason}`,+ group.leadId ? [group.leadId] : [], null, { kind: 'task-approval', state: approval.state })+ }+ result.conversationId = group.id+ break+ }case 'work.assign': {chatOnly(command.conversationId)projectChatWork(command.conversationId)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 08b59d450..82b224308 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -15,6 +15,8 @@ import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProjecexport type Role = 'owner' | 'collaborator' | 'viewer'export interface Person {+ /** Own future task decisions; absent keeps Auto approve. */+ approvalMode?: import('./taskApproval.js').ApprovalModeid: stringemail: stringrole: Role@@ -382,6 +384,8 @@ export function renderWorkTask(task: WorkTask): string {}export interface Conversation {+ /** Person decision, separate from execution status for old clients. */+ taskApproval?: import('./taskApproval.js').TaskApprovalid: string/** The removed Swarm-wide Leads conversation, still stored in an older Swarm (leadsRemoved), a person's Buddy chat in a* project (buddies.ts), or their one Buddy chat for the whole Swarm, with no project (`swarm-buddy`, buddies.ts@@ -803,6 +807,8 @@ export const NOTICE_READERS = {'notice-digest': 'recipients',// An agent's tag, ask or line to a person, routed to the PM instead (crewNeeds.ts): the PM's alone. Never gathered.'crew-need': 'recipients',+ // A person's decision wakes the task's PM; people read the decision in Tasks.+ 'task-approval': 'recipients',// Each its own case in commands.ts, decided by the row (forRecipients): statuses, briefs, merges, starts, removals.system: 'people',// A save of the project's instructions was posted in the project chat until #3132 (Dee and Ken, 11-05): the rows storeddiff --git a/backend/src/superTabs/notices.test.ts b/backend/src/superTabs/notices.test.tsindex 777637564..42f6133ef 100644--- a/backend/src/superTabs/notices.test.ts+++ b/backend/src/superTabs/notices.test.ts@@ -109,4 +109,9 @@ describe('the notices the Swarm writes into a chat', () => {expect(agentOnly({ kind: 'from-a-newer-server' }, ['lead'])).toBe(false)expect(agentOnly(undefined, [])).toBe(false)})++ it('keeps the PM’s task decision wake out of people’s chat while it reaches the PM', () => {+ expect(agentOnly({ kind: 'task-approval', state: 'approved' }, ['lead'])).toBe(true)+ expect(agentOnly({ kind: 'task-approval', state: 'rejected' }, [])).toBe(false)+ })})diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 4e2fb3670..d22faa85b 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -91,6 +91,7 @@ const conversation: Required<Conversation> = {stuck: { key: 'k', messageId: 'm', tagged: [], fixed: 'f' },talkedAt: { w: { person: 1, answer: 2 } },task: { goal: '', changes: '', constraints: '', owns: [] },+ taskApproval: { personId: 'p', generation: 'g', state: 'proposal', createdAt: 1 },teamWritten: true,teamWrittenBy: { kind: 'assigned' },title: 't',diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 089348079..a035c4257 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -42,6 +42,7 @@ export const GROUP_FIELDS = {'proposal','pulse','reviewOf',+ 'taskApproval',],whenRunning: ['assignment.execution',diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 0e1581b28..b8693341e 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -70,6 +70,18 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStateif (buddy) machine(buddy.machineId)break}+ case 'task.suggest': case 'task.approve': case 'task.reject': {+ head()+ const card = before.conversations.find(c => c.id === command.conversationId)+ member(card?.taskApproval?.personId)+ agent(card?.taskApproval?.suggestedAgentId)+ leadCheck(card && groupProject(before, card).id)+ break+ }+ case 'proposal.close':+ head()+ leadCheck(command.projectId)+ breakcase 'proposal.create':head()group(leadGroupOf(command.projectId))@@ -145,6 +157,8 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStategroup(leadGroupOf(projectId))group(command.reviewOf)member(command.requesterId)+ for (const created of effects.state.conversations.filter(c => !before.conversations.some(b => b.id === c.id))) member(created.requesterId)+ if (command.proposalMessageId) head()break}case 'conversation.merged':diff --git a/backend/src/superTabs/proposalCards.ts b/backend/src/superTabs/proposalCards.tsindex 03f8f7775..89332f62c 100644--- a/backend/src/superTabs/proposalCards.ts+++ b/backend/src/superTabs/proposalCards.ts@@ -1,3 +1,4 @@+import { stageTaskApproval } from './taskApproval.js'import { steers } from './boardRights.js'import { expireProposalQuestion } from './proposalClock.js'export { advanceProposalCards, proposalDueAt } from './proposalClock.js'@@ -58,8 +59,8 @@ export function cardPriority(state: SuperTabState, project: SwarmProject, ownerI}export function createProposalCard(state: SuperTabState, project: SwarmProject, sender: ProposalSender,- input: Omit<CreateProposal, 'type' | 'projectId'>, id: string, now: number): Conversation {- requireBoard(project)+ input: Omit<CreateProposal, 'type' | 'projectId'>, id: string, now: number, legacyMirror = false): Conversation {+ if (!legacyMirror) requireBoard(project)const member = state.people.find(p => p.id === sender.personId && p.generation === sender.generation)if (!member || !canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) fail('NOT_FOUND', 'This project is unavailable.', 404)const parsed = proposalCreateSchema.parse({ type: 'proposal.create', projectId: project.id, ...input })@@ -72,6 +73,7 @@ export function createProposalCard(state: SuperTabState, project: SwarmProject,requesterId: member.id, priority, codePullRequestUrls: [],proposal: { version: 1, text: parsed.text, goal: parsed.goal, why: parsed.why, doneWhen: parsed.doneWhen,evidence: parsed.evidence, priority, createdAt: now, senders: [sender], questions: [] } }+ stageTaskApproval(state, card, now)state.conversations.push(card)return card}@@ -218,8 +220,10 @@ export function applyProposalAction(state: SuperTabState, actor: Actor, command:row(`${command.decision}: ${command.reason}`, { kind: 'proposal-decision', decision: command.decision })messages.push(...proposalNotices(state, card, 'decided', `${card.title}: ${command.decision}. ${command.reason}`, sender, operationId))} else {+ if (card.taskApproval) fail('TASK_APPROVAL_REQUIRED', 'Keep Review proposals separate so each person’s decision and chosen agent stay attached.', 409)pending(card)const target = namedCard(state, actor, command.intoConversationId)+ if (target.taskApproval) fail('TASK_APPROVAL_REQUIRED', 'Keep Review proposals separate so each person’s decision and chosen agent stay attached.', 409)pending(target)if (target.id === card.id) fail('PROPOSAL_MERGE_SELF', 'Merge another proposal into this card.', 400)if (hasOpenQuestion(card)) fail('PROPOSAL_QUESTION_OPEN', 'Answer the source card’s questions before merging.', 409)diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 047768f99..4dd2fd044 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -166,6 +166,8 @@ interface ReadMeta {/** GET /api/super-tabs/:tabId/parts[?asAgentId=] */export interface FirstLoad extends ReadMeta {+ /** Own active Tasks; absent for agent readers and older servers. */+ personalTasks?: import('./personalTasks.js').PersonalTaskstabId: stringgithubApp?: true/** This backend opens a task's steps (`conversation.create` with `step`, task steps design); absent on an older one. */@@ -197,6 +199,8 @@ export interface MachineReading { key: string; version: number; receivedAt: numb/** GET /api/super-tabs/:tabId/machine-readings[?asAgentId=]: every machine the reader sees, whole, for the route and the machine panel. */export interface MachineReadings { format: number; serverTime: number; machines: LivePart<MachineView>[] }export interface ChangesDelta extends ReadMeta {+ /** Only summaries changed since this response’s existing cursor. */+ personalTasks?: import('./personalTasks.js').PersonalTasksreload: falsehead: LivePart<HeadView> | nullmembers: PartChange<MemberView>[]diff --git a/backend/src/superTabs/read/personalTasks.test.ts b/backend/src/superTabs/read/personalTasks.test.tsnew file mode 100644index 000000000..1f55c046a--- /dev/null+++ b/backend/src/superTabs/read/personalTasks.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest'+import { personalTasksFor } from './personalTasks.js'+import { readerView } from './views.js'+import { fullSwarm, NOW, owner, peer, outsider } from './fixture.test-support.js'+import * as parts from '../parts/index.js'+import type { Actor } from '../model.js'++function scene() {+ const f = fullSwarm()+ f.edit(s => {+ const member = s.people.find(p => p.id === peer.userId)!+ member.approvalMode = 'review'+ s.people.find(p => p.id === owner.userId)!.approvalMode = 'review'+ Object.assign(s.conversations.find(c => c.id === f.web)!, { requesterId: member.id,+ taskApproval: { personId: member.id, generation: member.generation, state: 'approved', createdAt: NOW - 50 } })+ Object.assign(s.conversations.find(c => c.id === f.secretGroup)!, { requesterId: member.id })+ })+ const stored = parts.split(f.state, { tabId: 'tab', version: 7, now: NOW })+ const view = (actor: Actor = peer) => readerView(stored, actor, NOW, { teamMachines: [] })+ return { f, stored, view }+}++describe('personal Tasks summaries', () => {+ it('includes only my visible requested tasks and proposals, with project, assigned identity and execution status', () => {+ const s = scene(), feed = personalTasksFor(s.stored.groups, s.view(), peer, true)!+ expect(feed).toMatchObject({ approvalMode: 'review', reset: true, removed: [] })+ expect(feed.upserts.map(r => r.id)).toEqual(expect.arrayContaining([s.f.web, s.f.secretGroup]))+ expect(feed.upserts.find(r => r.id === s.f.web)).toMatchObject({ version: 7, at: NOW, projectId: 'lead', projectName: 'Pilot',+ title: 'Web', status: 'working', suggested: false, agent: { id: s.f.worker, name: expect.any(String) } })+ expect(feed.upserts.some(r => r.id === s.f.done || r.id === s.f.buddyChat)).toBe(false)+ expect(personalTasksFor(s.stored.groups, s.view(outsider), outsider, true)!.upserts).toEqual([])+ const agent: Actor = { kind: 'agent', agentId: s.f.lead, machineOwnerId: `${owner.userId}-machine` }+ expect(personalTasksFor(s.stored.groups, s.view(agent), agent, true)).toBeUndefined()+ })+ it('shows proposal/rejected, suggested identity and reason, newest first with stable id ties', () => {+ const s = scene(), group = s.stored.groups.find(g => g.key === s.f.web)!+ const data = group.data!+ data.assignment = null+ data.taskApproval = { ...data.taskApproval!, state: 'proposal', suggestedAgentId: s.f.worker }+ const proposal = { ...structuredClone(group), key: 'proposal', changedAt: NOW + 1,+ data: { ...structuredClone(data), id: 'proposal', taskApproval: { ...data.taskApproval!, state: 'rejected' as const, reason: 'Too much scope' } } }+ const feed = personalTasksFor([group, proposal], s.view(), peer, true)!+ expect(feed.upserts.map(r => [r.id, r.status])).toEqual([['proposal', 'rejected'], [s.f.web, 'proposal']])+ expect(feed.upserts[0]).toMatchObject({ reason: 'Too much scope', suggested: true, agent: { id: s.f.worker } })+ })+ it('returns one changed summary or idle empty output; removes archived, reassigned, merged and deleted cards', () => {+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!+ expect(personalTasksFor([], s.view(), peer, false)!.upserts).toEqual([])+ expect(personalTasksFor([row], s.view(), peer, false)!.upserts.map(r => r.id)).toEqual([row.key])+ for (const change of [{ archived: true }, { requesterId: owner.userId, taskApproval: undefined }, { dormant: true }]) {+ const changed = { ...row, data: { ...row.data!, ...change } }+ expect(personalTasksFor([changed], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [row.key] })+ }+ expect(personalTasksFor([{ ...row, deleted: true }], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [row.key] })+ expect(personalTasksFor([{ ...row, data: { ...row.data!, proposal: { mergedInto: 'other' } as never } }], s.view(), peer, false))+ .toMatchObject({ upserts: [], removed: [row.key] })+ })+ it('never leaks a hidden project, private chat, hidden agent or stale membership proposal', () => {+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.secretGroup)!+ const hidden = s.f.state.agents.find(a => a.projectId === s.f.secret)+ s.stored.head.data!.projects!.find(p => p.id === s.f.secret)!.members = []+ expect(personalTasksFor([row], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [] })+ const web = s.stored.groups.find(g => g.key === s.f.web)!+ web.data!.assignment!.agentId = hidden?.id ?? 'hidden-agent'+ expect(personalTasksFor([web], s.view(), peer, true)!.upserts[0]!.agent).toBeNull()+ web.data!.taskApproval!.generation = 'old-membership'+ expect(personalTasksFor([web], s.view(), peer, true)!.upserts).toEqual([])+ })+ it('shows legacy or Board proposals before a task exists, without duplicate merged mirrors', () => {+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!+ delete row.data!.taskApproval+ row.data!.assignment = null+ row.data!.proposal = { version: 1, text: 'Keep drafts', goal: 'Drafts', why: 'Loss', doneWhen: 'Returns', evidence: ['Repro'], priority: 'P2',+ createdAt: NOW, questions: [], senders: [{ personId: peer.userId, generation: s.f.state.people.find(p => p.id === peer.userId)!.generation }] }+ expect(personalTasksFor([row], s.view(), peer, true)!.upserts[0]!.status).toBe('proposal')+ row.data!.proposal.mergedInto = 'prepared-task'+ expect(personalTasksFor([row], s.view(), peer, false)!.removed).toEqual([row.key])+ })+})diff --git a/backend/src/superTabs/read/personalTasks.ts b/backend/src/superTabs/read/personalTasks.tsnew file mode 100644index 000000000..f187ddfe2--- /dev/null+++ b/backend/src/superTabs/read/personalTasks.ts@@ -0,0 +1,60 @@+import type { Actor, Conversation } from '../model.js'+import type { Part } from '../parts/types.js'+import { canReadGroup, groupProject } from '../projects.js'+import type { ApprovalMode } from '../taskApproval.js'+import type { AgentView } from './contract.js'+import type { ReaderView } from './views.js'++export interface PersonalTask {+ id: string+ version: number+ at: number+ projectId: string+ projectName: string+ title: string+ agent: { id: string; name: string; avatar?: AgentView['avatar'] } | null+ status: import('../model.js').WorkStatus | 'proposal' | 'rejected'+ suggested: boolean+ reason?: string+}+export interface PersonalTasks {+ approvalMode: ApprovalMode+ reset: boolean+ upserts: PersonalTask[]+ removed: string[]+}++/** First load supplies its active groups; a poll supplies only its changed parts. No history read or second cursor. */+export function personalTasksFor(changed: readonly Part[], view: ReaderView, actor: Actor, reset: boolean): PersonalTasks | undefined {+ if (actor.kind !== 'person') return undefined+ const member = view.state.people.find(p => p.id === actor.userId)+ if (!member) return undefined+ const agents = new Map(view.parts.agents.map(a => [a.key, a.data]))+ const out: PersonalTasks = { approvalMode: member.approvalMode ?? 'autoApprove', reset, upserts: [], removed: [] }+ for (const part of changed) {+ if (part.kind !== 'group' || !part.data) continue+ const group = part.data as Conversation+ // Every id, including a removal's, passes today's read rules; revocation uses the existing visibility epoch reload.+ try { if (!canReadGroup(view.state, actor, group)) continue } catch { continue }+ if (group.kind || group.audience || group.reviewOf) continue+ const project = groupProject(view.state, group)+ if (group.id === project.leadConversationId) continue+ const approval = group.taskApproval+ const own = approval ? approval.personId === member.id && approval.generation === member.generation+ : group.proposal ? group.proposal.senders.some(s => s.personId === member.id && s.generation === member.generation)+ : group.requesterId === member.id+ if (part.deleted || part.dormant || group.archived || group.dormant || group.proposal?.mergedInto || !own) {+ if (!reset) out.removed.push(part.key)+ continue+ }+ const worker = agents.get(group.assignment?.agentId ?? approval?.suggestedAgentId ?? '')+ const status = approval?.state === 'proposal' || approval?.state === 'rejected' ? approval.state+ : group.assignment?.status ?? (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '') ? 'proposal' : 'planned')+ out.upserts.push({ id: group.id, version: part.version, at: part.changedAt, projectId: project.id, projectName: project.name,+ title: group.title, status, suggested: !group.assignment && !!approval?.suggestedAgentId,+ agent: worker ? { id: worker.id, name: worker.displayName ?? worker.name, ...worker.avatar ? { avatar: worker.avatar } : {} } : null,+ ...approval?.reason ? { reason: approval.reason } : {} })+ }+ out.upserts.sort((a, b) => b.at - a.at || a.id.localeCompare(b.id))+ return out+}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex cdc081c68..079e0dff3 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -1,3 +1,4 @@+import { personalTasksFor } from './personalTasks.js'/*** The read API by parts (design section 4; shapes in contract.ts). Every read takes its time `T0` before any query and* makes the next cursor from it, so a write that commits late, inside the overlap, is still seen by the next poll.@@ -133,6 +134,7 @@ export class SwarmReads {return { format: READ_FORMAT, tabId, cursor: cursorFor(t0, loaded.visibilityEpoch), serverTime: t0, lastChangedAt, epoch: loaded.visibilityEpoch,// This backend opens steps (task steps design): a newer CLI sends `step` only to a backend that says so....(this.options.githubApp ? { githubApp: true as const } : {}), steps: true as const, ...view.parts,+ ...read.actor.kind === 'person' ? { personalTasks: personalTasksFor(loaded.groups, view, read.actor, true) } : {},...stamped({ ...await this.withAvatars(view, t0), ...readableMarks(read, await this.marksOf(tx, tabId, read.actor),await this.threadMarksOf(tx, tabId, read.actor), await this.settingsOf(tx, tabId, read.actor)) }) }})@@ -219,6 +221,7 @@ export class SwarmReads {if (!asAgentId) sent.groups = await this.servedTops.served(tabId, read.view.state, sent.groups)return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,epoch: read.parts.visibilityEpoch, ...sent,+ ...read.actor.kind === 'person' ? { personalTasks: personalTasksFor(changed, read.view, read.actor, false) } : {},...stamped({ ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks, threadMarks, settings) }, options.derivedEtag) }})}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex a1b84a33e..b64d045f0 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1117,6 +1117,15 @@ export class SuperTabStore {const project = projectsOf(state).find(p => p.id === command.projectId)if (project) groupIds.push(...legacyAsks(state, project).slice(0, 100).map(a => legacyProposalId(project.id, a.messageId)))}+ // Legacy proposal mirrors can be archived after conversion. Load the exact mirror even then, so a second+ // conversion cannot manufacture a fresh task without the original person's decision. Same bounded message-id read+ // as the proposal context below; a reply's root is still verified by proposalNamed before any command applies.+ if (command.type === 'conversation.create' && command.proposalMessageId || command.type === 'proposal.close') {+ const messageId = command.type === 'conversation.create' ? command.proposalMessageId! : command.messageId+ const row = await tx.superTabMessage.findFirst({ where: { id: messageId, tabId }, select: { id: true, conversationId: true, replyTo: true, source: true } })+ const project = row && projectsOf(state).find(p => p.leadConversationId === row.conversationId)+ if (project && row) groupIds.push(legacyProposalId(project.id, !row.source && row.replyTo ? row.replyTo : row.id))+ }if (command.type === 'proposal.merge') {groupIds.push(command.intoConversationId)const card = state.conversations.find(c => c.id === command.conversationId)diff --git a/backend/src/superTabs/taskApproval.test.ts b/backend/src/superTabs/taskApproval.test.tsnew file mode 100644index 000000000..e52f4b91c--- /dev/null+++ b/backend/src/superTabs/taskApproval.test.ts@@ -0,0 +1,240 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, authorizeCommandAccess, commandSchema, withoutCredentials, type CommandContext } from './commands.js'+import { fullSwarm, NOW, owner, peer, outsider } from './read/fixture.test-support.js'+import type { Actor } from './model.js'+import { openTasks } from './dispatch.js'+import { queueSiblings } from './taskQueue.js'+import { touchesFor } from './parts/touches.js'+import { GROUP_FIELDS } from './parts/light.js'++const words = 'Keep offline edits.'+const task = { goal: words, changes: 'Persist drafts', constraints: 'No sign-in', owns: ['backend/src/superTabs/'] }+function fixture(board = true) {+ const f = fullSwarm(NOW)+ if (board) f.state.projects![0]!.boardMode = true+ else delete f.state.projects![0]!.boardMode+ const candidate = f.add('candidate', f.web), other = f.add('other-candidate', f.web)+ let seq = 0+ const pm: Actor = { kind: 'agent', agentId: f.lead, machineOwnerId: `${owner.userId}-machine` }+ const buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }+ const run = (value: unknown, actor: Actor = peer, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(f.state, actor, commandSchema.parse(value), { now: NOW, operationId: `approval-${++seq}`, ...context })+ f.edit(s => Object.assign(s, effects.state))+ return effects+ }+ const card = (id: unknown) => f.state.conversations.find(c => c.id === id)!+ const mode = (mode: string) => run({ type: 'member.approvalMode', mode })+ const create = () => run({ type: 'conversation.create', title: 'Offline drafts', task, priority: 'P2', requesterId: peer.userId,+ checks: [{ description: 'Restores drafts' }] }, pm).result.conversationId as string+ const propose = () => run({ type: 'buddy.propose', conversationId: f.buddyChat, projectId: 'lead', ownerMessageId: 'ask',+ text: words, goal: words, scope: 'Drafts', priority: 'normal', why: 'Lost edits', doneWhen: 'Drafts return', evidence: ['Reproduction'] }, buddy, {+ proposalAsk: { id: 'ask', conversationId: f.buddyChat, source: false, author: { kind: 'person', id: peer.userId, name: 'Peer',+ membershipGeneration: f.state.people.find(p => p.id === peer.userId)!.generation }, text: words,+ createdAt: NOW, newestOwnerMessageId: 'ask', shown: [] } })+ return Object.assign(f, { runCommand: run, card, mode, create, propose, pm, buddyActor: buddy, candidate, other })+}++describe('personal approval enforced before work', () => {+ it('keeps default Auto approve unchanged and persists only the acting person’s mode', () => {+ const f = fixture(), id = f.create()+ expect(f.card(id).taskApproval).toBeUndefined()+ expect(f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm).result.assignmentId).toBeTruthy()+ f.mode('review')+ expect(f.state.people.find(p => p.id === peer.userId)?.approvalMode).toBe('review')+ expect(f.state.people.find(p => p.id === owner.userId)?.approvalMode).toBeUndefined()+ expect(commandSchema.safeParse({ type: 'member.approvalMode', mode: 'review', personId: owner.userId }).success).toBe(false)+ for (const actor of [f.pm, f.buddyActor]) expect(() => f.runCommand({ type: 'member.approvalMode', mode: 'autoApprove' }, actor)).toThrow()+ })+ it('stages a PM task, excludes dispatch, and blocks assignment, starts and registration until approval', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ expect(f.card(id)).toMatchObject({ assignment: null, taskApproval: { state: 'proposal', personId: peer.userId } })+ expect(queueSiblings(f.state, f.state.projects![0]!)).not.toContainEqual(f.card(id))+ expect(openTasks(f.state, 'lead', NOW)).not.toContainEqual(f.card(id))+ for (const input of [+ { type: 'work.assign', conversationId: id, agentId: f.candidate },+ { type: 'agent.start', request: { conversationId: id, machineId: 'host', engine: 'codex', name: 'New worker', cwd: '/repo', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } },+ ]) expect(() => f.runCommand(input, f.pm)).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ 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')+ 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()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate }, f.pm)+ expect(f.card(id).assignment).toBeNull()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.other })+ const approved = f.runCommand({ type: 'task.approve', conversationId: id })+ expect(f.card(id)).toMatchObject({ taskApproval: { state: 'approved', suggestedAgentId: f.other }, assignment: null })+ expect(approved.messages.some(m => m.recipients.includes(f.lead))).toBe(true)+ f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.other }, f.pm)+ expect(f.card(id).assignment?.agentId).toBe(f.other)+ expect(approved.messages.some(m => m.recipients.includes(f.other))).toBe(false)+ expect(approved.messages.some(m => m.recipients.includes(f.candidate))).toBe(false)+ })+ it('refuses another person, PM or Buddy approval and old membership authority before receipt replay', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ for (const actor of [owner, outsider, f.pm, f.buddyActor]) for (const type of ['task.approve', 'task.reject'])+ expect(() => f.runCommand({ type, conversationId: id, ...type === 'task.reject' ? { reason: 'No' } : {} }, actor)).toThrow()+ const command = commandSchema.parse({ type: 'task.approve', conversationId: id })+ authorizeCommandAccess(f.state, peer, command)+ f.state.people.find(p => p.id === peer.userId)!.generation = 'rejoined'+ expect(() => authorizeCommandAccess(f.state, peer, command)).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_FORBIDDEN' }))+ })+ it('keeps rejected work stopped and refuses reopening or changing requester to evade approval', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ expect(() => f.runCommand({ type: 'conversation.requester', conversationId: id, personId: owner.userId }, f.pm)).toThrow()+ expect(commandSchema.safeParse({ type: 'task.reject', conversationId: id, reason: ' ' }).success).toBe(false)+ f.runCommand({ type: 'task.reject', conversationId: id, reason: 'Keep current behavior' })+ expect(f.card(id)).toMatchObject({ assignment: null, taskApproval: { state: 'rejected', reason: 'Keep current behavior' } })+ expect(() => f.runCommand({ type: 'task.approve', conversationId: id })).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_DECIDED' }))+ expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ })+ it.each([undefined, owner.userId])('stages personal approval when an unassigned task is attributed from %s to a Review requester', previous => {+ const f = fixture(); f.mode('review')+ const id = f.runCommand({ type: 'conversation.create', title: 'PM maintenance', task, priority: 'P2',+ ...previous ? { requesterId: previous } : { noRequesterReason: 'Proactive maintenance' },+ checks: [{ description: 'Restores drafts' }] }, f.pm).result.conversationId as string+ const command = commandSchema.parse({ type: 'conversation.requester', conversationId: id, personId: peer.userId })+ const before = f.state+ const effects = f.runCommand(command, f.pm)+ expect(f.card(id)).toMatchObject({ requesterId: peer.userId, assignment: null,+ taskApproval: { personId: peer.userId, generation: f.state.people.find(p => p.id === peer.userId)!.generation, state: 'proposal' } })+ expect(touchesFor(command, f.pm, before, effects)).toContainEqual({ kind: 'member', key: peer.userId })+ 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)+ })+ it('refuses attribution to a Review requester after assignment without changing the existing task', () => {+ const f = fixture()+ const id = f.runCommand({ type: 'conversation.create', title: 'PM maintenance', task, priority: 'P2', requesterId: owner.userId,+ checks: [{ description: 'Restores drafts' }] }, f.pm).result.conversationId as string+ f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)+ f.mode('review')+ expect(() => f.runCommand({ type: 'conversation.requester', conversationId: id, personId: peer.userId }, f.pm))+ .toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ expect(f.card(id)).toMatchObject({ requesterId: owner.userId, assignment: { agentId: f.candidate } })+ expect(f.card(id).taskApproval).toBeUndefined()+ })+ it('keeps existing attribution and Auto approve attribution compatible', () => {+ const f = fixture(), id = f.create()+ f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)+ f.mode('review')+ f.runCommand({ type: 'conversation.requester', conversationId: id, personId: peer.userId }, f.pm)+ expect(f.card(id).taskApproval).toBeUndefined()+ f.runCommand({ type: 'conversation.requester', conversationId: id, personId: owner.userId }, f.pm)+ expect(f.card(id)).toMatchObject({ requesterId: owner.userId, assignment: { agentId: f.candidate } })+ expect(f.card(id).taskApproval).toBeUndefined()+ })+ it.each([true, false])('keeps consented Buddy proposals in Tasks and reaches the PM with board mode %s', board => {+ const f = fixture(board); f.mode('review'); const sent = f.propose()+ const card = f.state.conversations.find(c => c.proposal?.senders.some(s => s.buddyId === f.buddy))!+ expect(card).toMatchObject({ requesterId: peer.userId, assignment: null, taskApproval: { state: 'proposal' }, proposal: { text: words } })+ expect(sent.messages.some(m => m.recipients.includes(f.lead) && m.author.id === peer.userId)).toBe(true)+ if (board) {+ f.runCommand({ type: 'proposal.decide', conversationId: card.id, decision: 'accept', reason: 'Build it', task,+ checks: [{ description: 'Restores drafts' }] }, f.pm)+ expect(() => f.runCommand({ type: 'work.assign', conversationId: card.id, agentId: f.candidate }, f.pm)).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ f.runCommand({ type: 'task.approve', conversationId: card.id })+ expect(f.card(card.id).taskApproval?.state).toBe('approved')+ }+ })+ it('cannot merge an unapproved proposal into another card to bypass its person', () => {+ const f = fixture(); f.mode('review'); f.propose()+ const card = f.state.conversations.find(c => c.taskApproval)!+ const other = f.runCommand({ type: 'proposal.create', projectId: 'lead', title: 'Other', text: 'Other', goal: 'Other', why: 'Other',+ doneWhen: 'Other', evidence: ['Reproduction'], priority: 'P2' }, owner).result.conversationId+ expect(() => f.runCommand({ type: 'proposal.merge', conversationId: card.id, intoConversationId: other, reason: 'Same' }, f.pm))+ .toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ })+ it('refuses invalid suggestions and rechecks a changed agent atomically on approval', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ for (const agentId of [f.buddy, f.worker, 'missing']) expect(() => f.runCommand({ type: 'task.suggest', conversationId: id, agentId })).toThrow()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate })+ f.state.agents.find(a => a.id === f.candidate)!.workDecision = 'stop'+ expect(() => f.runCommand({ type: 'task.approve', conversationId: id })).toThrow()+ expect(f.card(id)).toMatchObject({ assignment: null, taskApproval: { state: 'proposal' } })+ })+ it('keeps a legacy proposal’s decision when the PM converts it to a task and refuses a second conversion', () => {+ const f = fixture(false); f.mode('review'); const sent = f.propose()+ const row = sent.messages.find(m => m.source?.kind === 'buddy-proposal')!+ const proposal = { id: row.id, conversationId: row.conversationId, author: row.author, source: row.source ?? null }+ const input = { type: 'conversation.create', title: 'Prepared', task, priority: 'P2', proposalMessageId: row.id,+ checks: [{ description: 'Restores drafts' }] }+ const id = f.runCommand(input, f.pm, { proposal }).result.conversationId+ expect(f.card(id).taskApproval?.state).toBe('proposal')+ expect(f.state.conversations.filter(c => !c.archived && c.requesterId === peer.userId && (c.task || c.proposal))).toHaveLength(1)+ expect(() => f.runCommand(input, f.pm, { proposal })).toThrow()+ })+ it('keeps a chosen agent binding when the person approves before PM preparation', () => {+ const f = fixture(); f.mode('review'); f.propose()+ const card = f.state.conversations.find(c => c.proposal)!+ f.runCommand({ type: 'task.suggest', conversationId: card.id, agentId: f.candidate })+ f.runCommand({ type: 'task.approve', conversationId: card.id })+ f.runCommand({ type: 'proposal.decide', conversationId: card.id, decision: 'accept', reason: 'Build', task,+ checks: [{ description: 'Restores drafts' }] }, f.pm)+ expect(() => f.runCommand({ type: 'work.assign', conversationId: card.id, agentId: f.other }, f.pm)).toThrow()+ f.runCommand({ type: 'work.assign', conversationId: card.id, agentId: f.candidate }, f.pm)+ expect(f.card(card.id).assignment?.agentId).toBe(f.candidate)+ })+ it('cannot merge an approved Review proposal and lose its chosen agent or requester', () => {+ const f = fixture(); f.mode('review'); f.propose()+ const card = f.state.conversations.find(c => c.proposal)!+ f.runCommand({ type: 'task.suggest', conversationId: card.id, agentId: f.candidate })+ f.runCommand({ type: 'task.approve', conversationId: card.id })+ const target = f.runCommand({ type: 'proposal.create', projectId: 'lead', title: 'Other', text: 'Other', goal: 'Other', why: 'Other',+ doneWhen: 'Other', evidence: ['Reproduction'], priority: 'P2' }, owner).result.conversationId+ expect(() => f.runCommand({ type: 'proposal.merge', conversationId: card.id, intoConversationId: target, reason: 'Same' }, f.pm)).toThrow()+ })+ it('removes a closed legacy proposal mirror from active Tasks', () => {+ const f = fixture(false); const sent = f.propose()+ const row = sent.messages.find(m => m.source?.kind === 'buddy-proposal')!+ f.runCommand({ type: 'proposal.close', projectId: 'lead', messageId: row.id, reason: 'Not planned' }, f.pm,+ { proposal: { id: row.id, conversationId: row.conversationId, author: row.author, source: row.source ?? null } })+ expect(f.state.conversations.find(c => c.proposal?.legacyMessageId === row.id)?.archived).toBe(true)+ })+ it('redacts a pasted credential from a rejection before its reason reaches stored parts or messages', () => {+ const token = ['sk', 'AbCdEf0123456789'.repeat(3)].join('-') // Synthetic fixture, never a provider credential.+ const removed: Parameters<typeof withoutCredentials>[1] = []+ const clean = withoutCredentials(commandSchema.parse({ type: 'task.reject', conversationId: 'task', reason: `Avoid ${token}` }), removed)+ expect(JSON.stringify(clean)).not.toContain(token)+ expect(removed.length).toBeGreaterThan(0)+ })+ it('blocks child review execution while the owning task is pending or rejected', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ const step = () => f.runCommand({ type: 'conversation.create', title: 'Review', brief: 'Review implementation', checks: [{ description: 'Review passed' }],+ reviewOf: id, step: 'Review' }, f.pm)+ expect(step).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ f.runCommand({ type: 'task.reject', conversationId: id, reason: 'Do later' })+ expect(step).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))+ })+ it.each(['removed', 'stopping'])('recovers an approved, unassigned task when its chosen worker is %s, with fresh person approval', state => {+ const f = fixture(); f.mode('review'); const id = f.create()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate }, f.pm)+ f.runCommand({ type: 'task.approve', conversationId: id })+ if (state === 'removed') f.state.agents = f.state.agents.filter(a => a.id !== f.candidate)+ else f.state.agents.find(a => a.id === f.candidate)!.workDecision = 'stop'+ expect(() => f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.other }, owner)).toThrow()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.other }, state === 'removed' ? f.pm : peer)+ expect(f.card(id)).toMatchObject({ assignment: null, taskApproval: { state: 'proposal', suggestedAgentId: f.other } })+ expect(f.card(id).taskApproval?.decidedAt).toBeUndefined()+ expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.other }, 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.other }, f.pm)+ expect(f.card(id).assignment?.agentId).toBe(f.other)+ expect(() => f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.worker })).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_DECIDED' }))+ })+ it('guards the person and selected agent against concurrent changes, and keeps approval in light loads', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate })+ const before = f.state, command = commandSchema.parse({ type: 'task.approve', conversationId: id })+ const touches = touchesFor(command, peer, before, f.runCommand(command))+ expect(touches).toContainEqual({ kind: 'member', key: peer.userId })+ expect(touches).toContainEqual({ kind: 'agent', key: f.candidate })+ expect(GROUP_FIELDS.always).toContain('taskApproval')+ })+})diff --git a/backend/src/superTabs/taskApproval.ts b/backend/src/superTabs/taskApproval.tsnew file mode 100644index 000000000..4d2e9cc34--- /dev/null+++ b/backend/src/superTabs/taskApproval.ts@@ -0,0 +1,50 @@+import { author, fail, type Actor, type Conversation, type SuperTabState } from './model.js'+import { groupProject, ledProject, readConversation } from './projects.js'++export type ApprovalMode = 'autoApprove' | 'review'+/** Approval belongs to the requesting membership, never the execution host or PM. */+export interface TaskApproval {+ personId: string+ generation: string+ state: 'proposal' | 'approved' | 'rejected'+ createdAt: number+ decidedAt?: number+ suggestedAgentId?: string+ reason?: string+}+export const personalApprovalCommand = (type: string): boolean =>+ ['member.approvalMode', 'task.suggest', 'task.approve', 'task.reject'].includes(type)++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 = {+ personId: member.id, generation: member.generation, state: 'proposal', createdAt: now,+ }+}+export function requireTaskApproval(group: Conversation, agentId?: string | null): void {+ if (group.taskApproval && group.taskApproval.state !== 'approved')+ fail('TASK_APPROVAL_REQUIRED', 'The person who requested this task must approve it before work starts.', 409)+ if (!group.assignment && group.taskApproval?.suggestedAgentId && agentId !== undefined && group.taskApproval.suggestedAgentId !== agentId)+ fail('TASK_AGENT_CHANGED', 'Use the agent the requesting person approved for this task.', 409)+}+/** Authority is checked before receipt replay too; a decision's state is checked only when applying it. */+export function authorizeTaskApproval(state: SuperTabState, actor: Actor, type: string, conversationId?: string): Conversation | undefined {+ author(state, actor)+ if (type === 'member.approvalMode') {+ if (actor.kind !== 'person') fail('TASK_APPROVAL_FORBIDDEN', 'Choose your own approval mode as a person.', 403)+ return+ }+ const group = readConversation(state, actor, conversationId!)+ const approval = group.taskApproval+ const own = actor.kind === 'person' && approval?.personId === actor.userId+ && state.people.some(p => p.id === actor.userId && p.generation === approval.generation)+ const pm = type === 'task.suggest' && actor.kind === 'agent' && ledProject(state, actor.agentId)?.id === groupProject(state, group).id+ if (!approval || (!own && !pm)) fail('TASK_APPROVAL_FORBIDDEN', 'Only the requesting person can approve or reject; their PM may suggest an agent.', 403)+ return group+}+export function pendingTaskApproval(group: Conversation): TaskApproval {+ const approval = group.taskApproval+ if (!approval || approval.state !== 'proposal') fail('TASK_APPROVAL_DECIDED', 'This task already has an approval decision.', 409)+ return approval+}diff --git a/backend/src/superTabs/taskQueue.ts b/backend/src/superTabs/taskQueue.tsindex e182cd1fb..1719110a2 100644--- a/backend/src/superTabs/taskQueue.ts+++ b/backend/src/superTabs/taskQueue.ts@@ -17,7 +17,7 @@ export const queueOrder = <T extends Queued>(tasks: readonly T[]): T[] =>/** The tasks a project's Next up orders: open, never its chat, a Buddy chat, a private chat or a step. */export function queueSiblings(state: SuperTabState, project: SwarmProject): Conversation[] {- return state.conversations.filter(c => (!c.proposal || ['accept', 'reshape'].includes(c.proposal.decision?.kind ?? '')) && !c.archived && !c.kind && !c.audience && !c.reviewOf && c.id !== project.leadConversationId+ return state.conversations.filter(c => (!c.taskApproval || c.taskApproval.state === 'approved') && (!c.proposal || ['accept', 'reshape'].includes(c.proposal.decision?.kind ?? '')) && !c.archived && !c.kind && !c.audience && !c.reviewOf && c.id !== project.leadConversationId&& groupProject(state, c).id === project.id)}diff --git a/docs/plans/2026-11-07-swarm-v3-approval-plan.md b/docs/plans/2026-11-07-swarm-v3-approval-plan.mdnew file mode 100644index 000000000..e16ad38dc--- /dev/null+++ b/docs/plans/2026-11-07-swarm-v3-approval-plan.md@@ -0,0 +1,59 @@+# Swarm v3 approval and personal Tasks implementation plan++> Implement natively, task by task: commit each failing test before its code, then obtain independent security reviews of the final branch. No per-task subagent handoff.++**Goal:** Store and enforce each person's Auto approve / Review choice and deliver their Tasks summaries through existing cursor reads.+**Architecture:** Extend member and task JSON parts; reuse proposal cards, assignment/start/dispatch guards, operation receipts, project visibility and first-load/change APIs. One pure summary projection; no schema, endpoint, dependency or credential path.+**Tech Stack:** TypeScript, Zod, existing Mongo part store, Vitest, isolated real-store integration tests.+**Spec:** docs/specs/2026-11-07-swarm-v3.md; task #4115, conversation 62386c008cea90646d4c8eed.++## Global Constraints++- First commit includes the whole shared v3 spec and this plan; first PR body line: Requested by dee through Harness.+- Never read/post secrets or write production. No CLI login, relay, native process, phone/web UI, or account-removal changes here.+- Stay in backend/src/superTabs plus required spec/plan and focused integration tests. Coordinate overlapping model/commands/read contracts with the v3 agent and Desktop Tasks builders.+- Tests before implementation for every named behavior; affected tests locally, complete units and four integration shards in automatic PR CI. Real-store tests use isolated local fixtures, never real sign-in.+- Two independent security reviews for approval identity and feed authorization. Minor findings wait unless they block acceptance. Hold final head during review/CI.++## Review Focus++- A PM, Buddy, another person, rejoined membership or replay cannot change/forge personal approval.+- PM task preparation, automatic dispatch, explicit assignment and starts cannot run pending/rejected work; changing modes does not release existing pending work.+- Own proposals and PM tasks appear once with current state, time, project and visible agent; no private project/group leak or stale row after revocation/removal.+- Cursor changes read/return changed summaries, not history; failed/old cursors reset, and old clients keep their assignment status contract.++### Task 1: Approval preference and task lifecycle++**Files:** backend/src/superTabs/taskApproval.ts, taskApproval.test.ts, model.ts, commands.ts, proposalCards.ts, taskQueue.ts, parts/light.ts, parts/touches.ts; focused integration test.+**Interfaces:** approvalMode; taskApproval metadata; member.approvalMode and task.suggest/approve/reject commands as the spec defines.++- [x] Commit tests for default/Review modes, Buddy consent, PM task staging, suggested agent changes, approval and rejection, exact own identity/generation, protected replays, assignment/start/dispatch refusal and unchanged auto mode.+- [x] Observe failures; implement minimal guarded lifecycle and legacy-proposal card continuity.+- [x] Run affected command/proposal/queue/dispatch/light/touch tests and typecheck; commit and push.++### Task 2: Personal Tasks summaries on first load and cursor changes++**Files:** backend/src/superTabs/read/personalTasks.ts, personalTasks.test.ts, contract.ts, service.ts; focused store/read integration test.+**Interfaces:** personalTasks {approvalMode, reset, upserts, removed}, row fields in shared spec; existing response cursor/epoch.++- [x] Commit tests for own tasks/proposals, statuses and stable time order, project/agent identity, no hidden group/agent leak, removal/archive/reassignment, own-only preference, no agent feed, one-row/idle deltas and persisted API results.+- [x] Observe failures; implement from existing loaded parts only, no extra whole-history reads.+- [x] Run affected read tests and real-store integration, typecheck, diff checks and synthetic 1,000-task/one-row timing/size evidence; push.++### Task 3: Final acceptance and handoff++**Files:** plan validation notes and PR evidence only, unless a test-first review/CI fix is needed.+**Interfaces:** final PR head, tests, reviews, ci/required.++- [x] Update spec/contract details to match tested implementation; send exact contract to sibling builders.+- [x] Record red/green evidence and platform/rollback limitations in PR; mark Ready once.+- [ ] Two independent security reviews pass and ci/required green at final head; record acceptance and hand off for the 09:00 release. By 06:00 state any remaining release gap.++## Validation before review++- Approval tests were committed before implementation. Corrected fixture setup separately; the supported-mode/command cases then failed against the old backend. Additional red tests caught duplicate legacy conversion, losing the approved worker before preparation, merging away approval, closing a mirror, and unsanitized rejection reasons. Each production fix follows its test commit. The final child-step test fails before the parent gate is checked, then passes once creation waits for approval. The rejection test also fails when its scrub hook is removed, and passes with it restored.+- Focused affected units: 600 passed across 11 files before the last two narrow lifecycle/credential cases; the final approval/credential/commands run passed 486 tests after those fixes and the review-step fence. Backend typecheck and diff checks clean.+- Isolated real-store proposal suite: 14 passed. Includes new-member mode persistence, Review staging, direct-person decisions and receipt replay checks, project revocation/reload, legacy PM delivery and dormant mirror conversion refusal, and both approval modes through normal store assignment. Full units/four integration shards are CI evidence after Ready.+- Synthetic projection only, 1,000 active tasks (100 iterations, no database): initial 211,848 bytes, mean 0.228 ms; one changed row 277 bytes, 0.00039 ms; idle 70 bytes, 0.00061 ms. This measures the new projection, not end-to-end API latency. Feed reads add no queries. Legacy conversion/close adds one bounded existing message-id lookup to name a possibly dormant mirror; existing indexed group loading/guards persist it.+- Decisions never start work themselves. They notify the PM, and the existing work.assign store path enforces all repository/account/machine/global-session checks. The selected worker binds the first assignment; ordinary recovery after an actual assignment retains existing policy. Review proposal merges are refused to preserve each person's decision.+- No credential/login reads, schema change, production read/write, native process or visible UI change. Desktop owns light/dark UI evidence. Backend must not roll back to a version that ignores Review metadata while such tasks exist; compatible fix forward or explicit decision/drain first. Coordinated release remains held until 09:00 VN.diff --git a/docs/specs/2026-11-07-swarm-v3.md b/docs/specs/2026-11-07-swarm-v3.mdnew file mode 100644index 000000000..dd727df50--- /dev/null+++ b/docs/specs/2026-11-07-swarm-v3.md@@ -0,0 +1,50 @@+# Swarm v3 — 2026-11-07++Requested by anh Dee at 00:05 Vietnam time, for the 09:00 Vietnam release on 2026-11-07. Change only the delta to the existing Desktop UI; preserve today's audience rules. Phone and web are out of scope. #4089 remains off.++## Product spec (shared by all v3 tasks)++- **Left:** organization switching, Decisions, My agents (the person's Buddy first, then agents on their own account). Put a crown immediately beside a PM's name. Unread names are bold, with no dots or counts. Include + New agent. Projects follows, collapsible and initially closed unless the person has no agents. Remove Mentions.+- **Middle:** chat with the selected agent, or the selected project's Board and Chat tabs, Board first.+- **Right:** Tasks, sorted by time with no headings. Each task is two quiet lines: a project tag with a background and the task name; then the agent's face and name, with its status icon at the right. Reuse existing status marks and add proposal and rejected. Include the person's proposals and their status.+- **Approval:** Auto approve / Review dropdown beside Tasks, default Auto approve. In Review a new task waits; its agent is a suggestion the person can change, and the person approves or rejects it. The backend stores the per-person mode and enforces the wait. Rejection carries a reason. A mode change affects future tasks; it does not silently approve an existing waiting task.+- **Joining:** join the organization, bring your agent by choosing its engine on the computer you are using, and that agent becomes your Buddy. No separate add-machine step.+- **Agents:** a new agent is Regular or PM. A PM names and starts a project. A Regular agent is not tied to a project: the task determines where it works.+- **Routing:** Ken's router stays. Suggest the best agent using machine, memory, disk, model and remaining quota. Quota determines only whether enough remains. Read quota from the CLI's own reports: Claude Code status-line rate-limit fields and Codex app-server rate-limit reads.+- **Remove:** the owner-subscription relay, Claude/ChatGPT login reads for usage in CLI and Desktop, and Team accounts. Start each CLI with its owner's own settings. Stop Team agents only after the release is published and verified, with their work pushed first.+- **Quality:** check the existing UI first, light and dark, Windows without window flashes, tests with a memory store and fake sign-in. Push draft PRs early and keep them current. By 06:00 Vietnam post what is complete and what will miss the release. Never expose a secret; no production writes in implementation tasks.++**Done when:** a new member joins, brings an agent and receives a PM task in Tasks in both approval modes; Buddy proposals still reach the PM; no code path reads a Claude or ChatGPT login; the coordinated release is out at 09:00.++## Existing UI checked++The current `desktop/lib/super_tabs/project_sidebar.dart` has organization switching and Decisions/Mentions/Threads followed by Projects. `task_groups.dart` builds the project's Board from tasks and Buddy proposals with existing status/priority rules. The v3 Desktop tasks adapt those surfaces; this backend task adds no alternative UI or client sign-in.++## Backend contract (#4115)++Use existing authenticated command transport and first-load/change transport; no new poll or endpoint.++- `member.approvalMode { mode: "autoApprove" | "review" }`: the signed-in person's own preference. Absent stored preference means autoApprove. No target person id; agents cannot change it.+- `task.suggest { conversationId, agentId }`: the requesting person or that task's PM names an available, visible agent as a suggestion. This never starts work. Before the first assignment, a new suggestion on an already approved task returns it to proposal and needs the person’s fresh approval, so a lost/stopping choice cannot strand it. Person approval remains separate.+- `task.approve { conversationId }`: the requesting person approves their pending task. The PM is told to prepare/route it; only the existing assignment path starts work, with all repository, machine, account and session checks. The selected agent is enforced on its first assignment. Only the person's current membership can approve, not an agent quoting them.+- `task.reject { conversationId, reason }`: the requesting person rejects their pending task, with a nonempty reason. No assignment or agent launch occurs.+- Store approval metadata on the existing task/proposal card, separate from assignment status. Pending is `proposal`, rejected is `rejected`, approved joins the ordinary task lifecycle. No worker is assigned while pending or rejected. The same guard covers explicit assignment, starts and automatic dispatch. PM preparation of a task does not approve it.+- Apply Review to new PM tasks for that requester and to their Buddy proposal cards. Keep the exact-consent Buddy checks and legacy proposal delivery. Represent legacy Buddy proposals on a durable card too, and link them when the PM creates the resulting task, so the feed has one continuing entry rather than duplicate work.+- Changing an unassigned task’s requester to a person in Review stages that person’s approval, including a task originally opened with no requester. Refuse that attribution after assignment. Keeping the same requester does not retroactively gate existing work.+- Add optional `personalTasks` to `/parts` and `/changes`, for person readers only. It uses that response's existing cursor and visibility epoch, including its 30-second safety overlap; merge duplicate versions idempotently. Shape: `{ approvalMode, reset, upserts, removed }`. `reset` is true on first load; apply removals and upserts on changes. Each row has `id`, `version`, `at` (epoch ms), `projectId`, `projectName`, `title`, `agent` (null or id/name/avatar), `status`, `suggested`, and optional `reason`. Order newest first by `at`, then id. Overlay agent/project roster changes using their existing part updates; do not request the feed on a timer.+- The feed contains readable, active tasks requested by the person and their proposals; no chats or review steps. Archived, deleted, merged or dormant records leave the active feed through removals. Existing project history reads retain old work. First load uses the existing active snapshot; changes summarize only changed task parts, never all task history.++## Design (docs/feature-design-rules.md)++Reviewed revision: initial spec; independent review pending. These answers apply to #4115; each sibling task validates its implementation against this shared spec and documents its area-specific details.++1. **Growth/lifecycle:** one optional preference per existing membership; it is removed with the membership and resets on rejoin. One bounded approval record per existing task/card, removed by existing project/Swarm deletion. A task goes proposal → approved/ordinary lifecycle or rejected; rejected work stays visible until archive, never runs. Leaving/rejoining invalidates pending approval through membership generation. Existing archive/dormancy/tombstone retention removes rows from active Tasks; history remains in existing group reads. No new collection, raw feed history or timer.+2. **Concurrency:** use existing part-version guards and operation receipts. Approval/mode writes touch the person's member part. Creation and requester changes read/touch the requester; Buddy creation also touches its owner. Assignment and start guard the task; dispatch excludes unapproved tasks. Approval atomically changes metadata; the ordinary assignment command alone launches work. Suggestion selection guards its agent; changing modes cannot race task creation or attribution past the mode it read. Replays recheck current authority before returning old receipts.+3. **Read cost:** reuse active first-load parts and changed parts selected by the existing cursor index. Feed rows contain summaries, no task briefs, messages, login data or machine observations. At 1,000 active tasks, first load is O(active parts) as before, with only that person's rows added; a one-task change adds one summary, and an idle cursor adds no rows. Removals are explicit; a visibility epoch change forces a reset. Test payload count/bytes and no history query on changes.+4. **Scale:** at 10× today's active tasks, change output depends on changed rows, not total history. Record summary byte counts and timing on a synthetic 1,000-task snapshot and one-task delta. Existing cache/delta metrics and backend latency expose growth; do not introduce per-person collections or a task-history scan.+5. **Compatibility/readers:** add optional fields only; do not add assignment WorkStatus values. Existing Desktop/CLI/phone task, Board, decisions, dispatch, liveness and host readers keep their normal status vocabulary. New Desktop uses personalTasks when advertised; against an old backend it must not expose unsupported approval controls. Pending/rejected are card metadata and feed states; assignment/start/queue enforcement is server-side even for old clients. Existing group/member views preserve additive fields. Light loading must keep the approval guard fields; unchanged clients may show these tasks as unassigned/proposals but cannot start them.+6. **Migration/rollback:** backend first, Desktop after, then coordinated release at 09:00. No schema migration or production write. Absent mode is autoApprove; existing tasks are not retroactively gated. Previous backend releases do not enforce the new metadata: do not roll back the approval backend while Review tasks exist; first deploy a compatible fix forward or drain pending/rejected tasks with their person's explicit decision. Production restore/anomaly reads are unnecessary for this additive JSON change; verify persistence and reload through the isolated integration store, never production.+7. **Audience:** use existing membership and project/conversation read predicates for every feed row and removal. Feed is authenticated-person only, no `asAgent` copy. Agent/avatar references come only from the reader-visible roster. No content leaves Tasks through logs/observations. PM notices remain inside the readable task/project; the existing Buddy exact-consent path controls what leaves private chat. Sharing revocation moves the epoch and resets the feed. Existing private-chat/share rules stay intact.+8. **Identity:** preference and decision commands derive identity from the authenticated person, never machineOwnerId. Match pending owner id and membership generation. A PM can suggest but cannot impersonate approval. No credential, provider-login or subscription read; sibling tasks remove legacy account/relay paths. Missing identity is refused, never replaced with a machine owner's identity.+9. **Failure:** invalid/removed/busy agents are rejected with existing assignment reasons; a stale approval, wrong person, inaccessible project or rejected task fails visibly. PM preparation can continue while user approval waits, but no session runs. Offline agents remain subject to routing/start checks. Duplicate operations use existing receipts. Invalid/expired cursors use the existing reload response; removals and revocation cannot leave a stale active row.+10. **Platforms:** backend serves Desktop on macOS, Windows and Linux with the same contract. This task starts no native process and reads no real sign-in. The sibling Desktop tasks validate light/dark and window behavior. Phone/web UI is excluded and older clients remain compatible.