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
Merge batch 11-05 j0030: #3217 #3222 #3214 (#3239)
0xken153e3fbe4a7b7c
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex 8f2e5cec0..320bd597c 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -239,7 +239,7 @@ describe('a Buddy through the store', () => {// Past the seed's half hour, the read takes the kept proposals alone.await db.superTabOpenProposal.update({ where: { id: `seeded:${f.tab}:lead` }, data: { createdAt: new Date(Date.now() - SEED_SETTLE_MS - 1000) } })expect(await listed()).toEqual([sent])- await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Taking it', replyTo: sent, recipientIds: [] }, owner, f.lead)+ await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Taking this as a task', replyTo: sent, recipientIds: [] }, owner, f.lead)expect(await listed()).toEqual([])expect(await db.superTabOpenProposal.count({ where: { id: sent } })).toBe(0)})@@ -251,7 +251,7 @@ describe('a Buddy through the store', () => {checks: [] })).result.conversationId), [owner.sub])const { agentId } = await buddy(f)const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Offline sync', brief: 'Desktop keeps edits offline.',- checks: [{ description: 'Edits survive a restart', independent: false }] })).result.conversationId)+ checks: [{ description: 'Edits survive a restart', independent: false }], priority: 'P2', requesterId: owner.sub })).result.conversationId)const builder = String((await f.execute({ type: 'agent.add', conversationId: group, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Builder',configuration: config, lead: false })).result.agentId)const assignmentId = String((await f.execute({ type: 'work.assign', conversationId: group, agentId: builder })).result.assignmentId)@@ -873,7 +873,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',text: 'Goal: Offline sync\nScope: Desktop only\nPriority: normal', replyTo: proposal, thread: proposal, recipientIds: [f.lead], mentions: [] } })const open = (proposalMessageId: string) => f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Offline sync', brief: 'Desktop keeps edits offline.',checks: [{ description: 'Edits survive a restart', independent: false }], proposalMessageId }, owner, f.lead)- const answer = String((await pm('Taking it.', { replyTo: proposal })).result.messageId)+ const answer = String((await pm('Taking this as a task.', { replyTo: proposal })).result.messageId)await expect(open(answer)).rejects.toMatchObject({ code: 'PROPOSAL_UNKNOWN' })const created = await open(details.id)const stored = (await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === String(created.result.conversationId))!@@ -900,7 +900,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',it('stops hearing once its person stops reading the project: nothing new is sent, and what waits is refused at pickup', async () => {const { f, agentId, proposal, pm, heard } = await proposed()- const answer = String((await pm('Taking it.', { replyTo: proposal })).result.messageId)+ const answer = String((await pm('Taking this as a task.', { replyTo: proposal })).result.messageId)const waiting = (await f.store.deliveries(peer, f.tab, agentId)).find(d => d.conversationId === 'lead')expect(waiting?.messageId).toBe(answer)await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })@@ -919,7 +919,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })}), () => Date.now())const answer = String((await racing.execute(owner, f.tab, { operationId: randomUUID(), command: { type: 'message.send', conversationId: 'lead',- text: 'Taking it.', replyTo: proposal, recipientIds: [] } }, f.lead)).result.messageId)+ text: 'Taking this as a task.', replyTo: proposal, recipientIds: [] } }, f.lead)).result.messageId)expect(raced).toBe(true)expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: answer, agentId } })).toBe(0)})@@ -927,7 +927,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',it('hears no assignment of a task its person cannot read', async () => {const { f, agentId } = await proposed()const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Offline sync', brief: 'Desktop keeps edits offline.',- checks: [{ description: 'Edits survive a restart', independent: false }], requesterId: peer.sub }, owner, f.lead)).result.conversationId)+ checks: [{ description: 'Edits survive a restart', independent: false }], priority: 'P2', requesterId: peer.sub }, owner, f.lead)).result.conversationId)const builder = String((await f.execute({ type: 'agent.add', conversationId: group, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Builder',configuration: config, lead: false })).result.agentId)await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })@@ -955,7 +955,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',it('keeps whose Buddy heard a line hidden after that Buddy is removed or replaced (security review 1 of #2178)', async () => {const { f, proposal, pm } = await proposed()- const answer = String((await pm('Taking it.', { replyTo: proposal })).result.messageId)+ const answer = String((await pm('Taking this as a task.', { replyTo: proposal })).result.messageId)const read = async () => (await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.id === answer)!expect((await read()).deliveries).toEqual([])// Nor when an agent reads: the PM sees no Buddy among the line's deliveries.@@ -972,7 +972,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',it('never lets a person resolve a Buddy\'s news delivery: it reads as one that needs no checking (security review 2 of #2178)', async () => {const { f, agentId, proposal, pm } = await proposed()- const answer = String((await pm('Taking it.', { replyTo: proposal })).result.messageId)+ const answer = String((await pm('Taking this as a task.', { replyTo: proposal })).result.messageId)const news = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, messageId: answer, agentId } })await db.superTabDelivery.update({ where: { id: news.id }, data: { status: 'uncertain' } })for (const resolution of ['received', 'resend', 'cancel'] as const) {@@ -1001,7 +1001,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',it('hands a Buddy a claimed row without the machine it names (security review 2 of #2178)', async () => {const { f, agentId, proposal, pm } = await proposed()- const answer = String((await pm('Taking it.', { replyTo: proposal })).result.messageId)+ const answer = String((await pm('Taking this as a task.', { replyTo: proposal })).result.messageId)// A machine-removed row's shape (commands.ts removeMachine), as if it were news: what reaches the Buddy names no machine.await db.superTabMessage.update({ where: { id: answer }, data: { text: 'Studio Mac left the Swarm.', source: { kind: 'machine-removed', machine: 'Studio Mac' } } })const news = (await f.store.deliveries(peer, f.tab, agentId)).find(d => d.messageId === answer)!diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.tsindex adaba81be..890acf820 100644--- a/backend/integration/superTabSwarmBuddy.test.ts+++ b/backend/integration/superTabSwarmBuddy.test.ts@@ -158,7 +158,7 @@ describe('the one Buddy sends a proposal to a project its person reads (Scholes,expect(await db.superTabMessage.count({ where: { tabId: f.tab, replyTo: sent } })).toBe(0)expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: sent, agentId: f.pms.web } })).toBe(1)for (const elsewhere of ['lead', f.secret.conversationId]) expect(await texts(f, elsewhere, owner)).not.toContain(row.text)- const group = String((await f.execute({ type: 'conversation.create', title: 'Offline sync', brief: '', checks: [], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)+ const group = String((await f.execute({ type: 'conversation.create', title: 'Offline sync', brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)expect((await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === group)).toMatchObject({ requesterId: peer.sub,brief: 'Goal: Offline sync\nScope: Web only\nPriority: normal' })expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: group } })).data).toMatchObject({ ledger: { proposal: { buddyId: main } } })@@ -458,7 +458,7 @@ describe('a project session', () => {// Sessions end by themselves after 30 idle minutes, so the PM often opens the group after the session is gone.if (endBeforeOpen) await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'ended' }, peer)const group = String((await f.execute({ type: 'conversation.create', projectId: f.web.projectId, title: 'Offline sync', brief: 'Web keeps edits offline.',- checks: [], proposalMessageId: proposal }, owner, f.pms.web)).result.conversationId)+ checks: [{ description: 'Done', independent: false }], proposalMessageId: proposal }, owner, f.pms.web)).result.conversationId)await f.execute({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/example/app/pull/7' })if (!endBeforeOpen) await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'ended' }, peer)return { chat, main, agentId, group }@@ -500,7 +500,7 @@ describe('a project session', () => {peer, agentId)).result.messageId)await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'ended' }, peer)await f.execute({ type: 'project.sharing', projectId: f.web.projectId, visibility: 'private', memberIds: [owner.sub] })- const group = String((await f.execute({ type: 'conversation.create', projectId: f.web.projectId, title: 'T', brief: '', checks: [], proposalMessageId: proposal },+ const group = String((await f.execute({ type: 'conversation.create', projectId: f.web.projectId, title: 'T', brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: proposal, requesterId: owner.sub },owner, f.pms.web)).result.conversationId)await f.execute({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/example/app/pull/8' })const board = await new SwarmReads(f.store).leaderboard(owner, f.tab, f.web.projectId)@@ -529,7 +529,7 @@ describe('a project session', () => {const ask = String((await send(f, chat, 'Send it', { replyTo: thread })).result.messageId)const proposal = String((await f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, text: 'Send it', goal: 'G', scope: 'S', priority: 'normal' },peer, agentId)).result.messageId)- await f.execute({ type: 'conversation.create', projectId: f.web.projectId, title: 'T', brief: '', checks: [], proposalMessageId: proposal }, owner, f.pms.web)+ await f.execute({ type: 'conversation.create', projectId: f.web.projectId, title: 'T', brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: proposal }, owner, f.pms.web)expect((await buddyRows(f, peer, f.web.projectId)).map(r => r.agentId)).toEqual([main])})@@ -547,7 +547,7 @@ describe('a project session', () => {const sent = String((await f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, text: 'Send it', projectId: f.web.projectId, goal: 'G', scope: 'S', priority: 'normal' }, peer, agentId)).result.messageId)expect(await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: sent } })).toMatchObject({ conversationId: f.web.conversationId, recipientIds: [f.pms.web] })// Credited to the person's one Buddy, as a project session's is: a session ends.- const group = String((await f.execute({ type: 'conversation.create', title: 'From the session', brief: '', checks: [], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)+ const group = String((await f.execute({ type: 'conversation.create', title: 'From the session', brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: sent }, owner, f.pms.web)).result.conversationId)const row = (await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === group)expect(row?.requesterId).toBe(peer.sub)expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: group } })).data).toMatchObject({ ledger: { proposal: { buddyId: main } } })diff --git a/backend/integration/superTabTaskLines.test.ts b/backend/integration/superTabTaskLines.test.tsindex a40b9b943..f3382c114 100644--- a/backend/integration/superTabTaskLines.test.ts+++ b/backend/integration/superTabTaskLines.test.ts@@ -69,7 +69,7 @@ describe('a task\'s one message in its project chat', () => {const s = await swarm()const P = await s.add('Coordinator', 'lead', true)const before = (await store.messages(owner, s.tab, 'lead', {})).messages.length- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', requesterId: owner.sub, brief: 'Keep drafts.', checks: [] })).result.conversationId)+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', requesterId: owner.sub, brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2' })).result.conversationId)const E = await s.add('Engineer', T)const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)const pr = 'https://github.com/example/app/pull/7'@@ -89,14 +89,14 @@ describe('a task\'s one message in its project chat', () => {const P = await s.add('Coordinator', 'lead', true)const asked = String((await run(s.tab, { type: 'message.send', conversationId: 'lead', text: 'Can the phone show who answered?', replyTo: null,recipientIds: [] }, peer)).result.messageId)- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Phone shows who answered', brief: 'Show who answered.', checks: [],+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Phone shows who answered', brief: 'Show who answered.', checks: [{ description: 'Done', independent: false }], priority: 'P2',requestMessageId: asked })).result.conversationId)expect((await s.page('lead')).lines).toEqual([])expect((await store.read(owner, s.tab)).state.conversations.find(c => c.id === T)?.requesterId).toBe(peer.sub)const E = await s.add('Engineer', T)await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })// A second task may hang under the same message; its thread names both.- await s.as(P)({ type: 'conversation.create', title: 'Desktop shows who answered', brief: 'Same on Desktop.', checks: [], requestMessageId: asked })+ await s.as(P)({ type: 'conversation.create', title: 'Desktop shows who answered', brief: 'Same on Desktop.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: asked })expect((await s.page('lead')).lines).toEqual([])expect((await store.messages(owner, s.tab, 'lead', { thread: asked })).messages.map(m => m.text)).toEqual(['Can the phone show who answered?', 'Phone shows who answered', 'Desktop shows who answered'])@@ -111,7 +111,7 @@ describe('a task\'s one message in its project chat', () => {const P = await s.add('Coordinator', 'lead', true)const asked = String((await run(s.tab, { type: 'message.send', conversationId: 'lead', text: 'Can drafts survive a restart?', replyTo: null,recipientIds: [] }, peer)).result.messageId)- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], requestMessageId: asked }))+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: asked })).result.conversationId)const E = await s.add('Engineer', T)const reactions = async () => {@@ -139,7 +139,7 @@ describe('a task\'s one message in its project chat', () => {const s = await swarm()const P = await s.add('Coordinator', 'lead', true)const root = await s.ask('Can drafts survive a restart?')- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], requestMessageId: root }))+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: root })).result.conversationId)const E = await s.add('Engineer', T)const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)@@ -154,7 +154,7 @@ describe('a task\'s one message in its project chat', () => {const s = await swarm()const P = await s.add('Coordinator', 'lead', true)const root = await s.ask('Can drafts survive a restart?')- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], requestMessageId: root }))+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: root })).result.conversationId)const E = await s.add('Engineer', T)const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)@@ -175,7 +175,7 @@ describe('a task\'s one message in its project chat', () => {const created = (await run(s.tab, { type: 'project.create', name: 'Secret', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }const P = await s.add('Coordinator', created.conversationId, true)const root = await s.ask('Can we do the hidden work?', created.conversationId)- const T = String((await s.as(P)({ type: 'conversation.create', title: 'Hidden work', brief: 'Quietly.', checks: [], requestMessageId: root })).result.conversationId)+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Hidden work', brief: 'Quietly.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: root })).result.conversationId)const E = await s.add('Engineer', T)const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)await s.as(E)({ type: 'work.status', conversationId: T, assignmentId, status: 'working', result: 'Started.' })diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 4b821a355..eaf4c02a8 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -640,7 +640,7 @@ describe('a teammate\'s work and the machines that take it', () => {const refused = { code: 'TEAM_ACCOUNT_REQUIRED', message: NO_TEAM_ACCOUNT }await expect(run(f.tab, post([volunteer]), owner, f.lead)).rejects.toMatchObject(refused)await expect(run(f.tab, post([]), person, volunteer)).rejects.toMatchObject(refused)- await expect(run(f.tab, { type: 'conversation.create', title: 'Its own task', brief: 'Do it', checks: [] }, person, volunteer)).rejects.toMatchObject(refused)+ await expect(run(f.tab, { type: 'conversation.create', title: 'Its own task', brief: 'Do it', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: person.sub }, person, volunteer)).rejects.toMatchObject(refused)const task = (await store.read(owner, f.tab)).state.conversations.find(c => c.id === f.teamGroup)!expect(task.agentIds).not.toContain(volunteer)// The agent on the person's Team machine is named into another task of the owner's project.@@ -1261,7 +1261,7 @@ describe('a message from an agent of another account (audit M3)', () => {expect(answer).not.toHaveProperty('otherAccount')expect(answer.quotedOtherAccount).toEqual([asked.id])// A reply to the Lead's reply quotes the Lead's, and its thread is the Team agent's.- const again = await said(f, 'On it.', f.lead, { agent: f.helper, user: owner }, relayed.id)+ const again = await said(f, 'On it, rebasing now.', f.lead, { agent: f.helper, user: owner }, relayed.id)expect((await claimed(f, owner, f.lead, again.id)).quotedOtherAccount).toEqual([asked.id])})it('names no quoted message from the same account, nor a person\'s', async () => {@@ -1270,7 +1270,7 @@ describe('a message from an agent of another account (audit M3)', () => {const reply = await said(f, 'Agreed.', f.lead, { agent: f.helper, user: owner }, own.id)expect(await claimed(f, owner, f.lead, reply.id)).not.toHaveProperty('quotedOtherAccount')const person = await said(f, 'From the owner, quoted.', f.lead)- const answer = await said(f, 'Will do.', f.helper, { agent: f.lead, user: owner }, person.id)+ const answer = await said(f, 'Will do, after the rebase.', f.helper, { agent: f.lead, user: owner }, person.id)expect(await claimed(f, owner, f.helper, answer.id)).not.toHaveProperty('quotedOtherAccount')})diff --git a/backend/integration/superTabWorkflow.test.ts b/backend/integration/superTabWorkflow.test.tsindex 585d8b482..26bd8b99f 100644--- a/backend/integration/superTabWorkflow.test.ts+++ b/backend/integration/superTabWorkflow.test.ts@@ -59,7 +59,7 @@ describe('the template\'s workflow', () => {// The coordinator opens the task with its two checks and assigns the Engineer.const T = String((await as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts across a restart.',- checks: [{ description: 'Review passes', independent: false }, { description: 'Test passes', independent: false }] })).result.conversationId)+ checks: [{ description: 'Review passes', independent: false }, { description: 'Test passes', independent: false }], priority: 'P2', requesterId: owner.sub })).result.conversationId)const assignment = String((await as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)const [review, test] = (await task(T)).checksexpect([review!.description, test!.description]).toEqual(['Review passes', 'Test passes'])diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex fd095725e..0942e3f8c 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -36,7 +36,7 @@ import { recipientShare } from '../src/routes/harnessShares.js'import { beforeFirstWrite } from './interleave.test-support.js'import { wantDefaultDigest } from './noDefaultDigest.test-support.js'import { startMessageReachStats } from '../src/superTabs/messageReachStats.js'-import { profiled } from './plans.test-support.js'+import { plan as planOf, profiled, reads } from './plans.test-support.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.let replica: MongoMemoryReplSet@@ -575,7 +575,7 @@ describe('five-part task persistence', () => {const checks = [{ description: 'Draft survives reconnect', independent: false }]const created = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`,headers: { authorization: `Bearer ${host.sub}` }, payload: { operationId: randomUUID(), asAgentId: lead,- command: { type: 'conversation.create', title: 'Drafts', task, checks } } })+ command: { type: 'conversation.create', title: 'Drafts', task, checks, priority: 'P2', requesterId: owner.sub } } })expect(created.statusCode, created.body).toBe(200)const group = created.json().data.result.conversationId as stringconst worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(), name: 'Worker', configuration: config, lead: false })).result.agentId as string@@ -2072,6 +2072,50 @@ describe('Super Tabs on a real Mongo replica set', () => {.rejects.toMatchObject({ code: 'INVALID_ANSWER' })})+ // Task #3391: acknowledging is a reaction, not a post, so a reaction settles the recipient's delivery as an answer does.+ it('closes the reacting agent\'s own deliveries of a message as answered, and nobody else\'s', async () => {+ const { tab, lead } = await fixture()+ const group = String((await run(tab, { type: 'conversation.create', title: 'Task', brief: '', checks: [] })).result.conversationId)+ const helper = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Helper', configuration: config, lead: false })).result.agentId as string+ await invite(tab)+ const asked = await run(tab, { type: 'message.send', conversationId: group, text: 'Please look at the failing build.', replyTo: null,+ recipientIds: [lead, helper] }, peer)+ const messageId = asked.result.messageId as string+ const held = (await store.deliveries(host, tab, lead)).find(d => d.messageId === messageId)!+ const other = (await store.deliveries(host, tab, helper)).find(d => d.messageId === messageId)!+ await store.delivery(host, tab, lead, held.id, { type: 'claim', claimId: randomUUID() })+ const react = (emoji: string, on = true) => ({ type: 'message.react', conversationId: group, messageId, emoji, on }) as Command+ // A person's reaction, and an agent taking its reaction back, settle nothing.+ await run(tab, react('eyes'), peer)+ await run(tab, react('eyes', false), host, lead)+ expect(await store.deliveryReceipt(host, tab, lead, held.id)).toEqual({ id: held.id, status: 'claimed' })+ await run(tab, react('check'), host, lead)+ expect(await store.deliveryReceipt(host, tab, lead, held.id)).toEqual({ id: held.id, status: 'answered' })+ expect((await store.deliveries(host, tab, lead)).map(d => d.messageId)).not.toContain(messageId)+ expect(await store.deliveryReceipt(host, tab, helper, other.id)).toEqual({ id: other.id, status: 'queued' })+ })++ // Backend AGENTS.md rule 3, ENGINEERING §4: the reaction's delivery queries are indexed and read only the agent's claimed rows and+ // that message's deliveries, however many deliveries the Swarm holds.+ it('settles a reaction\'s deliveries by index, examining only the claimed rows and that message\'s rows', async () => {+ const { tab, lead } = await fixture()+ const group = String((await run(tab, { type: 'conversation.create', title: 'Task', brief: '', checks: [] })).result.conversationId)+ await invite(tab)+ const ids: string[] = []+ // Twenty messages to the Lead, so the Swarm holds many deliveries beside the one this reaction settles.+ for (let i = 0; i < 20; i++) {+ ids.push((await run(tab, { type: 'message.send', conversationId: group, text: `Question ${i}`, replyTo: null, recipientIds: [lead] }, peer)).result.messageId as string)+ }+ const entries = await profiled(db, () => run(tab, { type: 'message.react', conversationId: group, messageId: ids[7]!, emoji: 'eyes', on: true } as Command, host, lead))+ const queries = reads(entries, 'SuperTabDelivery', ['tabId', 'messageId', 'agentId'])+ // The claimed-rows read (endDeliveries) goes by the agent's claimed rows, the update by the message: two operations, one row.+ const plans = planOf(queries)+ expect(plans.map(q => q.plan)).toEqual(['IXSCAN { tabId: 1, agentId: 1, status: 1, createdAt: 1 }', 'IXSCAN { tabId: 1, messageId: 1 }'])+ expect(plans.map(q => q.docsExamined)).toEqual([0, 1])+ expect(plans.map(q => q.keysExamined)).toEqual([0, 1])+ })+it('durably resumes a claim, never steals it on timeout, and does not resurrect revoked messages on rejoin', async () => {const { tab, lead } = await fixture()await invite(tab)@@ -4082,7 +4126,7 @@ describe('Product Managers chat, removed (Dee, 2026-10-31)', () => {title: 'Roster', owns: ['desktop/lib/super_tabs'], status: 'working' })])expect((await store.read(host, tab, worker)).state).not.toHaveProperty('otherProjectsWork')- const filter = String((await run(tab, { type: 'conversation.create', title: 'Agents filter', task: task(['desktop/lib/super_tabs/roster.dart']), checks },+ const filter = String((await run(tab, { type: 'conversation.create', title: 'Agents filter', task: task(['desktop/lib/super_tabs/roster.dart']), checks, priority: 'P2', requesterId: owner.sub },host, lead)).result.conversationId)await run(tab, { type: 'work.define', conversationId: filter, task: task(['desktop/lib/super_tabs']), checks }, host, lead)const alerts = await db.superTabMessage.findMany({ where: { tabId: tab, source: { equals: { kind: 'overlap', conversationIds: [filter, roster] } } } })@@ -4553,7 +4597,7 @@ describe('Lead mentions', () => {const earlierAt = async (tab: string, minutes: number) => (await after(minutes).mentions(peer, tab, 'earlier')).mentionsconst as = (minutes: number, user: AuthUser, tab: string, command: Command, agent?: string) =>after(minutes).execute(user, tab, { operationId: randomUUID(), command }, agent)- const post = (group: string): Command => ({ type: 'message.send', conversationId: group, text: 'On it.', replyTo: null, recipientIds: [] })+ const post = (group: string): Command => ({ type: 'message.send', conversationId: group, text: 'On it, rebasing now.', replyTo: null, recipientIds: [] })it('keeps a tag the Lead acted on out of Waiting and Earlier, also when a worker is assigned or the requester replies later', async () => {const { tab, lead, group } = await held()diff --git a/backend/src/superTabs/acknowledgements.test.ts b/backend/src/superTabs/acknowledgements.test.tsnew file mode 100644index 000000000..3e6a7a3b9--- /dev/null+++ b/backend/src/superTabs/acknowledgements.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import type { Command } from './commands.js'+import { isAcknowledgement } from './acknowledgements.js'+import { owner, stepsFixture } from './steps.test-support.js'++describe('isAcknowledgement (task #3391)', () => {+ it.each(['on it', 'On it!', 'Got it.', 'got it, thanks', 'Thanks!', 'thank you', 'Will do', 'Noted. Will do.', 'Understood 👍', 'ack', 'copy that'])(+ 'reads %j as an acknowledgement', text => expect(isAcknowledgement(text)).toBe(true))++ it.each(['Yes at 1a2b3c', 'Yes', 'ok', 'Done', 'on it?', 'got it #12', 'thanks, merged', 'on it: https://github.com/a/b/pull/3',+ 'see github.com/a/b', 'Will do after the build', 'will do in 5 minutes', 'on it @Ken', 'Thanks for the review, fixed in abc123', '', ' ', '👍',+ // A courtesy after an answer does not make the answer an acknowledgement (review of #3391: Hugo).+ 'Yes, thanks.', 'Okay, thanks.', 'Yes', 'Yep, got it', 'Sure, will do', 'ok, on it', 'Great, thanks'])(+ 'lets %j through', text => expect(isAcknowledgement(text)).toBe(false))+})++describe('an agent post that only acknowledges', () => {+ const send = (f: ReturnType<typeof stepsFixture>, by: string | null, text: string, extra: Record<string, unknown> = {}, on = f.task) =>+ f.run({ type: 'message.send', conversationId: on, text, replyTo: null, recipientIds: [], ...extra } as Command, by ? f.as(by) : owner)++ it('is refused with ACK_ONLY and the next step', () => {+ const f = stepsFixture()+ for (const text of ['on it', 'Got it, thanks!', 'will do']) {+ expect(() => send(f, f.dev, text)).toThrow(expect.objectContaining({ code: 'ACK_ONLY', message: expect.stringMatching(/react/i) }))+ }+ })++ it('is refused in the project chat and as a reply too', () => {+ const f = stepsFixture()+ expect(() => send(f, f.dev, 'on it', {}, 'lead')).toThrow(expect.objectContaining({ code: 'ACK_ONLY' }))+ expect(() => send(f, f.lead, 'thanks', { recipientIds: [f.dev] })).toThrow(expect.objectContaining({ code: 'ACK_ONLY' }))+ })++ it('lets real short answers through, and never refuses a person', () => {+ const f = stepsFixture()+ for (const text of ['Yes at 1a2b3c', 'https://github.com/a/b/pull/3', 'Merged.', 'on it?', 'Yes, thanks.', 'Okay, thanks.']) expect(() => send(f, f.dev, text)).not.toThrow()+ expect(() => send(f, null, 'on it')).not.toThrow()+ expect(() => send(f, null, 'thanks')).not.toThrow()+ })++ it('passes with a tag or a note to itself', () => {+ const f = stepsFixture()+ expect(() => send(f, f.dev, 'on it', { agentOnly: true, recipientIds: [f.dev] })).not.toThrow()+ })+})diff --git a/backend/src/superTabs/acknowledgements.ts b/backend/src/superTabs/acknowledgements.tsnew file mode 100644index 000000000..83ab0f741--- /dev/null+++ b/backend/src/superTabs/acknowledgements.ts@@ -0,0 +1,34 @@+/**+ * An agent's post that only acknowledges (task #3391, anh Dee's Swarm redesign, 11-05). "On it", "got it", "thanks" and+ * "will do" fill the chat, wake the agent they answer for nothing, and tell nobody what a reaction would not. The server+ * refuses such a post with ACK_ONLY and the next step; a reaction settles the delivery instead (reactions.ts).+ *+ * The classifier is conservative: a post is an acknowledgement only when every clause of it is on the list below, so a real+ * short answer ("Yes at 1a2b3c", "Merged.", a link, a question) is never refused. There is no length number: the list is the+ * whole rule.+ */++/** What a clause may say to acknowledge. At least one clause of a post is one of these. Apostrophes are dropped before the match. */+const ACKNOWLEDGEMENTS: ReadonlySet<string> = new Set([+ 'on it', 'got it', 'i got it', 'took it', 'taking it', 'ill take it', 'will do', 'ill do', 'ill do it', 'noted', 'understood',+ 'acknowledged', 'ack', 'roger', 'roger that', 'copy', 'copy that', 'sounds good', 'makes sense', 'confirmed',+ 'thanks', 'thank you', 'thanks a lot', 'thanks so much', 'many thanks', 'thx', 'ty',+])++/** Words that may stand around an acknowledgement but acknowledge nothing alone. Only greetings: "yes", "ok", "sure" or "great"+ * can answer a question, so "Yes, thanks." is an answer and passes (review of #3391). */+const FILLERS: ReadonlySet<string> = new Set(['hi', 'hey'])++/** A question, a number, a tag, a link or a file name: something the post says beyond acknowledging. */+const SAYS_MORE = /[?@#/\\\d]|:\/\/|[a-z]\.[a-z]/++/** Whether the text says nothing beyond an acknowledgement. */+export function isAcknowledgement(text: string): boolean {+ const plain = text.toLowerCase().replace(/[\p{Extended_Pictographic}️]/gu, '').replace(/['’`]/g, '')+ if (SAYS_MORE.test(plain)) return false+ const clauses = plain.split(/[.,;:!\-–—…\n]+|\s&\s|\band\b/).map(clause => clause.replace(/\s+/g, ' ').trim()).filter(Boolean)+ return clauses.some(clause => ACKNOWLEDGEMENTS.has(clause)) && clauses.every(clause => ACKNOWLEDGEMENTS.has(clause) || FILLERS.has(clause))+}++/** The refusal's words: the guard and the next step. */+export const ACK_ONLY_HINT = 'This post only acknowledges. React to the message instead: 👀 when you start, ✅ when you have done what it asked. Post only substance: a plan, a question, a finding, a verdict or a result.'diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 224f22d47..f18819f3a 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -785,7 +785,7 @@ describe('a Buddy\'s proposal to the PM', () => {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 id = f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline drafts', brief, checks: [], proposalMessageId: root.id },+ 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)}@@ -798,7 +798,7 @@ describe('a Buddy\'s proposal to the PM', () => {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: [], proposalMessageId: root.id, ...fields } as Command, agentActor(f.pm), context).result+ brief: '', checks: [{ description: 'Done', independent: false }], proposalMessageId: root.id, ...fields } as Command, agentActor(f.pm), context).result// Its Buddy said high: a P1, with no warning that none was given.const opened = open()expect(opened).toMatchObject({ priority: 'P1' })diff --git a/backend/src/superTabs/buddyNews.test.ts b/backend/src/superTabs/buddyNews.test.tsindex b7f4eeea3..dad1a0fcd 100644--- a/backend/src/superTabs/buddyNews.test.ts+++ b/backend/src/superTabs/buddyNews.test.ts@@ -105,7 +105,7 @@ describe('which Buddy a project-chat message reaches (Diego, 10-29)', () => {it('is nobody once its person no longer reads the project, has left, or rejoined at a new membership', () => {const lost = setup(), sent = lost.propose()lost.state.projects!.find(p => p.id === lost.app.projectId)!.visibility = 'private'- expect(lost.pmPost('Taking it.', { replyTo: sent }).buddyRecipients).toBeUndefined()+ expect(lost.pmPost('Taking this as its own task.', { replyTo: sent }).buddyRecipients).toBeUndefined()const rejoined = setup(), asked = rejoined.propose()rejoined.state.people.find(p => p.id === 'peer')!.generation = 'second'expect(buddiesTold(rejoined.state, { ...asked, id: 'answer', replyTo: asked.id, thread: asked.id, author: { kind: 'agent', id: rejoined.pm, name: 'pm',@@ -213,18 +213,19 @@ describe('work the PM opens from a Buddy\'s proposal without naming anyone (grouexpect(find().requesterId).toBe('owner')})- it('names nobody, and says so, when the proposal\'s person left the Swarm or no longer reads the project; the group still opens', () => {+ it('is refused naming the requester when the proposal\'s person left the Swarm or no longer reads the project, and opens once the PM names one (task #3389)', () => {for (const lose of [(f: ReturnType<typeof setup>) => { f.state.people = f.state.people.filter(p => p.id !== 'peer') },(f: ReturnType<typeof setup>) => { f.state.projects!.find(p => p.id === f.app.projectId)!.visibility = 'private' }]) {const f = setup(), sent = f.propose()lose(f)- const created = f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline edits', brief: 'Save edits offline.',- checks: [{ description: 'Tests pass', independent: false }], proposalMessageId: sent.id } as Command, agentActor(f.pm),+ const open = (extra: Record<string, unknown> = {}) => f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Offline edits', brief: 'Save edits offline.',+ checks: [{ description: 'Tests pass', independent: false }], proposalMessageId: sent.id, ...extra } as Command, agentActor(f.pm),{ proposal: { id: sent.id, conversationId: sent.conversationId, author: sent.author, source: sent.source ?? null } })- const group = f.state.conversations.find(c => c.id === created.result.conversationId)!- expect(group.requesterId).toBeUndefined()+ expect(() => open()).toThrow(expect.objectContaining({ code: 'TASK_CONTRACT_MISSING', message: expect.stringContaining('requester') }))+ const opened = open({ requesterId: 'owner' }).result.conversationId+ const group = f.state.conversations.find(c => c.id === opened)!+ expect(group.requesterId).toBe('owner')expect(group.ledger?.proposal).toEqual({ buddyId: 'buddy', messageId: sent.id })- expect(created.result).toMatchObject({ requesterUnknown: true, warnings: [expect.stringContaining('Name the person who asked')] })}})diff --git a/backend/src/superTabs/closedAgents.test.ts b/backend/src/superTabs/closedAgents.test.tsindex d131f0ba6..e924fd87c 100644--- a/backend/src/superTabs/closedAgents.test.ts+++ b/backend/src/superTabs/closedAgents.test.ts@@ -66,6 +66,16 @@ describe('closedAgents: which agents a report shows closed', () => {f.state.machines![0]!.observation!.runningHarnessIds = []expect(closedAgents(f.state, 'mac', f.report(['lead']), NOW)).toEqual([])})+ // Task #3397: a crew member's host reopens it in place, so a report never removes one; the same agent off the crew goes.+ it('never takes a crew member, and takes the same agent once it is off the crew', () => {+ const f = fixture()+ f.worker.crew = { role: 'Engineer', at: 1, by: 'owner' }+ expect(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW)).toEqual([])+ f.worker.downSince = new Date(NOW - DOWN_REMOVE_MS).toISOString()+ expect(closedAgents(f.state, 'mac', f.report(['lead']), NOW)).toEqual([])+ delete f.worker.crew+ expect(ids(closedAgents(f.state, 'mac', f.report(['lead'], ['worker']), NOW))).toEqual(['worker'])+ })it('never takes a coordinator', () => {const f = fixture()f.lead.downSince = f.worker.downSincediff --git a/backend/src/superTabs/closedAgents.ts b/backend/src/superTabs/closedAgents.tsindex f4acb523a..677acda49 100644--- a/backend/src/superTabs/closedAgents.ts+++ b/backend/src/superTabs/closedAgents.ts@@ -1,4 +1,5 @@import { isBuddy } from './buddies.js'+import { isCrew } from './crew.js'import { MACHINE_FRESH_MS, productManagerOn, teamAccountPool, teamWorkCheck, type MachineObservation } from './machines.js'import { activeWork, type Agent, type RemovedSession, type SuperTabState } from './model.js'import { agentProjectId, canReadProject, isConfidential, ledProject, onTeamAccount, projectsOf } from './projects.js'@@ -17,9 +18,10 @@ export const REMOVED_KEEP_MS = 30 * 24 * 60 * 60_000* one stopped for a moment before it is back (security reviews of #2569). */export const STOPPED_REMOVE_MS = 30_000-/** Whether [target] could ever leave this way: not a coordinator, a Buddy, one kept or being stopped. */+/** Whether [target] could ever leave this way: not a coordinator, a Buddy, crew (its host reopens it in place, crew.ts), one+ * kept or being stopped. */const removable = (state: SuperTabState, target: Agent): boolean =>- !isBuddy(target) && target.workDecision !== 'keep' && target.workDecision !== 'stop' && !ledProject(state, target.id)+ !isBuddy(target) && !isCrew(target) && target.workDecision !== 'keep' && target.workDecision !== 'stop' && !ledProject(state, target.id)/** Whether [report] proves [target]'s session stopped: listed stopped and, for a reservation a resume renewed, stopped in that* very generation, since an older host lists the earlier run stopped and cannot say which. */diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex f80067e6d..d30aefc45 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1961,7 +1961,7 @@ describe('any agent of the project', () => {it('lets any agent of the project run the task commands', () => {const { f, engineer, E } = project(), A = f.workerconst group = f.run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits while offline.',- checks: [{ description: 'Reconnect preserves the edits.', independent: false }] }, E).result.conversationId as string+ checks: [{ description: 'Reconnect preserves the edits.', independent: false }], priority: 'P2', requesterId: 'owner' }, E).result.conversationId as stringconst task = () => f.state.conversations.find(c => c.id === group)!f.run({ type: 'work.define', conversationId: group, brief: 'Build it.', checks: [{ description: 'Tests pass.', independent: false }] }, E)expect(f.run({ type: 'route.record', conversationId: group, decision: record() } as Command, E).result.routeDecisionId).toEqual(expect.any(String))@@ -2625,7 +2625,7 @@ describe('an agent joining a task by a post or by opening it', () => {it('checks the team access of an agent that opens a task, which it would be in', () => {const { f, mate, mine } = teammate()- const create = { type: 'conversation.create', title: 'Fix it', brief: 'Fix it.', checks: [] } as Command+ const create = { type: 'conversation.create', title: 'Fix it', brief: 'Fix it.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' } as Commandconst groups = f.state.conversations.lengthexpect(() => f.run(create, as(mate))).toThrow(refused)expect(f.state.conversations).toHaveLength(groups)@@ -4115,7 +4115,7 @@ describe('other projects\' work for Leads', () => {const roster = work(docs.projectId, 'Roster', ['desktop/lib/super_tabs'])const name = (id: string) => f.state.agents.find(a => a.id === id)!.displayNameconst overlaps = (effects: ReturnType<typeof f.run>) => effects.messages.filter(m => (m.source as { kind?: string } | undefined)?.kind === 'overlap')- const created = f.run({ type: 'conversation.create', title: 'Agents filter', task: task([' ./desktop/lib/super_tabs/roster.dart ', 'cli']), checks }, as(lead))+ const created = f.run({ type: 'conversation.create', title: 'Agents filter', task: task([' ./desktop/lib/super_tabs/roster.dart ', 'cli']), checks, priority: 'P2', requesterId: 'owner' }, as(lead))const group = created.result.conversationId as stringconst text = `"Agents filter" (Pilot, ${name(lead)}) and "Roster" (Docs, ${name(docs.lead)}) both change desktop/lib/super_tabs/roster.dart.`// The acting Lead created the overlap and is not told again; the other project's Lead hears it in its own project chat.@@ -4916,14 +4916,14 @@ describe('checks are information', () => {it('creates, defines and assigns a task with no checks', () => {const f = routed()- const group = f.run({ type: 'conversation.create', title: 'Docs', brief: 'Fix the docs.', checks: [] }, f.leadActor).result.conversationId as string+ const group = f.run({ type: 'conversation.create', title: 'Docs', brief: 'Fix the docs.', checks: [] }, owner).result.conversationId as stringexpect(f.state.conversations.find(c => c.id === group)!.checks).toEqual([])f.run(commandSchema.parse({ type: 'work.define', conversationId: group, brief: 'Fix the install docs.', checks: [] }), f.leadActor)f.run({ type: 'conversation.agent', conversationId: group, agentId: f.worker, present: true, lead: false }, f.leadActor)const assigned = f.run({ type: 'work.assign', conversationId: group, agentId: f.worker })expect(assigned.messages.find(m => m.recipients.includes(f.worker))!.text).toBe('Fix the install docs.\n\nStart each pull request body with: Requested by owner through Harness.')// A task with no brief at all is assigned too: its title is what its agent reads.- const bare = f.run({ type: 'conversation.create', title: 'Look into the flaky test', brief: '', checks: [] }, f.leadActor).result.conversationId as string+ const bare = f.run({ type: 'conversation.create', title: 'Look into the flaky test', brief: '', checks: [] }, owner).result.conversationId as stringconst other = f.add('other', 'owner', bare)expect(f.run({ type: 'work.assign', conversationId: bare, agentId: other }).messages.find(m => m.recipients.includes(other))!.text).toBe('Look into the flaky test\n\nStart each pull request body with: Requested by owner through Harness.')@@ -5931,8 +5931,10 @@ describe('a task\'s priority (conversation.create and work.priority)', () => {function prioritized() {const f = routed()const task = (id: string) => f.state.conversations.find(g => g.id === id)!+ // An agent's task says its check, priority and who asked (taskContract.ts); a step carries no priority, a person's defaults.const create = (fields: Record<string, unknown> = {}, actor: Actor = f.leadActor) =>- f.run(commandSchema.parse({ type: 'conversation.create', title: 'Sign-in broken', brief: 'Fix it.', checks: [], ...fields }), actor)+ f.run(commandSchema.parse({ type: 'conversation.create', title: 'Sign-in broken', brief: 'Fix it.',+ checks: [{ description: 'Done', independent: false }], ...actor.kind === 'agent' && !fields.reviewOf ? { priority: 'P2', requesterId: 'owner' } : {}, ...fields }), actor)const set = (conversationId: string, priority: string) => commandSchema.parse({ type: 'work.priority', conversationId, priority })return { f, task, create, set }}@@ -5948,7 +5950,7 @@ describe('a task\'s priority (conversation.create and work.priority)', () => {it('gives a task created without one P2, and the reply says so', () => {const { task, create } = prioritized()- const created = create()+ const created = create({}, owner)expect(task(created.result.conversationId as string).priority).toBe('P2')expect(created.result).toMatchObject({ priority: 'P2',warnings: expect.arrayContaining(['No priority given: this task is P2. Set P0-P3 with work.priority.']) })diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex abb22790f..f9e93ace4 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -5,6 +5,7 @@ import { admitByRoom, admitMachineStart, noRepositoryStart, failOwnAccountTeamEnimport { movableEntry } from './computerMoves.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'import { addedAgentName, renameAgentTo } from './agentRename.js'+import { addCrew, CREW_LANES, CREW_ROLE_MAX, removeCrew } from './crew.js'import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'import { agentWrittenNameOf, setName, shownNameOf } from './personNames.js'import { z } from 'zod'@@ -58,10 +59,12 @@ import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy,import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'+import { ACK_ONLY_HINT, isAcknowledgement } from './acknowledgements.js'import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPPED_LINES, refuseRepeats, type ApprovalRow, type DroppedLine } from './ruleGuard.js'import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'import { BUILT_IN_HEADING, tidySaved } from './pmSchedule.js'+import { contractRefusal, missingContract } from './taskContract.js'import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'import { placeAfter, queueSiblings } from './taskQueue.js'@@ -251,6 +254,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(),// How urgent the task is (taskPriority.ts); without one it is P2, and the reply says so.priority: z.enum(TASK_PRIORITIES).optional(),+ // Work no person asked for (a flaky test seen twice, an alarm) names nobody; this says why, in a few words (taskContract.ts).+ noRequesterReason: z.string().trim().min(1).max(200).optional(),// A step of the task `reviewOf` names (task steps design): its name as the instructions give it, free text in any language.// No line break or control character: the name is printed in agents' terminals (final review, minor 10).step: z.string().trim().min(1).max(40).regex(/^[^\u0000-\u001f\u007f]+$/, 'A step name is one line of text.').optional(), checks: z.array(check).max(40),@@ -336,6 +341,8 @@ export const commandSchema = z.discriminatedUnion('type', [// Rename Harness on the agent's Mac renames the agent for every reader (task #2912); the contributor or machine owner only.z.object({ type: z.literal('agent.rename'), agentId: id, name: z.string().max(200) }).strict(),z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),+ z.object({ type: z.literal('crew.add'), agentId: id, role: z.string().trim().min(1).max(CREW_ROLE_MAX).regex(/^[^\x00-\x1f\x7f]+$/).optional(), lane: z.enum(CREW_LANES).optional() }).strict(),+ z.object({ type: z.literal('crew.remove'), agentId: id }).strict(),z.object({ type: z.literal('agent.sessionClosed'), agentId: id, harnessId: id }).strict(),z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),z.object({ type: z.literal('agent.rebind'), agentId: id, machineId: id, projectId: id,@@ -422,13 +429,14 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'member.status': ['status.text'],'agent.add': ['name', 'initialMessage'],'agent.rename': ['name'],+ 'crew.add': ['role'],'agent.start': ['request.name', 'overrideReason'],'agent.startFailed': ['error'],'agent.switchResult': ['error'],'buddy.modelResult': ['error'],'agent.switchHandoff': ['note'],'agent.startSettled': ['warning'],- 'conversation.create': ['title', 'brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'task.review.focus', 'checks[].description'],+ 'conversation.create': ['title', 'brief', 'noRequesterReason', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'task.review.focus', 'checks[].description'],'conversation.rename': ['title'],'buddy.rename': ['name'],'proposal.close': ['reason'],@@ -872,9 +880,6 @@ function proposalRequester(state: SuperTabState, project: SwarmProject, personId/** Who may cancel a lost or stopped task, and a live one (work.cancel), for the refusals that name them. */const WHO_CANCELS_ENDED = 'Only the person who asked for this task, its project\'s owner, the Swarm owner or an agent of this project can cancel it.'const WHO_CANCELS_LIVE = 'Only an agent of this project or the Swarm owner can cancel work in progress. Ask the project\'s coordinator.'-/** What an agent opening a group for nobody is told, so the person who asked still gets the credit (groups #294, #327). */-export const REQUESTER_UNKNOWN = 'Name the person who asked: conversation.requester with their personId for this group, or requesterId when you open a group.'-function open(state: SuperTabState, conversationId: string) {const group = conversation(state, conversationId)if (group.archived) fail('ARCHIVED', 'Reopen this conversation before changing its work.')@@ -2284,6 +2289,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const request = command.requestMessageId ? requestOf(state, project, context.request) : undefinedconst requesterId = command.requesterId ? requester(state, project, command.requesterId): proposalRequester(state, project, proposal?.personId) ?? request?.personId ?? (actor.kind === 'person' ? actor.userId : undefined)+ // An agent's task says its goal, when it is done, its priority and who asked (taskContract.ts, task #3389). A step and a+ // private chat are no task of their own; a Buddy's proposal supplies its brief, priority and person.+ if (actor.kind === 'agent' && prioritized && !command.reviewOf) {+ const missing = missingContract({ goal: brief, checks: command.checks.length, priority: Boolean(command.priority || proposal), requester: Boolean(requesterId || command.noRequesterReason) })+ if (missing.length) fail('TASK_CONTRACT_MISSING', contractRefusal(missing), 400)+ }const number = nextConversationNumber(state)state.groupCounter = number// The agent that opens a task is in it, so an Engineer that opens its own review can post there and pass its checks.@@ -2305,22 +2316,20 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,checks: storedChecks(command.checks, operationId),})recordAsked(state.conversations.at(-1)!, requesterId, context.now)+ // 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+ if (noRequester && state.conversations.at(-1)!.ledger) state.conversations.at(-1)!.ledger!.noRequesterReason = noRequesterif (proposal) recordProposal(state.conversations.at(-1)!, { buddyId: proposal.buddyId, messageId: proposal.messageId })// The asker's message is the task's root; its thread takes the task's replies (taskLine.ts).if (request) state.conversations.at(-1)!.cards = { line: { messageId: request.messageId, conversationId: project.leadConversationId } }result.conversationId = operationIdresult.number = number- // A build group an agent opens for nobody credits nobody when it ships: say so, as the PM can still name them.- if (actor.kind === 'agent' && !requesterId && !command.reviewOf) {- result.requesterUnknown = true- result.warnings = [REQUESTER_UNKNOWN]- }if (prioritized) {result.priority = state.conversations.at(-1)!.priorityif (!command.priority && !proposal) result.warnings = [...result.warnings as string[] ?? [], PRIORITY_DEFAULTED]}if (brief) {- message(operationId, brief, [], null, SYSTEM_ROW)+ message(operationId, noRequester ? `${brief}\n\nNo requester: ${noRequester}` : brief, [], null, SYSTEM_ROW)bindTaskCard(state.conversations.at(-1)!, effects.messages.at(-1)!)}break@@ -3210,6 +3219,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,case 'agent.rename':renameAgentTo(state, actor, agent(state, command.agentId), command.name)break+ case 'crew.add':+ addCrew(state, actor, agent(state, command.agentId), command.role, command.lane, context.now)+ break+ case 'crew.remove':+ removeCrew(state, actor, agent(state, command.agentId))+ breakcase 'agent.remove': {const target = agent(state, command.agentId)const hostStop = actor.kind === 'agent' && actor.agentId === target.id && target.workDecision === 'stop'@@ -3323,6 +3338,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)}result.changed = react(group, command.messageId, command.on, context.reaction)+ // A reaction is how an agent acknowledges (ACK_ONLY refuses the post), so it settles the agent's delivery of that message.+ if (actor.kind === 'agent' && command.on) effects.settles = { messageId: command.messageId, agentId: actor.agentId }break}case 'message.edit':@@ -3381,6 +3398,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const ids = [...new Set(command.attachmentIds ?? [])]const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)+ // An agent's post that says nothing beyond an acknowledgement is refused: a reaction acknowledges (task #3391). Never a+ // person's, a note to itself, a post with a file or a tag, or a Buddy's talk with its person.+ if (actor.kind === 'agent' && !command.agentOnly && !attachments.length && !command.mentions?.length && !isBuddyChat(group) && isAcknowledgement(command.text)) {+ fail('ACK_ONLY', ACK_ONLY_HINT, 400)+ }// A voice message is its clip alone, and its words are its text: what agents, search and older apps read (voiceMessages.ts).const voice = attachments.find(a => a.voice)if (voice && (attachments.length > 1 || command.text || command.mentions?.length)) {diff --git a/backend/src/superTabs/crew.test.ts b/backend/src/superTabs/crew.test.tsnew file mode 100644index 000000000..42b49d1a2--- /dev/null+++ b/backend/src/superTabs/crew.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import { createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'+import { isCrew } from './crew.js'+import { projectsOf } from './projects.js'++// Task #3397: a project's crew, the agents the Swarm keeps alive and never closes for being idle.++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++function fixture() {+ let state = 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, commandSchema.parse(command), { now: 5000, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const add = (harnessId: string, lead = false, roleName?: string) => {+ const agentId = run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId, name: harnessId, configuration: config, lead },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ if (roleName) state.agents.find(a => a.id === agentId)!.roleName = roleName+ return agentId+ }+ const invite = (role: 'viewer' | 'collaborator') => {+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ }+ const pm = add('pm', true), worker = add('worker', false, 'Engineer')+ const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })+ const target = (id = worker) => state.agents.find(a => a.id === id)!+ return { run, add, invite, pm, worker, agentActor, target, get state() { return state } }+}++describe('crew.add and crew.remove', () => {+ it('lets the project\'s PM mark an agent as crew, with its role, and take it off again', () => {+ const f = fixture()+ f.run({ type: 'crew.add', agentId: f.worker, role: 'Reviewer' }, f.agentActor(f.pm))+ expect(f.target().crew).toEqual({ role: 'Reviewer', at: 5000, by: f.pm })+ expect(isCrew(f.target())).toBe(true)+ f.run({ type: 'crew.remove', agentId: f.worker }, f.agentActor(f.pm))+ expect(f.target().crew).toBeUndefined()+ expect(isCrew(f.target())).toBe(false)+ })++ it('names the role the agent goes by when none is given, and lets a person of the project add one', () => {+ const f = fixture()+ f.run({ type: 'crew.add', agentId: f.worker })+ expect(f.target().crew).toEqual({ role: 'Engineer', at: 5000, by: 'owner' })+ })++ it('refuses a viewer, another agent that is not the PM, the PM itself and a Buddy', () => {+ const f = fixture()+ f.invite('viewer')+ // The Swarm's own guard refuses a viewer's every write first.+ expect(() => f.run({ type: 'crew.add', agentId: f.worker }, peer)).toThrow(/read-only/)+ const other = f.add('other')+ expect(() => f.run({ type: 'crew.add', agentId: f.worker }, f.agentActor(other))).toThrow(/PM or the person who runs/)+ expect(() => f.run({ type: 'crew.remove', agentId: f.worker }, f.agentActor(other))).toThrow(/PM or the person who runs/)+ expect(() => f.run({ type: 'crew.add', agentId: f.pm })).toThrow(/already kept/)+ f.target(other).buddyOf = { personId: 'owner', generation: f.state.people[0]!.generation }+ expect(() => f.run({ type: 'crew.add', agentId: other })).toThrow(/Buddy/)+ expect(f.state.agents.some(a => a.crew)).toBe(false)+ })++ // Budget's automatic assignment (River, 11-05): a member gets its lane's top task; one with no lane, the project's.+ it('keeps an optional lane, one of the project\'s five, and none when not given', () => {+ const f = fixture()+ f.run({ type: 'crew.add', agentId: f.worker, role: 'Engineer', lane: 'desktop' }, f.agentActor(f.pm))+ expect(f.target().crew).toEqual({ role: 'Engineer', lane: 'desktop', at: 5000, by: f.pm })+ f.run({ type: 'crew.add', agentId: f.worker, role: 'Engineer' }, f.agentActor(f.pm))+ expect(f.target().crew).toEqual({ role: 'Engineer', at: 5000, by: f.pm })+ for (const lane of ['backend', 'cli', 'desktop', 'mobile', 'docs']) expect(commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', lane }).success).toBe(true)+ for (const lane of ['', 'web', 'Backend']) expect([lane, commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', lane }).success]).toEqual([lane, false])+ })++ // River for security review 1 of #3222 (the Swarm goes public): of the people, only the Swarm's or the project's owner,+ // or the person who runs the agent or whose machine it runs on, as agent.release takes.+ it('refuses a collaborator who neither owns the Swarm or project nor runs the agent', () => {+ const f = fixture()+ f.invite('collaborator')+ expect(() => f.run({ type: 'crew.add', agentId: f.worker }, peer)).toThrow(/PM or the person who runs/)+ expect(f.target().crew).toBeUndefined()+ f.target().machineOwnerId = 'peer'+ f.run({ type: 'crew.add', agentId: f.worker }, peer)+ expect(f.target().crew).toMatchObject({ by: 'peer' })+ })++ it('refuses the person who runs the agent once they cannot read its private project', () => {+ const f = fixture()+ f.invite('collaborator')+ f.target().machineOwnerId = 'peer'+ f.state.projects = projectsOf(f.state).map(p => ({ ...p, visibility: 'private' as const, members: [] }))+ expect(() => f.run({ type: 'crew.add', agentId: f.worker }, peer)).toThrow()+ expect(f.target().crew).toBeUndefined()+ })++ it('refuses a role that is empty, too long or holds control characters', () => {+ for (const role of ['', ' ', 'x'.repeat(41), 'Rev\u0007iewer']) {+ expect([role, commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', role }).success]).toEqual([role, false])+ }+ expect(commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', role: 'x'.repeat(40) }).success).toBe(true)+ })++ it('shows crew in what every reader of the Swarm reads (status)', () => {+ const f = fixture()+ f.run({ type: 'crew.add', agentId: f.worker, role: 'Tester' })+ const seen = visibleState(f.state, f.agentActor(f.pm)).agents.find(a => a.id === f.worker)+ expect(seen?.crew).toEqual({ role: 'Tester', at: 5000, by: 'owner' })+ })+})diff --git a/backend/src/superTabs/crew.ts b/backend/src/superTabs/crew.tsnew file mode 100644index 000000000..45e6dc49c--- /dev/null+++ b/backend/src/superTabs/crew.ts@@ -0,0 +1,50 @@+/**+ * A project's crew (task #3397, anh Dee's Swarm redesign, 11-05): named agents the Swarm keeps alive. Their host reopens a+ * crashed or frozen session in place (cli superTabs/crew.ts), and no idle path closes or removes one: the CLI's idle cleanup+ * (its retention names crew), the coordinator's idle notice (tidy.ts) and the removal of closed agents (closedAgents.ts).+ * A crashed crew member keeps its task for CREW_REOPEN_GRACE_MS, while its host reopens it (liveness.ts).+ *+ * The numbers here stay in this one place until the project rules record lands (sibling task of #3397).+ */+import { isBuddy } from './buddies.js'+import { roleNameOf } from './instructions.js'+import { fail, type Actor, type Agent, type SuperTabState } from './model.js'+import { agentProjectId, canReadProject, ledProject, ownsProject, projectOf } from './projects.js'++/** How long a crew member whose session stopped keeps its task while its host reopens it in place. */+export const CREW_REOPEN_GRACE_MS = 5 * 60_000+/** The longest role a crew entry names, in characters. */+export const CREW_ROLE_MAX = 40+/** The lanes a crew member may work in: automatic assignment gives it its lane's top task, and one with no lane the+ * project's (River for Budget, 11-05). */+export const CREW_LANES = ['backend', 'cli', 'desktop', 'mobile', 'docs'] as const+export type CrewLane = typeof CREW_LANES[number]++export const isCrew = (target: Pick<Agent, 'crew'>): boolean => !!target.crew++/** Who may change [target]'s crew mark: its project's PM, or, of the people who read the project and are no viewer, the+ * Swarm's owner, the project's owner, the person who runs the agent or the owner of the machine it runs on, as agent.release+ * takes (River for security review 1 of #3222, before the Swarm goes public): a crew mark makes that machine reopen it. */+function mayManageCrew(state: SuperTabState, actor: Actor, target: Agent): void {+ const project = projectOf(state, agentProjectId(state, target))+ const allowed = actor.kind === 'agent'+ ? ledProject(state, actor.agentId)?.id === project.id+ : state.people.find(p => p.id === actor.userId)?.role !== 'viewer' && canReadProject(state, actor, project)+ && (actor.userId === state.ownerId || ownsProject(state, actor.userId, project) || [target.contributorId, target.machineOwnerId].includes(actor.userId))+ if (!allowed) fail('FORBIDDEN', 'Only the project\'s PM or the person who runs this agent, its machine\'s owner or the project\'s owner can change its crew.', 403)+}++/** `crew.add`: marks [target] as crew, with [role] or the role it goes by, and its [lane] if any. Again on crew replaces it.+ * Never the PM (kept alive already) nor a Buddy. */+export function addCrew(state: SuperTabState, actor: Actor, target: Agent, role: string | undefined, lane: CrewLane | undefined, now: number): void {+ mayManageCrew(state, actor, target)+ if (isBuddy(target)) fail('CREW_BUDDY', 'A Buddy waits for its person; it is never crew.')+ if (ledProject(state, target.id)) fail('CREW_LEAD', 'The PM is already kept alive; it needs no crew mark.')+ target.crew = { role: role ?? roleNameOf(state, target).slice(0, CREW_ROLE_MAX), ...lane ? { lane } : {}, at: now, by: actor.kind === 'agent' ? actor.agentId : actor.userId }+}++/** `crew.remove`: [target] goes back to the ordinary idle handling. */+export function removeCrew(state: SuperTabState, actor: Actor, target: Agent): void {+ mayManageCrew(state, actor, target)+ delete target.crew+}diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex a90135503..be7aaf4c5 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -27,7 +27,7 @@ function fixture() {name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as stringconst asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })const create = (actor: Actor = owner, extra: Record<string, unknown> = {}) =>- run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, ...extra }), actor).result.conversationId as string+ run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, priority: 'P2', ...actor.kind === 'agent' ? { requesterId: 'owner' } : {}, ...extra }), actor).result.conversationId as stringconst group = (id: string): Conversation => state.conversations.find(c => c.id === id)!/** The owner's Buddy chat in the Swarm's project, as adding a Buddy opens it: the one private chat (buddies.ts). */const buddyChat = () => {@@ -68,26 +68,17 @@ describe('who asked for a group', () => {expect(f.group(id).requesterId).toBe('peer')})- it('leaves the requester unknown when a Lead names nobody, rather than guessing', () => {- const f = fixture(), lead = f.add('lead', 'lead', true)- const id = f.create(f.asAgent(lead))- expect(f.group(id).requesterId).toBeUndefined()- expect(f.group(id).ledger).toEqual({ askedAt: 1_000 })- })-- it('tells a Lead that opens a build group for nobody to name who asked; never for a named requester, a person or a review', () => {+ it('refuses a Lead that names nobody, rather than guessing, and asks nobody of a person or a review (task #3389)', () => {const f = fixture(), lead = f.add('lead', 'lead', true)f.invitePeer()- // Each gives a priority, so the only warning left is who asked (a task without one is told it is P2: task #3117).+ expect(() => f.create(f.asAgent(lead), { requesterId: undefined })).toThrow(expect.objectContaining({ code: 'TASK_CONTRACT_MISSING' }))+ // A person opens it for themselves, and a review is a step of the task: neither names anyone and neither is refused.const open = (actor: Actor, extra: Record<string, unknown> = {}) =>f.run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks, priority: 'P2', ...extra }), actor).result- const unnamed = open(f.asAgent(lead))- expect(unnamed).toMatchObject({ requesterUnknown: true, warnings: [expect.stringContaining('Name the person who asked')] })- for (const result of [open(f.asAgent(lead), { requesterId: 'peer' }), open(owner),- open(f.asAgent(lead), { reviewOf: unnamed.conversationId as string, title: 'Review: Offline editing' })]) {- expect(result.requesterUnknown).toBeUndefined()- expect(result.warnings).toBeUndefined()- }+ const named = open(f.asAgent(lead), { requesterId: 'peer' })+ for (const result of [named, open(owner)]) expect(result.warnings).toBeUndefined()+ expect(open(f.asAgent(lead), { reviewOf: named.conversationId as string, title: 'Review: Offline editing', priority: undefined }).conversationId)+ .toEqual(expect.any(String))})it('refuses a requester who is not a member of the Swarm', () => {diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex a1cdb3ab8..2595f30a2 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -50,6 +50,8 @@ export interface ReviewHour extends RanOn { hour: number; count: number }/** A group's leaderboard bookkeeping; readers never get it whole (read/views.ts groupView). */export interface GroupLedger {askedAt?: number+ /** Why nobody is named as its requester, said by the agent that opened work no person asked for (taskContract.ts). */+ noRequesterReason?: string/** When it shipped: its earliest recorded merge, or without one the first time its work was done. A group is one request,* so finishing it again ships nothing new. */shippedAt?: numberdiff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex ef0128809..2994b6898 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import type { AgentStart, Assignment, SuperTabState } from './model.js'import { changesRequested, LEASE_MS, loseTasks, nextLossAt, QUIET_RUNNING_MS, renewOwnTask, revisionReady, sweepForLead, sweepLiveness, waitingForReview } from './liveness.js'import { MACHINE_FRESH_MS, startPreparing } from './machines.js'+import { CREW_REOPEN_GRACE_MS } from './crew.js'import { split } from './parts/index.js'import { stepsFixture } from './steps.test-support.js'@@ -131,6 +132,32 @@ describe('a task waiting for review', () => {expect(handOff({ reviewFoundAt: handedOver })).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 45 minutes' } })})+ // Task #3397: a crashed crew member's host reopens it in place, so it keeps its task for CREW_REOPEN_GRACE_MS after its+ // session went down; one still down then loses it as any worker does. Its machine going offline still loses it at once.+ it('keeps a crew member\'s task while its host reopens it, and loses it once the grace ends', () => {+ const crewStopped = (downFor: number) => {+ const state = quiet('working', 1)+ state.machines![0]!.observation!.stoppedHarnessIds = ['h']+ state.agents[0]!.crew = { role: 'Engineer', at: 1, by: 'p' }+ state.agents[0]!.downSince = new Date(handedOver + MINUTE - downFor).toISOString()+ return state+ }+ expect(status(crewStopped(CREW_REOPEN_GRACE_MS - 1), handedOver + MINUTE)).toMatchObject({ status: 'working' })+ expect(status(crewStopped(CREW_REOPEN_GRACE_MS), handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })+ const notCrew = crewStopped(CREW_REOPEN_GRACE_MS - 1)+ delete notCrew.agents[0]!.crew+ expect(status(notCrew, handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })+ // Asleep (closed on purpose) or moved to another machine (task #3398): nothing reopens it here, so no grace.+ for (const gone of [{ asleep: { since: 1 } }, { movedTo: 'w2' }]) {+ const away = crewStopped(CREW_REOPEN_GRACE_MS - 1)+ Object.assign(away.agents[0]!, gone)+ expect(status(away, handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })+ }+ const offline = quiet('working', 1)+ offline.agents[0]!.crew = { role: 'Engineer', at: 1, by: 'p' }+ expect(status(offline, handedOver + 4 * MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its machine Mac has been offline for 2 minutes' } })+ })+it('is still lost at once when its session stops or its machine goes offline', () => {const stopped = quiet('review', 1)stopped.machines![0]!.observation!.stoppedHarnessIds = ['h']diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 3fd2be5a4..f5d3e75d1 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -1,3 +1,4 @@+import { CREW_REOPEN_GRACE_MS, isCrew } from './crew.js'import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,type SuperTabState, type TaskLiveness } from './model.js'import { failedSessionStart } from './buddySessions.js'@@ -299,10 +300,18 @@ export function nextLossAt(state: SuperTabState, machineId: string): number | unreturn ends.length ? Math.min(...ends) : undefined}+/** A crew member whose session went down less than CREW_REOPEN_GRACE_MS ago, which its host is reopening: never one asleep+ * (closed on purpose) or moved to another machine (task #3398 adds both marks), which its host leaves closed. */+const reopening = (worker: Agent, now: number): boolean => {+ const away = worker as Agent & { asleep?: unknown; movedTo?: unknown }+ return isCrew(worker) && !away.asleep && !away.movedTo && !!worker.downSince && now - Date.parse(worker.downSince) < CREW_REOPEN_GRACE_MS+}+/** Why a worker has lost its task now, or null while it still holds it. Only a machine that has reported can be offline. */function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex): string | null {const pool = state.machines?.find(m => m.machineId === worker.machineId)- if (pool?.observation?.stoppedHarnessIds.includes(worker.harnessId)) return sessionStopped(pool.name)+ // A crew member's host reopens its session in place (crew.ts): it keeps its task for the reopen's grace.+ if (pool?.observation?.stoppedHarnessIds.includes(worker.harnessId) && !reopening(worker, now)) return sessionStopped(pool.name)if (pool?.observation && now - pool.observation.receivedAt > OFFLINE_LOST_MS) return machineOffline(pool.name)const limited = limitReason(worker, now)if (limited) return limiteddiff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 00afbbe01..0126c30f8 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -73,6 +73,9 @@ export interface Agent {* close it (agent.stopRefused). */idleStop?: { previous: 'awaiting' | 'keep' | null }releaseId?: string+ /** Set while it is one of its project's crew (crew.ts): its host keeps it alive, and no idle path closes or removes it.+ * `by` is the person's or PM agent's id that marked it. */+ crew?: { role: string; lane?: 'backend' | 'cli' | 'desktop' | 'mobile' | 'docs'; at: number; by: string }/** A person's request to move this Product Manager to another engine or account (lead.switch), carried out by its host.* `id` is the operation that asked; `claimedUntil` is set once the host took it (agent.switchClaim). *//** The switch request the last rebind settled, until its result arrives: that result is the one line the chat gets, and@@ -753,6 +756,8 @@ export interface CommandEffects {result: Record<string, unknown>/** `message.edit`'s new text, credentials removed (commands.ts WORDS): what the store writes into the row. */messageEdit?: { messageId: string; text: string }+ /** An agent's reaction settles that agent's own deliveries of the message it reacted to, as an answer does (reactions.ts; the store closes the rows). */+ settles?: { messageId: string; agentId: string }/** A terminal request or its answer, written outside the tab state by the store (terminal.ts). */terminal?: import('./terminal.js').TerminalEffect/** A Buddy's proposal closed by hand, written into the open proposals by the store (proposals.ts closeProposal). */diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.tsindex a5ceb562a..b20edc906 100644--- a/backend/src/superTabs/parts/touches.test.ts+++ b/backend/src/superTabs/parts/touches.test.ts@@ -97,7 +97,7 @@ describe('the parts a command touches (design section 1.2, column T)', () => {const f = swarm()const invited = f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' }).effects.result.inviteId as stringf.run({ type: 'invite.accept', inviteId: invited }, { kind: 'person', userId: 'peer', email: '[email protected]' })- const opened = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [{ description: 'Done', independent: false }], requesterId: 'peer' },+ const opened = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'peer' },f.agentActor(f.lead))expect(has(opened.touches, 'member', 'peer')).toBe(true)const id = opened.effects.result.conversationId as string@@ -108,7 +108,7 @@ describe('the parts a command touches (design section 1.2, column T)', () => {it('makes a priority change meet a change of who is PM on the project\'s chat (task #3117)', () => {const f = swarm()- const id = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [] }, f.agentActor(f.lead)).effects.result.conversationId as string+ const id = f.run({ type: 'conversation.create', title: 'R', brief: 'Do it', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' }, f.agentActor(f.lead)).effects.result.conversationId as stringconst changed = f.run({ type: 'work.priority', conversationId: id, priority: 'P0' }, f.agentActor(f.lead))expect(has(changed.touches, 'group', 'lead')).toBe(true)})diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex ccc48f6cd..246502cef 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -169,7 +169,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatehead()break}- case 'agent.release':+ case 'agent.release': case 'crew.add': case 'crew.remove':leadCheck(agentProject(command.agentId))breakcase 'agent.rebind':diff --git a/backend/src/superTabs/postRecipients.test.ts b/backend/src/superTabs/postRecipients.test.tsindex da3737f98..fd132e0da 100644--- a/backend/src/superTabs/postRecipients.test.ts+++ b/backend/src/superTabs/postRecipients.test.ts@@ -36,7 +36,7 @@ describe('an agent post that names no one', () => {const { f, post, to } = setup()const other = f.add('other', f.task)f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: 'Merged' } as Command, f.as(f.dev))- expect(to(post(other, f.task, 'Thanks.'))).toEqual([[]])+ expect(to(post(other, f.task, 'Thanks, it merged.'))).toEqual([[]])expect(to(post(f.dev, f.task, 'Merged.'))).toEqual([[]])})@@ -143,8 +143,8 @@ describe('the PM\'s deliveries in a fixture hour', () => {const rows = [...['Plan pushed.', 'Task 1 red.', 'Task 1 green.', 'PR is ready.', 'CI green.', 'Merged main in.'].flatMap(t => post(f.dev, f.task, t)),...['Reading the diff.', 'Ready to merge: With fixes', 'Ready to merge: Yes'].flatMap(t => post(reviewer, step, t)),- ...post(reviewer, f.task, 'Understood.'),- ...post(other, f.task, 'On it.'),+ ...post(reviewer, f.task, 'Understood, re-reading the plan.'),+ ...post(other, f.task, 'On it, starting with the fixtures.'),...post(f.dev, f.task, '@owner here is the mockup.'),...['Ken, I am on it.', 'Ken, it shipped.'].flatMap(t => post(f.dev, 'lead', t)),...post(f.dev, step, 'Fixed in abc123.', [reviewer]),diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex 50644a050..a733209a1 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -75,7 +75,7 @@ describe('projects inside an invite-only swarm', () => {const f = setup(), p = f.project()const lead = f.add(p.conversationId, 'lead')const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host' }- const work = f.run({ type: 'conversation.create', title: 'Work', brief: 'Deliver it', checks: [{ description: 'It works', independent: true }] }, actor)+ const work = f.run({ type: 'conversation.create', title: 'Work', brief: 'Deliver it', checks: [{ description: 'It works', independent: true }], priority: 'P2', requesterId: 'owner' }, actor)expect(f.state.conversations.find(c => c.id === work.conversationId)).toMatchObject({ projectId: p.projectId, agentIds: [lead], leadId: lead })expect(visibleState(f.state, actor).projects!.map(p => p.id)).toEqual([p.projectId])expect(() => f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: lead, present: true, lead: false })).toThrow('separate agent')diff --git a/backend/src/superTabs/reactions.test.ts b/backend/src/superTabs/reactions.test.tsindex cda384e75..51842e450 100644--- a/backend/src/superTabs/reactions.test.ts+++ b/backend/src/superTabs/reactions.test.ts@@ -95,4 +95,18 @@ describe('reactions', () => {const rows = ['rocket', 'check', 'eyes'].map(emoji => ({ messageId: 'm1', emoji, actorKind: 'agent', actorId: builder }))expect(reactionCounts(f.state, rows).get('m1')!.map(r => r.emoji)).toEqual(['eyes', 'check', 'rocket'])})++ // Task #3391: a reaction settles the reacting agent's delivery of the message, as an answer does (the store closes the rows).+ it('tells the store which delivery an agent\'s reaction settles, and settles nothing for anyone else', () => {+ const f = fixture()+ const builder = f.agent('lead', 'Builder')+ f.lead().agentIds.push(builder)+ for (const emoji of ['eyes', 'check', 'thumbs_up']) {+ expect(f.run(react(true, emoji), asAgent(builder), target(false)).settles, emoji).toEqual({ messageId: 'm1', agentId: builder })+ }+ // A repeat of the reaction still settles: its delivery may have come back since.+ expect(f.run(react(true, 'eyes'), asAgent(builder), target(true)).settles).toEqual({ messageId: 'm1', agentId: builder })+ expect(f.run(react(false, 'eyes'), asAgent(builder), target(true)).settles).toBeUndefined()+ expect(f.run(react(true), owner, target(false)).settles).toBeUndefined()+ })})diff --git a/backend/src/superTabs/steps.test-support.ts b/backend/src/superTabs/steps.test-support.tsindex 5aa850b15..23b05c434 100644--- a/backend/src/superTabs/steps.test-support.ts+++ b/backend/src/superTabs/steps.test-support.ts@@ -21,7 +21,7 @@ export function stepsFixture() {const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })const lead = add('pm', 'lead', true)const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.',- checks: [{ description: 'Signs in offline', independent: true }] }, as(lead)).result.conversationId as string+ checks: [{ description: 'Signs in offline', independent: true }], priority: 'P2', requesterId: 'owner' }, as(lead)).result.conversationId as stringconst dev = add('dev', task)run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))const step = (name: string, actor: Actor = as(dev), on = task, checks: Array<{ description: string; independent: boolean }> = []) =>diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.tsindex edf45a3ef..39e9a2113 100644--- a/backend/src/superTabs/steps.test.ts+++ b/backend/src/superTabs/steps.test.ts@@ -259,7 +259,7 @@ describe('a step closes with its task', () => {it('cancelling an unassigned task closes its steps', () => {const f = stepsFixture()- const other = f.run({ type: 'conversation.create', title: 'Docs', brief: 'Write docs.', checks: [] }, f.as(f.lead)).result.conversationId as string+ const other = f.run({ type: 'conversation.create', title: 'Docs', brief: 'Write docs.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as stringconst id = f.step('Review', f.as(f.lead), other)f.run({ type: 'work.cancel', conversationId: other, assignmentId: 'current', reason: 'Not needed' } as Command, f.as(f.lead))expect(f.group(other).archived).toBe(true)@@ -509,7 +509,7 @@ describe('the PM is not told what a step\'s agent says to its task', () => {const rev = f.add('rev', id)f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))f.run({ type: 'work.status', conversationId: id, assignmentId: f.group(id).assignment!.id, status: 'done', result: 'Passed' } as Command, f.as(rev))- const other = f.run({ type: 'conversation.create', title: 'Fix logout', brief: 'Sign out works.', checks: [] }, f.as(f.lead)).result.conversationId as string+ const other = f.run({ type: 'conversation.create', title: 'Fix logout', brief: 'Sign out works.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as stringconst dev2 = f.add('dev2', other)f.run({ type: 'work.assign', conversationId: other, agentId: dev2 }, f.as(f.lead))const second = f.step('Review', f.as(dev2), other)diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex abe3417d7..dac5da35b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -2137,11 +2137,10 @@ export class SuperTabStore {// deliveries of the message.if (command.type === 'message.send' && (command.replyTo || command.answers) && actor.kind === 'agent') {// A notice gathered for the digest and answered before it (read in its chat): the digest does not name it again.- const replyTo = (command.replyTo ?? command.answers)!, agentId = actor.agentId- await this.endDeliveries(tx, tabId, { where: { messageId: replyTo, agentId } }, () => tx.superTabDelivery.updateMany({ where: { tabId, messageId: replyTo, agentId,- status: { in: ['queued', 'claimed', 'uncertain', 'delivered', 'confirmed', 'gathered'] } },- data: { status: 'answered', answeredAt: new Date(context.now), holdReason: null, holdSince: null } }))+ await this.settleAnswered(tx, tabId, (command.replyTo ?? command.answers)!, actor.agentId, context.now)}+ // An agent's reaction settles its delivery of the message as an answer does (task #3391).+ if (effects.settles) await this.settleAnswered(tx, tabId, effects.settles.messageId, effects.settles.agentId, context.now)if (command.type === 'project.report' && actor.kind === 'agent') {// Judged on the progress after this report summarized what it names.const progress = projectsOf(effects.state).find(p => p.id === command.projectId)?.progress@@ -2632,6 +2631,13 @@ export class SuperTabStore {claimed: own.map(r => r.id), proposed: handed.map(r => r.id) }}+ /** Closes an agent's own open deliveries of a message as answered: by its reply, its answer right below it, or its reaction. */+ private async settleAnswered(tx: Transaction, tabId: string, messageId: string, agentId: string, now: number) {+ await this.endDeliveries(tx, tabId, { where: { messageId, agentId } }, () => tx.superTabDelivery.updateMany({ where: { tabId, messageId, agentId,+ status: { in: ['queued', 'claimed', 'uncertain', 'delivered', 'confirmed', 'gathered'] } },+ data: { status: 'answered', answeredAt: new Date(now), holdReason: null, holdSince: null } }))+ }+/** The message a reaction names, when it is in that conversation and this actor may see it, and whether the actor already* reacted to it with that emoji. An agent-only notice is its recipient's alone. */private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand, state: SuperTabState): Promise<ReactionTarget | undefined> {diff --git a/backend/src/superTabs/taskContract.test.ts b/backend/src/superTabs/taskContract.test.tsnew file mode 100644index 000000000..2dc8c01b1--- /dev/null+++ b/backend/src/superTabs/taskContract.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }+const checks = [{ description: 'Works', independent: false }]+const task = { goal: 'Save edits offline.', changes: 'Queue them.', constraints: 'None.', owns: ['backend/'] }++function fixture() {+ let state = 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: 1_000, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ const lead = run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'lead', name: 'lead', configuration: config, lead: true },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ const agent: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ const create = (extra: Record<string, unknown>, actor: Actor = agent) =>+ run(commandSchema.parse({ type: 'conversation.create', title: 'Offline editing', ...extra }), actor)+ return { create, agent, run }+}++const whole = { brief: 'Save edits offline.', checks, priority: 'P2', requesterId: 'peer' }+const refusal = (fields: string[]) => expect.objectContaining({ code: 'TASK_CONTRACT_MISSING', status: 400,+ message: expect.stringContaining(fields.join(', ')) })++describe('the task contract: what an agent says when it opens a task', () => {+ it('opens a task that gives its goal, a check, a priority and who asked', () => {+ const f = fixture()+ expect(f.create(whole).result.conversationId).toEqual(expect.any(String))+ expect(f.create({ task, checks, priority: 'P1', requesterId: 'peer' }).result.conversationId).toEqual(expect.any(String))+ })++ it.each([+ ['goal', { brief: '' }],+ ['goal', { brief: ' ' }],+ ['checks', { checks: [] }],+ ['priority', { priority: undefined }],+ ['requester', { requesterId: undefined }],+ ])('refuses an agent\'s task with no %s, naming it', (field, change) => {+ const f = fixture()+ expect(() => f.create({ ...whole, ...change })).toThrow(refusal([field!]))+ })++ it('names every missing field at once, with an example of a whole create', () => {+ const f = fixture()+ expect(() => f.create({ brief: '', checks: [] })).toThrow(refusal(['goal', 'checks', 'priority', 'requester']))+ expect(() => f.create({ brief: '', checks: [] })).toThrow(expect.objectContaining({ message: expect.stringContaining('"type":"conversation.create"') }))+ })++ it('refuses the PM (the project\'s coordinator) the same way', () => {+ const f = fixture()+ expect(() => f.create({ ...whole, requesterId: undefined })).toThrow(refusal(['requester']))+ })++ it('accepts a recorded reason in place of a requester, keeps it on the task and shows it in the task\'s first row (River, task #3389)', () => {+ const f = fixture()+ const reason = 'found by the PM: second flaky sighting'+ const created = f.create({ ...whole, requesterId: undefined, noRequesterReason: reason })+ const group = created.state.conversations.find(c => c.id === created.result.conversationId)!+ expect(group.requesterId).toBeUndefined()+ expect(group.ledger?.noRequesterReason).toBe(reason)+ expect(created.messages.find(m => m.conversationId === group.id)!.text).toBe(`Save edits offline.\n\nNo requester: ${reason}`)+ // The reason stands only for the requester: every other field is still asked, and the refusal says how to give it.+ expect(() => f.create({ ...whole, requesterId: undefined, noRequesterReason: reason, checks: [] })).toThrow(refusal(['checks']))+ expect(() => f.create({ ...whole, requesterId: undefined })).toThrow(expect.objectContaining({ message: expect.stringContaining('noRequesterReason') }))+ expect(() => f.create({ ...whole, requesterId: undefined, noRequesterReason: ' ' })).toThrow()+ })++ it('records no reason when someone is named: the requester wins', () => {+ const f = fixture()+ const created = f.create({ ...whole, noRequesterReason: 'not needed' })+ const group = created.state.conversations.find(c => c.id === created.result.conversationId)!+ expect(group.requesterId).toBe('peer')+ expect(group.ledger?.noRequesterReason).toBeUndefined()+ expect(created.messages.find(m => m.conversationId === group.id)!.text).toBe('Save edits offline.')+ })++ it('leaves a person\'s task with today\'s defaults alone: no priority or check needed, the requester is the person', () => {+ const f = fixture()+ const created = f.create({ title: 'Offline editing', brief: 'Save edits.', checks: [] }, owner)+ expect(created.result).toMatchObject({ priority: 'P2' })+ expect(created.state.conversations.at(-1)!.requesterId).toBe('owner')+ expect(f.create({ brief: '', checks: [] }, peer).result.conversationId).toEqual(expect.any(String))+ })++ it('does not ask a step of a task for a contract: it is no task of its own', () => {+ const f = fixture()+ const parent = f.create(whole).result.conversationId as string+ expect(f.create({ title: 'Review', reviewOf: parent, step: 'Review', brief: '', checks: [] }).result.conversationId).toEqual(expect.any(String))+ })+})diff --git a/backend/src/superTabs/taskContract.ts b/backend/src/superTabs/taskContract.tsnew file mode 100644index 000000000..cc9a3fd1b--- /dev/null+++ b/backend/src/superTabs/taskContract.ts@@ -0,0 +1,23 @@+/**+ * The task contract (task #3389, Dee's Swarm redesign, 2026-11-05): a task an agent opens says its goal, how to tell it is+ * done (at least one check), its priority and who asked. People keep today's defaults; the server refuses an agent's create+ * that leaves one out, naming the fields and showing a whole create, so the fix is one resend. The code is new on purpose:+ * the refusals project instructions removed (removedRefusals.test.ts) stay removed.+ */+export const CONTRACT_FIELDS = ['goal', 'checks', 'priority', 'requester'] as const+export type ContractField = typeof CONTRACT_FIELDS[number]++/** What a create gave. `requester` is the person already resolved from requesterId, a proposal or a request message. */+export interface ContractGiven { goal: string; checks: number; priority: boolean; requester: boolean }++export const missingContract = (given: ContractGiven): ContractField[] => CONTRACT_FIELDS.filter(field =>+ field === 'goal' ? !given.goal.trim() : field === 'checks' ? given.checks < 1 : field === 'priority' ? !given.priority : !given.requester)++const EXAMPLE = '{"type":"conversation.create","title":"Short plain title","task":{"goal":"What to build","changes":"...","constraints":"...","owns":["path/"]},'+ + '"checks":[{"description":"Observable proof it is done","independent":false}],"priority":"P2","requesterId":"PERSON"}'++/** The refusal's text: what is missing, the next step, and an example. */+export const contractRefusal = (missing: readonly ContractField[]): string =>+ `Missing: ${missing.join(', ')}. A task an agent opens says its goal, at least one check that says when it is done, a priority (P0 to P3, P0 only for the PM) and the person who asked (requesterId). `+ + `Work no person asked for (a flaky test seen twice, an alarm) names nobody: give noRequesterReason, a few words on why, in place of requesterId. `+ + `Add ${missing.length === 1 ? 'it' : 'them'} and send the create again, for example ${EXAMPLE}`diff --git a/backend/src/superTabs/taskLine.test.ts b/backend/src/superTabs/taskLine.test.tsindex ef3a8c4c3..123720ac3 100644--- a/backend/src/superTabs/taskLine.test.ts+++ b/backend/src/superTabs/taskLine.test.ts@@ -25,7 +25,7 @@ function fixture() {author: { kind: 'person' as const, id: 'owner', name: owner.email, membershipGeneration: state.people[0]!.generation } })/** A task the PM opens for the owner's message [ask]: its thread is the task's (taskLine.ts). */const group = (title = 'Offline drafts', extra: Record<string, unknown> = {}, ask = 'ask') => run({ type: 'conversation.create', title,- brief: 'Keep drafts.', checks: [], requestMessageId: ask, ...extra } as Command, as(pm), { request: request(ask) } as Partial<CommandContext>)+ brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: ask, ...extra } as Command, as(pm), { request: request(ask) } as Partial<CommandContext>).result.conversationId as stringconst task = (id: string) => state.conversations.find(c => c.id === id)!const status = (id: string, worker: string, value: 'working' | 'needs_human' | 'blocked' | 'review' | 'done' | 'stopped', result: string | null = null,@@ -40,8 +40,8 @@ describe('ordinary task messages and progress replies', () => {// own conversation, never as a row under its requester's name or the PM's.it('posts nothing in the project chat for a task no message asked for, whoever opens it', () => {const f = fixture()- for (const [actor, extra] of [[owner, {}], [f.as(f.pm), { requesterId: 'owner' }], [f.as(f.pm), {}]] as const) {- const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], ...extra } as Command, actor)+ for (const [actor, extra] of [[owner, {}], [f.as(f.pm), { requesterId: 'owner' }]] as const) {+ const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', ...extra } as Command, actor)const id = created.result.conversationId as stringexpect(created.messages.filter(m => m.conversationId !== id)).toEqual([])expect(f.task(id).cards?.line).toBeUndefined()@@ -54,9 +54,9 @@ describe('ordinary task messages and progress replies', () => {it('names each task in the thread of the message that asked for it, and several tasks may share that message', () => {const f = fixture()- const first = f.run({ type: 'conversation.create', title: 'Phone shows who answered', brief: 'Show who answered.', checks: [], requestMessageId: 'ask' } as Command,+ const first = f.run({ type: 'conversation.create', title: 'Phone shows who answered', brief: 'Show who answered.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command,f.as(f.pm), { request: f.request() } as Partial<CommandContext>)- const second = f.run({ type: 'conversation.create', title: 'Desktop shows who answered', brief: 'Same on Desktop.', checks: [], requestMessageId: 'ask' } as Command,+ const second = f.run({ type: 'conversation.create', title: 'Desktop shows who answered', brief: 'Same on Desktop.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command,f.as(f.pm), { request: f.request() } as Partial<CommandContext>)for (const [created, title] of [[first, 'Phone shows who answered'], [second, 'Desktop shows who answered']] as const) {const id = created.result.conversationId as string@@ -106,7 +106,7 @@ describe('ordinary task messages and progress replies', () => {.map(m => (m.source as { ask?: string } | undefined)?.ask)it('is on it from the brief to the merge, then shipped', () => {- const f = fixture(), first = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], requestMessageId: 'ask' } as Command,+ const f = fixture(), first = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command,f.as(f.pm), { request: f.request() } as Partial<CommandContext>)const id = first.result.conversationId as string, root = f.task(id).cards!.line!.messageIdexpect(marks(first, root)).toEqual(['on-it'])@@ -131,7 +131,7 @@ describe('ordinary task messages and progress replies', () => {const f = fixture(), generation = f.state.people[0]!.generationconst request = { id: 'ask', conversationId: 'lead', author: { kind: 'person' as const, id: 'owner', name: owner.email, membershipGeneration: generation },source: null, replyTo: null }- const id = f.run({ type: 'conversation.create', title: 'Who answered', brief: 'Show who answered.', checks: [], requestMessageId: 'ask' } as Command,+ const id = f.run({ type: 'conversation.create', title: 'Who answered', brief: 'Show who answered.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command,f.as(f.pm), { request } as Partial<CommandContext>).result.conversationId as stringconst builder = f.add('Kai', id)expect(marks(f.status(id, (f.run({ type: 'work.assign', conversationId: id, agentId: builder }), builder), 'review', 'Ready.'), 'ask')).toEqual(['on-it'])@@ -173,7 +173,7 @@ describe('ordinary task messages and progress replies', () => {const project = f.run({ type: 'project.create', name: 'Quiet', visibility: 'private', brief: '' }).result.projectId as stringconst chat = f.state.projects!.find(p => p.id === project)!.leadConversationIdexpect(f.state.conversations.find(c => c.id === chat)!.leadId ?? null).toBeNull()- const id = f.run({ type: 'conversation.create', projectId: project, title: 'Offline drafts', brief: 'Keep drafts.', checks: [], requestMessageId: 'quiet-ask' } as Command,+ const id = f.run({ type: 'conversation.create', projectId: project, title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'quiet-ask' } as Command,owner, { request: f.request('quiet-ask', chat) } as Partial<CommandContext>).result.conversationId as stringconst root = f.task(id).cards!.line!.messageIdconst builder = f.add('Kai', id)@@ -202,7 +202,7 @@ describe('ordinary task messages and progress replies', () => {it('links a proposal root instead of posting a second opening message, and adds no brief under the proposal', () => {const f = fixture()- const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], proposalMessageId: 'proposal' }, f.as(f.pm),+ const created = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', proposalMessageId: 'proposal' }, f.as(f.pm),{ proposal: { id: 'proposal', conversationId: 'lead', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: f.state.people[0]!.generation },source: { kind: 'buddy-proposal', personId: 'owner', buddyId: 'former-buddy' } } })expect(f.lines(created)).toEqual([])@@ -215,7 +215,7 @@ describe('ordinary task messages and progress replies', () => {const generation = f.state.people[0]!.generationconst request = { id: 'ask', conversationId: 'lead', author: { kind: 'person' as const, id: 'owner', name: owner.email, membershipGeneration: generation },source: null, replyTo: null }- const created = f.run({ type: 'conversation.create', title: 'Who answered', brief: 'Show who answered.', checks: [], requestMessageId: 'ask' } as Command,+ const created = f.run({ type: 'conversation.create', title: 'Who answered', brief: 'Show who answered.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command,f.as(f.pm), { request } as Partial<CommandContext>)const id = created.result.conversationId as stringexpect(created.messages.filter(m => m.conversationId === 'lead' && !m.thread)).toEqual([])@@ -257,7 +257,7 @@ describe('ordinary task messages and progress replies', () => {it('reacts on a Buddy\'s proposal that a task was opened from', () => {const f = fixture()- const id = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [], proposalMessageId: 'proposal' }, f.as(f.pm),+ const id = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2', proposalMessageId: 'proposal' }, f.as(f.pm),{ proposal: { id: 'proposal', conversationId: 'lead', author: { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: f.state.people[0]!.generation },source: { kind: 'buddy-proposal', personId: 'owner', buddyId: 'former-buddy' } } }).result.conversationId as stringconst builder = f.add('Kai', id)@@ -267,7 +267,7 @@ describe('ordinary task messages and progress replies', () => {it('reacts nowhere for a task no message asked for', () => {const f = fixture()- const id = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [] }).result.conversationId as string+ const id = f.run({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [{ description: 'Done', independent: false }], priority: 'P2' }).result.conversationId as stringconst builder = f.add('Kai', id), seq = chatSeq(f)expect(f.run({ type: 'work.assign', conversationId: id, agentId: builder }).reactions ?? []).toEqual([])f.status(id, builder, 'done', `Checks passed: ${PR}`)@@ -287,7 +287,7 @@ describe('ordinary task messages and progress replies', () => {]for (const index of [0, 1, 2, 3, 4]) {const f = fixture()- expect(() => f.run({ type: 'conversation.create', title: 'Who answered', brief: '', checks: [], requestMessageId: 'ask' } as Command, f.as(f.pm),+ expect(() => f.run({ type: 'conversation.create', title: 'Who answered', brief: '', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'ask' } as Command, f.as(f.pm),{ request: cases(f)[index] } as Partial<CommandContext>)).toThrow(expect.objectContaining({ code: 'REQUEST_UNKNOWN' }))}})@@ -304,7 +304,7 @@ describe('ordinary task messages and progress replies', () => {const f = fixture()const project = f.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).result.projectId as stringconst chat = f.state.projects!.find(p => p.id === project)!.leadConversationId- const parent = f.run({ type: 'conversation.create', projectId: project, title: 'Hidden work', brief: 'Hidden.', checks: [], requestMessageId: 'secret-ask' } as Command,+ const parent = f.run({ type: 'conversation.create', projectId: project, title: 'Hidden work', brief: 'Hidden.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requestMessageId: 'secret-ask' } as Command,owner, { request: f.request('secret-ask', chat) } as Partial<CommandContext>).result.conversationId as stringexpect(f.task(parent).cards?.line).toEqual({ messageId: 'secret-ask', conversationId: chat })const step = f.run({ type: 'conversation.create', projectId: project, title: 'Review', step: 'Review', reviewOf: parent, brief: 'Review.', checks: [] })diff --git a/backend/src/superTabs/teamWritten.test.ts b/backend/src/superTabs/teamWritten.test.tsindex a070b982b..d2a86341f 100644--- a/backend/src/superTabs/teamWritten.test.ts+++ b/backend/src/superTabs/teamWritten.test.ts@@ -63,7 +63,7 @@ describe('a task a Team agent worked on', () => {it('does not mark a task when a Team agent opens it, is added to it, is named into it or posts there', () => {const f = swarm(), builder = f.member('main-builder', 'mac')const asBuilder: Actor = { kind: 'agent', agentId: builder, machineOwnerId: 'owner' }- const opened = f.group({}, { kind: 'agent', agentId: f.member('team-a', 'mac-team'), machineOwnerId: 'owner' })+ const opened = f.group({ checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' }, { kind: 'agent', agentId: f.member('team-a', 'mac-team'), machineOwnerId: 'owner' })const added = f.group(), named = f.group(), posted = f.group()for (const task of [added, named, posted]) f.run({ type: 'conversation.agent', conversationId: task, agentId: builder, present: true, lead: false })const told = [diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.tsindex 8e5deac8b..8c0e1d38b 100644--- a/backend/src/superTabs/tidy.test.ts+++ b/backend/src/superTabs/tidy.test.ts@@ -54,6 +54,14 @@ describe('idle agents', () => {expect(target(state).idleNoticedAt).toBe(at + 2 * MINUTE)})+ // Task #3397: a crew member stands by between tasks; the coordinator is not told to stop it.+ it('never tells of a crew member, and tells of the same agent off the crew', () => {+ const crew = swarm({ agents: [worker({ crew: { role: 'Engineer', at: START, by: 'p' } })], groups: [] })+ expect(idleNotices(crew, 'lead', at, new Set())).toEqual([])+ delete target(crew).crew+ expect(idleNotices(crew, 'lead', at, new Set())).toEqual([expect.objectContaining({ text: 'Rowan has had no open task for 15 minutes.' })])+ })+it('never tells of a Buddy, the coordinator, an agent with a delivery waiting or one in a task with active work', () => {const buddy = swarm({ agents: [worker({ buddyOf: { personId: 'p', generation: 'g' } })], groups: [] })expect(idleNotices(buddy, 'lead', at, new Set())).toEqual([])diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 1fb66ac5a..28e21f895 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -1,5 +1,6 @@import { checksOpenWork, isStep, taskEnded } from './steps.js'import { isBuddy } from './buddies.js'+import { isCrew } from './crew.js'import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'import { agentDisplayName } from './agentNames.js'import { githubRepository, type GitHubRepository } from '../github/repository.js'@@ -47,7 +48,7 @@ function waitingToResume(state: SuperTabState, target: Agent): boolean {/*** Tells the project's coordinator, once per idle spell, of every agent of the project with no open task for IDLE_NOTICE_MS:- * not a Buddy (it waits for its person) nor the coordinator, not stopping nor kept (a keep answers the notice until the agent+ * not a Buddy (it waits for its person), crew (it stands by between tasks, crew.ts) nor the coordinator, not stopping nor kept (a keep answers the notice until the agent* is assigned again, which clears it, and finishes that work), with no delivery waiting for it (`busy`), not* waiting to resume after a usage limit, and in no loaded group with active work. One row in the coordinator's chat, to it* alone (model.ts NOTICE_READERS `idle`); the agent's `idleNoticedAt` records the spell, so the next poll says nothing until@@ -60,7 +61,7 @@ export function idleNotices(state: SuperTabState, projectId: string, now: numberif (!project || !coordinator) return []const rows: MessageDraft[] = []for (const target of state.agents) {- if (target.id === coordinator.id || isBuddy(target) || target.workDecision === 'stop' || target.workDecision === 'keep' || busy.has(target.id)+ if (target.id === coordinator.id || isBuddy(target) || isCrew(target) || target.workDecision === 'stop' || target.workDecision === 'keep' || busy.has(target.id)|| agentProjectId(state, target) !== projectId || waitingToResume(state, target)) continueconst groups = groupsOf(state, target)if (groups.some(activeWork)) continuediff --git a/cli/src/lib/swarmTools.spec.ts b/cli/src/lib/swarmTools.spec.tsindex 9c19d4c7e..11289d266 100644--- a/cli/src/lib/swarmTools.spec.ts+++ b/cli/src/lib/swarmTools.spec.ts@@ -95,7 +95,12 @@ describe('SWARM_TOOLS_SKILL', () => {// Task #3117: the tools say how a task gets its priority and who changes it, as the help does.it('says how a task gets its priority, what P0 to P3 mean, and who changes it', () => {expect(SWARM_TOOLS_SKILL).toContain('- `mine`: what you work on, one line per task, P0 first: its number, priority, title,')- expect(SWARM_TOOLS_SKILL).toContain('`"priority":"P0|P1|P2|P3"` (P0 hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; without one the task is P2)')+ expect(SWARM_TOOLS_SKILL).toContain('`"priority":"P0|P1|P2|P3"` (P0 hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; an agent\'s task must give one, a person\'s without one is P2)')+ // Task #3389: an agent\'s task says what it needs, and how work nobody asked for names no requester.+ expect(SWARM_TOOLS_SKILL).toContain('An agent\'s task (the PM\'s too) needs a goal, at least one check, a priority and `requesterId`')+ expect(SWARM_TOOLS_SKILL).toContain('TASK_CONTRACT_MISSING')+ expect(SWARM_TOOLS_SKILL).toContain('`"noRequesterReason":"found by the PM: second flaky sighting"`')+ expect(SWARM_TOOLS_SKILL).not.toContain('checks may be empty')expect(SWARM_TOOLS_SKILL).toContain('- `{"type":"work.priority","conversationId":"GROUP","priority":"P0"}` changes a task\'s priority. Only a person or the project\'s coordinator may send it, and only they set P0.\n')})// River, 11-04 (task #2926): proposals answered before threads, or built without the task's link, closed by hand.diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.tsindex 63cf48d18..299888190 100644--- a/cli/src/lib/swarmTools.ts+++ b/cli/src/lib/swarmTools.ts@@ -58,7 +58,7 @@ JSONPut OPERATION_ID before the JSON, on the same command line. A refusal says what to fix; change something before you resend.Task and group commands:-- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. Optional: \`"priority":"P0|P1|P2|P3"\` (P0 hotfix: something shipped is broken, loses data, or stops people's or agents' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; without one the task is P2), \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths; checks may be empty. A task is taken as written: one with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts you gave.+- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. An agent's task (the PM's too) needs a goal, at least one check, a priority and \`requesterId\`; without them the Swarm refuses with TASK_CONTRACT_MISSING, naming what is missing with an example to resend. A person's task keeps its defaults. Work no person asked for gives \`"noRequesterReason":"found by the PM: second flaky sighting"\` (a few words, up to 200 characters) in place of \`requesterId\`; it is recorded and shown in the task's first row. A step (\`reviewOf\`) is asked for none of it. Also: \`"priority":"P0|P1|P2|P3"\` (P0 hotfix: something shipped is broken, loses data, or stops people's or agents' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; an agent's task must give one, a person's without one is P2), \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths. A task is taken as written: one with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts you gave.- \`{"type":"work.define","conversationId":"GROUP","task":{...},"checks":[...]}\` sets or replaces the task of a group already open (same shape).- \`{"type":"conversation.agent","conversationId":"GROUP","agentId":"AGENT","present":true,"lead":false}\` adds an agent to a group (\`present\` false removes it).- \`{"type":"conversation.requester","conversationId":"GROUP","personId":"PERSON"}\` names who asked for a group already open (null clears).diff --git a/cli/src/services/agentCleanup.spec.ts b/cli/src/services/agentCleanup.spec.tsindex 2546b8844..6724fdacf 100644--- a/cli/src/services/agentCleanup.spec.ts+++ b/cli/src/services/agentCleanup.spec.ts@@ -94,6 +94,23 @@ it('never closes a Swarm Lead, idle or orphaned, even once its roster has lapsedt.cleanup.port.stop()})+// Task #3397: a crew member stands by between tasks, in no open group: the idle close never takes it, as long as the roster+// marks it crew; the same harness off the crew is closed as before.+it('never closes a crew member idle in no open group, and closes the same harness once it is off the crew', async () => {+ const sessions = [kid('crew'), kid('member')]+ const t = setup(sessions, { crew: 2 * IDLE_CLOSE_MS, member: 2 * IDLE_CLOSE_MS })+ const crewRow = { tabId: 'tab', active: false, agent: { harnessId: 'crew', machineId: 'machine-1', crew: { role: 'Reviewer', at: 1, by: 'pm' } } }+ retainContributions(dir, 'machine-1', [crewRow, { tabId: 'tab', active: false, agent: { harnessId: 'member', machineId: 'machine-1' } }])+ await t.cleanup.look()+ t.advance(IDLE_CLOSE_MS + MIN)+ await t.cleanup.look()+ expect(t.closeStarted.mock.calls).toEqual([['member', 'idle']])+ retainContributions(dir, 'machine-1', [{ ...crewRow, agent: { harnessId: 'crew', machineId: 'machine-1' } }])+ await t.cleanup.look()+ expect(t.closeStarted.mock.calls).toEqual([['member', 'idle'], ['crew', 'idle']])+ t.cleanup.port.stop()+})+// HARNESS_SWARM=off: the Swarm hands in no members, its saved roster is not read, and a harness it kept is an ordinary// one another agent started: closed with its starter, closed once idle, and closable by the core. The review of #1765// found it kept, where the same harness on a computer without the Swarm is closed.diff --git a/cli/src/superTabs/crew.spec.ts b/cli/src/superTabs/crew.spec.tsnew file mode 100644index 000000000..c683cfcc2--- /dev/null+++ b/cli/src/superTabs/crew.spec.ts@@ -0,0 +1,244 @@+import { describe, expect, it, vi } from 'vitest'+import type { SuperTabScreen } from '../core/api.js'+import { fakeCore } from '../testing/fakeCore.js'+import { CREW_CONTINUE, CREW_CONTINUE_TRIES, CREW_FROZEN_MS, CREW_LOOK_MS, CrewKeeper, isCrewRow } from './crew.js'++// Task #3397: the host keeps a project's crew alive. A frozen crew session (the engine working, its whole screen still for+// 30 minutes) is closed so the keep-alive reopens it in place; a reopened one still holding its task is told to continue.++const crew = { role: 'Engineer', at: 1, by: 'pm' }+const row = (over: Record<string, unknown> = {}, agent: Record<string, unknown> = {}) =>+ ({ tabId: 'tab', active: true, agent: { id: 'a1', harnessId: 'h1', machineId: 'm1', crew, ...agent }, ...over })++/** A keeper on a fake core. The screen is [text] with [hold]; typing adds to it, and Enter goes through only on the screen+ * the caller read (inputIfScreen, as the core's pane lock does). `still` is when the whole screen last changed, which the+ * terminal watch records from its own reads. */+function setup(options: { working?: () => boolean; owns?: () => boolean; typing?: () => boolean; team?: boolean } = {}) {+ let clock = 1_000_000+ let text = '❯ '+ let hold: 'permission_open' | null = null+ let still: number | undefined = clock+ const steps: string[] = []+ const closeMember = vi.fn(async (id: string) => { steps.push(`close ${id}`); return { closed: true as const } })+ const activity = vi.fn(async (ids: string[]) => Object.fromEntries(ids.map(id => [id, (options.working?.() ?? true) ? 'working' as const : 'idle' as const])))+ const screen = vi.fn(async (): Promise<SuperTabScreen> => ({ ok: true, text, hold }))+ const core = fakeCore({+ agents: {+ byAgent: vi.fn((id: string) => (['h1', 'h2'].includes(id) ? { agentId: id } as never : undefined)),+ terminalAvailable: vi.fn(() => true),+ activity,+ closeMember,+ },+ superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen,+ input: vi.fn(async (_id: string, typed: string) => {+ if (options.typing && !options.typing()) return { ok: false as const, error: 'PANE_BUSY' }+ steps.push(`type ${typed}`); text = `❯ ${typed}`; return { ok: true as const }+ }),+ inputIfScreen: vi.fn(async (_id: string, keys: string[], seen: string) => {+ if (seen !== text || hold) return { ok: false as const, error: 'SCREEN_CHANGED' }+ steps.push(keys.join(' ')); text = '❯ '; return { ok: true as const }+ }) },+ })+ const log = vi.fn()+ const keeper = new CrewKeeper(core, 'm1', { now: () => clock, log, owns: async () => options.owns?.() ?? true, stillSince: () => still, team: () => options.team ?? false })+ return { core, keeper, steps, log, closeMember, activity, screen,+ wait: (ms: number) => { clock += ms },+ moved: () => { still = clock },+ prompt: (open: boolean) => { hold = open ? 'permission_open' : null; text = open ? 'Allow? 1. Yes 2. No' : text },+ show: (next: string) => { text = next },+ unknown: () => { still = undefined } }+}++describe('which roster rows are crew this host keeps alive', () => {+ it('is a row whose agent is crew, not asleep and not moved', () => {+ expect(isCrewRow(row())).toBe(true)+ expect(isCrewRow(row({}, { crew: undefined }))).toBe(false)+ expect(isCrewRow(row({}, { crew: { role: '' } }))).toBe(false)+ expect(isCrewRow(row({}, { asleep: { since: 5 } }))).toBe(false)+ expect(isCrewRow(row({}, { movedTo: 'a2' }))).toBe(false)+ expect(isCrewRow({})).toBe(false)+ })+})++describe('a frozen crew session', () => {+ it('is closed once the engine has been working with an unchanged screen for 30 minutes, so its keep-alive reopens it', async () => {+ const t = setup()+ await t.keeper.tick([row()])+ // Looked at once a minute: still 29 minutes in, frozen at 30.+ for (let i = 1; i < CREW_FROZEN_MS / CREW_LOOK_MS; i++) { t.wait(CREW_LOOK_MS); await t.keeper.tick([row()]) }+ expect(t.closeMember).not.toHaveBeenCalled()+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual(['close h1'])+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('froze'))+ })++ // Review of #3222 (ENGINEERING.md 4, the daemon's idle work): the keeper reads no screen of its own for this, and asks the+ // engines' activity once a minute for all its crew in one call, whatever the host's poll rate.+ it('reads no screen and asks activity once a minute for all crew in one call', async () => {+ const t = setup()+ const rows = [row(), row({}, { id: 'a2', harnessId: 'h2' })]+ for (let i = 0; i < 120; i++) { t.wait(1_000); await t.keeper.tick(rows) }+ expect(t.screen).not.toHaveBeenCalled()+ expect(t.activity.mock.calls).toEqual([[['h1', 'h2']], [['h1', 'h2']]])+ })++ it('is not one whose screen moves, nor one idle at its prompt, nor one off the crew, nor one never read', async () => {+ const moving = setup()+ await moving.keeper.tick([row()])+ for (let i = 0; i < 40; i++) { moving.wait(CREW_LOOK_MS); moving.moved(); await moving.keeper.tick([row()]) }+ expect(moving.closeMember).not.toHaveBeenCalled()+ const idle = setup({ working: () => false })+ await idle.keeper.tick([row()])+ idle.wait(2 * CREW_FROZEN_MS)+ await idle.keeper.tick([row()])+ expect(idle.closeMember).not.toHaveBeenCalled()+ const ordinary = setup()+ await ordinary.keeper.tick([row({}, { crew: undefined })])+ ordinary.wait(2 * CREW_FROZEN_MS)+ await ordinary.keeper.tick([row({}, { crew: undefined })])+ expect(ordinary.closeMember).not.toHaveBeenCalled()+ const unread = setup()+ unread.unknown()+ await unread.keeper.tick([row()])+ unread.wait(2 * CREW_FROZEN_MS)+ await unread.keeper.tick([row()])+ expect(unread.closeMember).not.toHaveBeenCalled()+ })++ // Security review 1 of #3222: on a Team daemon a close is the Swarm's end for good, which deletes a Team-written Codex+ // session's own engine home (inCore/teamPurge.ts), so the reopen could not resume it. There it is left, and said once.+ it('is never closed on a Team daemon, where a close deletes what the reopen needs', async () => {+ const t = setup({ team: true })+ await t.keeper.tick([row()])+ for (let i = 0; i < 2 * CREW_FROZEN_MS / CREW_LOOK_MS; i++) { t.wait(CREW_LOOK_MS); await t.keeper.tick([row()]) }+ expect(t.closeMember).not.toHaveBeenCalled()+ expect(t.log.mock.calls.filter(([line]) => String(line).includes('Team account'))).toHaveLength(1)+ })++ it('is never closed when its session is confidential: closing one deletes its data in a Team account', async () => {+ const t = setup()+ await t.keeper.tick([row({ confidential: true })])+ t.wait(2 * CREW_FROZEN_MS)+ await t.keeper.tick([row({ confidential: true })])+ expect(t.closeMember).not.toHaveBeenCalled()+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('confidential'))+ })++ it('counts its 30 minutes again after the engine went idle', async () => {+ let working = true+ const t = setup({ working: () => working })+ await t.keeper.tick([row()])+ t.wait(CREW_FROZEN_MS - CREW_LOOK_MS)+ working = false+ await t.keeper.tick([row()])+ working = true+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.closeMember).not.toHaveBeenCalled()+ })+})++describe('a reopened crew session', () => {+ it('is told once to continue its task, only after no prompt waits on its screen', async () => {+ const t = setup({ working: () => false })+ t.prompt(true)+ t.keeper.reopened('h1')+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([])+ t.prompt(false)+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ })++ // Reviews of #3222: a prompt that opens between the screen read and the typing must never take the Enter.+ it('never sends Enter to a prompt that opened after its screen was read, and continues once it is answered', async () => {+ const t = setup({ working: () => false })+ t.keeper.reopened('h1')+ vi.mocked(t.core.superTabs!.input).mockImplementationOnce(async (_id, typed) => { t.steps.push(`type ${typed}`); t.prompt(true); return { ok: true } })+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`])+ t.prompt(false)+ t.show(`❯ ${CREW_CONTINUE}`)+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ // The screen after its typing was never seen without the prompt: it is typed again (at worst twice), never a bare Enter.+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, `type ${CREW_CONTINUE}`, 'Enter'])+ })++ // Review of #3222: a typing that failed for a moment is tried again, a few times, never dropped at once.+ it('tries a continue that failed again, at most CREW_CONTINUE_TRIES times, and says once it gave up', async () => {+ let fails = 2+ const t = setup({ working: () => false, typing: () => fails-- <= 0 })+ t.keeper.reopened('h1')+ for (let i = 0; i < 3; i++) { await t.keeper.tick([row()]); t.wait(CREW_LOOK_MS) }+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ const never = setup({ working: () => false, typing: () => false })+ never.keeper.reopened('h1')+ for (let i = 0; i < CREW_CONTINUE_TRIES + 3; i++) { await never.keeper.tick([row()]); never.wait(CREW_LOOK_MS) }+ expect(vi.mocked(never.core.superTabs!.input)).toHaveBeenCalledTimes(CREW_CONTINUE_TRIES)+ expect(never.log.mock.calls.filter(([line]) => /gave up/i.test(String(line)))).toHaveLength(1)+ })++ // Review 2 of #3222: after a second crash the restored history shows the first continue; the composer is empty, so it is+ // typed again, never an Enter on an empty prompt.+ it('types the continue again when only the history shows it, never a bare Enter', async () => {+ const t = setup({ working: () => false })+ t.show(`❯ ${CREW_CONTINUE}\n\n⏺ Picking the task up again.\n\n${'─'.repeat(40)}\n❯ \n${'─'.repeat(40)}\n ? for shortcuts`)+ t.keeper.reopened('h1')+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ })++ // Review 3 of #3222: typed, then a prompt opened before the Enter; once it is answered the composer was cleared and only the+ // history still shows an older continue. The Enter goes only on the exact screen its own typing left, so it types again.+ it('types again when the screen its typing left is gone, though the history shows the continue', async () => {+ const t = setup({ working: () => false })+ t.keeper.reopened('h1')+ vi.mocked(t.core.superTabs!.inputIfScreen).mockImplementationOnce(async () => { t.prompt(true); return { ok: false, error: 'SCREEN_CHANGED' } })+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`])+ t.prompt(false)+ t.show(`❯ ${CREW_CONTINUE}\n\n⏺ Earlier answer.\n${'─'.repeat(40)}\n❯ \n${'─'.repeat(40)}`)+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, `type ${CREW_CONTINUE}`, 'Enter'])+ })++ it('sends only the Enter when the screen its typing left is back once a prompt is answered', async () => {+ const t = setup({ working: () => false })+ t.keeper.reopened('h1')+ vi.mocked(t.core.superTabs!.inputIfScreen).mockImplementationOnce(async () => ({ ok: false, error: 'SCREEN_CHANGED' }))+ await t.keeper.tick([row()])+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ })++ // Review 2 of #3222: a terminal gone for a moment keeps the continue owed while the roster names the crew member.+ it('keeps the continue owed while its terminal is away for a moment', async () => {+ let away = true+ const t = setup({ working: () => false })+ vi.mocked(t.core.agents.terminalAvailable).mockImplementation(() => !away)+ t.keeper.reopened('h1')+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([])+ away = false+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([`type ${CREW_CONTINUE}`, 'Enter'])+ })++ it('is told nothing when it holds no task here', async () => {+ const t = setup({ working: () => false, owns: () => false })+ t.keeper.reopened('h1')+ await t.keeper.tick([row()])+ t.wait(CREW_LOOK_MS)+ await t.keeper.tick([row()])+ expect(t.steps).toEqual([])+ })+})diff --git a/cli/src/superTabs/crew.ts b/cli/src/superTabs/crew.tsnew file mode 100644index 000000000..08e9d51a4--- /dev/null+++ b/cli/src/superTabs/crew.ts@@ -0,0 +1,162 @@+/**+ * A project's crew on this machine (task #3397, anh Dee's Swarm redesign, 11-05): named agents the Swarm keeps alive. The+ * backend marks one (`agent.crew`, backend superTabs/crew.ts); its roster row carries the mark. This host then keeps it as it+ * keeps the PM (host.ts keepAlive: a gone session is reopened in place), restarts one whose screen froze, and types one+ * continue into a reopened session that still holds its task. The retention names crew (retention.ts), so the idle cleanup+ * (services/agentCleanup.ts) never closes one, and the core lets this host reopen it (inCore/agents.ts keepLeadAlive).+ *+ * The numbers here stay in this one place until the project rules record lands (sibling task of #3397).+ */+import type { CoreApi } from '../core/api.js'+import { WAITING } from './terminal.js'+import { identifier, object } from './wire.js'++/** A crew session the engine says is working whose whole screen did not change this long is frozen: it is restarted. */+export const CREW_FROZEN_MS = 30 * 60_000+/** How often a crew member's screen is looked at for a freeze. */+export const CREW_LOOK_MS = 60_000+/** Typed once into a reopened crew session that still holds its task: nothing old is replayed, the task goes on. */+export const CREW_CONTINUE = 'continue: your session was reopened after it stopped, and this task is still yours'+/** How many times a continue that failed (the pane busy, a prompt in the way) is tried, a look apart, before it is given up. */+export const CREW_CONTINUE_TRIES = 5++/** Whether a host roster row marks its agent as crew this host keeps alive: crew (`agent.crew` with a role), not asleep (closed+ * on purpose by crew sleep, task #3398) and not moved to another machine (`movedTo`, task #3398), which is gone here. */+export function isCrewRow(row: unknown): boolean {+ const agent = object(object(row).agent), role = object(agent.crew).role+ return typeof role === 'string' && role.length > 0 && !agent.asleep && !agent.movedTo+}++/** Whether this machine's assignment rows name a task running in session [harnessId] (host.ts reads its feed). */+type Owns = (harnessId: string) => Promise<boolean>++/** What the keeper knows of one crew session here: since when its engine has been seen working without a break. */+interface Watch { workingSince: number; said?: string }+/** A continue still owed to a reopened session: when it may be tried next, how many tries it has left, and the screen this+ * reopen's own typing left, whose Enter is still owed (null until it typed, or once that screen is gone). Only that exact+ * screen takes the Enter: after a second crash the history shows an earlier continue over an empty composer, and a prompt+ * answered meanwhile may have cleared it (reviews 2 and 3 of #3222). At worst the text is typed twice, never a bare Enter. */+interface Owed { at: number; tries: number; typed: string | null }++/**+ * Restarts a frozen crew session and continues a reopened one. The keep-alive itself is the host's (host.ts keepAlive),+ * shared with the PM: a gone session is reopened in place on its own conversation. A frozen one is closed here (the core's+ * closeMember, which keeps its conversation) so that keep-alive reopens it.+ *+ * It reads no screen of its own for a freeze: the terminal watch records when each whole screen last changed+ * (terminal.ts stillSince), and this asks the engines' activity once a minute for all its crew in one call (review of #3222,+ * ENGINEERING.md 4: the daemon's idle work).+ *+ * Never a close where it deletes what the reopen needs: a confidential session's data, and on a Team daemon any session's+ * (inCore/teamPurge.ts deletes a Team-written Codex session's own engine home, security review 1 of #3222).+ */+export class CrewKeeper {+ private readonly watches = new Map<string, Watch>()+ private readonly owed = new Map<string, Owed>()+ private lookedAt = -Infinity+ private running: Promise<void> | null = null+ private readonly now: () => number+ private readonly log: (message: string) => void+ private readonly owns: Owns+ private readonly stillSince: (harnessId: string) => number | undefined+ private readonly team: () => boolean++ constructor(private readonly core: CoreApi, private readonly machineId: string,+ options: { owns: Owns; stillSince: (harnessId: string) => number | undefined; team: () => boolean; now?: () => number; log?: (message: string) => void }) {+ this.owns = options.owns+ this.stillSince = options.stillSince+ this.team = options.team+ this.now = options.now ?? Date.now+ this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))+ }++ /** The keep-alive reopened crew session [harnessId]: it is told to continue once its screen takes input. */+ reopened(harnessId: string): void {+ this.owed.set(harnessId, { at: 0, tries: CREW_CONTINUE_TRIES, typed: null })+ this.watches.delete(harnessId)+ }++ /** Each host roster read; one pass at a time. */+ tick(rows: unknown[]): Promise<void> {+ return this.running ??= this.pass(rows).catch(error => this.log(error instanceof Error ? error.message : String(error)))+ .finally(() => { this.running = null })+ }++ private async pass(rows: unknown[]): Promise<void> {+ /** The crew the roster names here; what is owed them is kept while it does, their terminal away for a moment or not+ * (review 2 of #3222). */+ const named = new Set<string>()+ const here = new Map<string, Record<string, unknown>>()+ for (const row of rows.map(object)) {+ const agent = object(row.agent)+ if (!identifier(agent.harnessId) || agent.machineId !== this.machineId || row.closeSession === true || row.stopRequested === true || !isCrewRow(row)) continue+ named.add(agent.harnessId)+ if (!this.core.agents.byAgent(agent.harnessId) || !this.core.agents.terminalAvailable(agent.harnessId)) continue+ here.set(agent.harnessId, row)+ }+ for (const id of this.watches.keys()) if (!here.has(id)) this.watches.delete(id)+ for (const id of this.owed.keys()) if (!named.has(id)) this.owed.delete(id)+ for (const harnessId of here.keys()) if (this.owed.has(harnessId)) await this.continueTask(harnessId)+ const now = this.now()+ if (now - this.lookedAt < CREW_LOOK_MS) return+ this.lookedAt = now+ const looked = [...here.keys()].filter(id => !this.owed.has(id))+ if (!looked.length) return+ const activity = await this.core.agents.activity(looked).catch(() => ({} as Record<string, string>))+ for (const harnessId of looked) await this.look(harnessId, activity[harnessId] === 'working', here.get(harnessId)!.confidential === true, now)+ }++ /** Types the owed continue: its text, then Enter only on the screen read after it (inputIfScreen, under the pane's write+ * lock), so a prompt that opened meanwhile never takes the Enter (reviews of #3222). A try that failed is tried again a+ * look later, CREW_CONTINUE_TRIES times at most. */+ private async continueTask(harnessId: string): Promise<void> {+ const owed = this.owed.get(harnessId)!, now = this.now()+ if (owed.at > now) return+ if (!await this.owns(harnessId)) return void this.owed.delete(harnessId)+ const again = (why: string) => {+ if (--owed.tries > 0) return void (owed.at = now + CREW_LOOK_MS)+ this.owed.delete(harnessId)+ this.log(`Gave up telling the reopened crew member ${harnessId.slice(0, 8)} to continue: ${why}.`)+ }+ const ready = async () => {+ const read = await this.core.superTabs?.screen(harnessId, 0).catch(() => null)+ return read?.ok && (read.hold === null || !WAITING.has(read.hold)) ? read.text : null+ }+ // A prompt or an unreadable screen waits, a look later, and costs no try.+ if (await ready() === null) return void (owed.at = now + CREW_LOOK_MS)+ // The screen its typing left is back (a prompt answered): only its Enter is owed.+ if (owed.typed !== null) {+ if ((await this.core.superTabs!.inputIfScreen(harnessId, ['Enter'], owed.typed)).ok) return void this.owed.delete(harnessId)+ owed.typed = null+ }+ const typed = await this.core.superTabs!.input(harnessId, CREW_CONTINUE, [])+ if (!typed.ok) return again(typed.error)+ const screen = await ready()+ if (screen === null) return void (owed.at = now + CREW_LOOK_MS)+ owed.typed = screen+ const entered = await this.core.superTabs!.inputIfScreen(harnessId, ['Enter'], screen)+ if (!entered.ok) return again(entered.error)+ this.owed.delete(harnessId)+ }++ private async look(harnessId: string, working: boolean, confidential: boolean, now: number): Promise<void> {+ const watch = this.watches.get(harnessId)+ // Idle at its prompt: its frozen time starts again from its next work.+ if (!working || !watch) return void this.watches.set(harnessId, { workingSince: now, ...watch?.said ? { said: watch.said } : {} })+ const still = this.stillSince(harnessId)+ if (still === undefined) return+ const frozenFor = now - Math.max(still, watch.workingSince)+ if (frozenFor < CREW_FROZEN_MS) return+ const spared = confidential ? 'its session is confidential: closing it would delete its data'+ : this.team() ? 'it runs in a Team account, where closing it deletes what reopening it needs' : null+ if (spared) {+ if (watch.said !== spared) this.log(`The crew member ${harnessId.slice(0, 8)} looks frozen, but ${spared}, so it is left as it is.`)+ watch.said = spared+ return+ }+ this.log(`The crew member ${harnessId.slice(0, 8)} froze: working with an unchanged screen for ${Math.round(frozenFor / 60_000)} minutes. Closing it to reopen it in place.`)+ this.watches.delete(harnessId)+ const closed = await this.core.agents.closeMember?.(harnessId)+ if (!closed || !('closed' in closed) || !closed.closed) this.log(`Could not close the frozen crew member ${harnessId.slice(0, 8)}: ${closed?.error ?? 'unsupported'}.`)+ }+}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 8e59623c7..9aa3410b1 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -33,6 +33,7 @@ import { ADDED_MAX } from './deliveryContext.js'import { SWITCH_ADOPT_MS, SWITCH_HOLD_MS } from './leadSwitch.js'import { TerminalHost } from './terminal.js'import { hostForm, swarmReply } from './fixtures/read/index.js'+import { CREW_CONTINUE } from './crew.js'import { CONTINUE } from './limitResume.js'import { HostFeed } from './hostFeed.js'import { SwarmReads } from './swarmReads.js'@@ -4563,6 +4564,57 @@ describe('ending a Buddy\'s thread sessions', () => {})})+// Task #3397: the host keeps a project's crew alive as it keeps the PM. A crashed crew session is reopened in place, on its own+// conversation, and told once to continue the task it still holds; an ordinary agent is left as before.+describe('keeping a crew member alive', () => {+ const crewRow = (agent: Record<string, unknown> = {}) => ({ tabId: 'tab', active: false,+ agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', crew: { role: 'Engineer', at: 1, by: 'pm' }, ...agent } })+ /** [t]'s host with its task `work` running in the session, and a screen and input the crew keeper reads and types into. */+ const withTask = (t: ReturnType<typeof lifeFixture>, rows: Record<string, unknown>[]) => {+ const typed: string[] = []+ t.core.account.backend = async (_method, path, body) => {+ if ((body as any)?.command) { t.commands.push(body as Record<string, unknown>); return { status: 200, body: { data: {} } } }+ if (path.includes('/hosts/')) return { status: 200, body: { data: hostForm(rows, { tabs: ['tab'], assignments: [{ tabId: 'tab', assignmentId: 'work', harnessId: 'harness' }] }) } }+ return { status: 200, body: { data: [] } }+ }+ let screen = '❯ '+ ;(t.core as any).superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),+ screen: vi.fn(async () => ({ ok: true as const, text: screen, hold: null })),+ input: vi.fn(async (_id: string, text: string) => { typed.push(text); screen = `❯ ${text}`; return { ok: true as const } }),+ inputIfScreen: vi.fn(async (_id: string, keys: string[], seen: string) => {+ if (seen !== screen) return { ok: false as const, error: 'SCREEN_CHANGED' }+ typed.push(keys.join(' ')); screen = '❯ '; return { ok: true as const }+ }) }+ return typed+ }++ it('reopens a crashed crew session in place and tells it once to continue its task', async () => {+ const rows = [crewRow()]+ const t = lifeFixture(rows)+ const typed = withTask(t, rows)+ t.keepLeadAlive.mockResolvedValue({ ok: true })+ await t.poll()+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')+ t.live(true)+ await t.poll(1_000)+ await t.poll(1_000)+ expect(typed).toEqual([CREW_CONTINUE, 'Enter'])+ await t.poll(2 * 60_000)+ expect(typed).toEqual([CREW_CONTINUE, 'Enter'])+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ })++ it('reopens no ordinary agent, nor a crew member asleep or moved', async () => {+ for (const row of [crewRow({ crew: undefined }), crewRow({ asleep: { since: 1 } }), crewRow({ movedTo: 'agent-2' })]) {+ const t = lifeFixture([row])+ withTask(t, [row])+ await t.poll()+ await t.poll(60_000)+ expect(t.keepLeadAlive).not.toHaveBeenCalled()+ }+ })+})+describe('keeping a Swarm Lead alive', () => {it('services a landed PM switch after the source is no longer marked as Lead', async () => {const t = lifeFixture([leadRow({ lead: false, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1',diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 1794fecbe..20908e1ed 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -25,6 +25,7 @@ import { RebindSender, replacementObservations } from './replacements.js'import { TerminalHost, type TerminalRelay } from './terminal.js'import { realRelayRecovery } from './relayRecovery.js'import { LimitResume } from './limitResume.js'+import { CrewKeeper, isCrewRow } from './crew.js'import { LeadSwitchRequests, type SwitchRow } from './leadSwitchRequest.js'import { BuddyModelRequests, type BuddyModelRow } from './buddyModel.js'import { openDaemon } from '../agentClient/daemon.js'@@ -608,6 +609,8 @@ export class SuperTabHost {private readonly terminal: TerminalHost/** Gives a task lost to a usage limit back to its session once the limit has reset. */private readonly limitResume: LimitResume+ /** Restarts a frozen crew session and continues a reopened one (crew.ts); the keep-alive below reopens it. */+ private readonly crew: CrewKeeperconstructor(private readonly core: CoreApi, readonly machineId: string, options: SuperTabHostOptions = {}) {if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')@@ -633,6 +636,9 @@ export class SuperTabHost {this.limitResume = new LimitResume(core, machineId, { now: this.now, log: this.log,owns: async (tabId, assignmentId, harnessId) => (await this.sources.feed.fresh()).assignments.some(a => a.tabId === tabId && a.assignmentId === assignmentId && a.harnessId === harnessId) })+ this.crew = new CrewKeeper(core, machineId, { now: this.now, log: this.log, team: isTeamDaemon,+ stillSince: harnessId => this.terminal.stillSince(harnessId),+ owns: async harnessId => (await this.sources.feed.fresh()).assignments.some(a => a.harnessId === harnessId) })this.rebinds = new RebindSender((path, body) => backend(this.core, 'POST', path, body), this.now)this.leadSwitches = new LeadSwitchRequests(core, machineId, { now: this.now, log: this.log, team: isTeamDaemon })// Over this machine's own daemon socket, which answers as the machine owner: the Buddy runs only on its owner's machine.@@ -1104,7 +1110,7 @@ export class SuperTabHost {this.joinTeams(data)this.cleanRemoved(data)// Off the poll: a screen read waits on the core, and never delays the input leases below.- if (this.core.superTabs) { void this.terminal.tick(data); void this.limitResume.tick(data) }+ if (this.core.superTabs) { void this.terminal.tick(data); void this.limitResume.tick(data); void this.crew.tick(data) }// Recovery can wait on a native receipt. Run it beside leases, so another worker's input// never expires while an old Change agent is being reconciled.if (!this.replacementsRunning && this.now() >= this.nextReplacementsAt) {@@ -1165,6 +1171,10 @@ export class SuperTabHost {if (row.lead === true) leads.add(target.agent.harnessId)this.keepAlive(target.agent.harnessId)void this.leadSwitches.serve(target as unknown as SwitchRow).catch(error => this.log(`PM switch: ${error instanceof Error ? error.name : typeof error}`))+ } else if (isCrewRow(row)) {+ // A project's crew is kept alive as its PM is (task #3397): reopened in place, then told to continue its task.+ leads.add(target.agent.harnessId)+ this.keepAlive(target.agent.harnessId, true)}// Never adopt another live session as a replacement for the recorded harness.if (!this.core.agents.byAgent(target.agent.harnessId) || !this.core.agents.terminalAvailable(target.agent.harnessId)) continue@@ -1321,7 +1331,7 @@ export class SuperTabHost {/** The owner, 2026-10-23: the Lead of an active project stays alive. One whose session is gone (a machine restart, a* kill) is reopened on its own conversation; nothing is typed into it, so no old input is replayed. A failure backs* off, so an engine that cannot start never spins. */- private keepAlive(harnessId: string): void {+ private keepAlive(harnessId: string, crew = false): void {const reopen = this.core.agents.keepLeadAliveif (!reopen) returnconst state = this.keepAlives.get(harnessId) ?? { running: false, failures: 0, retryAt: 0 }@@ -1345,7 +1355,7 @@ export class SuperTabHost {state.running = trueconst failed = (reason: string) => {state.retryAt = this.now() + Math.min(LEAD_RETRY_MAX_MS, LEAD_RETRY_MS * 2 ** state.failures++)- if (reason !== state.reason) this.log(`Could not reopen the Product Manager ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)+ if (reason !== state.reason) this.log(`Could not reopen the ${crew ? 'crew member' : 'Product Manager'} ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)state.reason = reason}void (async () => {@@ -1360,6 +1370,7 @@ export class SuperTabHost {}const result = await reopen(harnessId)if (!result.ok) return failed(result.detail ?? result.error)+ if (crew) this.crew.reopened(harnessId)state.failures = 0state.retryAt = this.now() + LEAD_REOPEN_WAIT_MSdelete state.reasondiff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.tsindex 90e05ff56..65d7ec4f7 100644--- a/cli/src/superTabs/inCore/agents.ts+++ b/cli/src/superTabs/inCore/agents.ts@@ -8,7 +8,7 @@ import type { SwarmAgentDeps, SwarmAgents } from '../../core/api.js'import { PURGE_RECORD_UNREADABLE } from './teamPurge.js'export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members, purgeEnded }: SwarmAgentDeps & {- /** The Leads and members this machine's Super Tab host keeps (superTabs/retention.ts). */+ /** The Leads and crew (`leads`) and members this machine's Super Tab host keeps (superTabs/retention.ts). */members: { leads(): Set<string>; harnesses(): Set<string> }/** On a Team daemon, deletes the session data of a confidential member the Swarm ended (inCore/teamApps.ts); absent elsewhere. */purgeEnded?: (agentId: string) => Promise<Record<string, unknown>>diff --git a/cli/src/superTabs/retention.spec.ts b/cli/src/superTabs/retention.spec.tsindex 028b9846f..4a3aae523 100644--- a/cli/src/superTabs/retention.spec.ts+++ b/cli/src/superTabs/retention.spec.ts@@ -183,3 +183,26 @@ it('retains a harness that holds an assignment, and for a minute after the hostretainContributions(dir, 'machine', [], now + 1000)expect([...retainedHarnesses(dir, now + 1000)]).toEqual(['heron'])})++// Task #3397: a crew member is kept in no open group as between tasks, never lapses, and is among the sessions the core may+// reopen; off the crew it is an ordinary member again on the next roster.+it('keeps a crew member with no open group, past the lapse, and names it among those the core reopens', () => {+ const dir = root(), now = Date.now(), file = retentionFile(dir)+ const crew = { crew: { role: 'Engineer', at: 1, by: 'pm' } }+ const crewRow = (harnessId: string, extra: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { harnessId, machineId: 'machine', ...crew }, ...extra })+ retainContributions(dir, 'machine', [crewRow('standing', { active: false }), row('idle', { active: false }), row('pm', { lead: true })], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['pm', 'standing'])+ expect([...retainedLeads(dir)].sort()).toEqual(['pm', 'standing'])+ expect(JSON.parse(readFileSync(file, 'utf8')).crew).toEqual(['standing'])+ const lapsed = new Date(now - RETENTION_LAPSE_MS - 60_000)+ utimesSync(file, lapsed, lapsed)+ expect([...retainedHarnesses(dir, now)].sort()).toEqual(['pm', 'standing'])+ // A crew mark is not a Lead's: a stop still reaches it (leadSwitch.ts mayBeLead).+ expect(mayBeLead(dir, 'standing')).toBe(false)+ // Security review 1 of #3222: one whose stop is asked for is no crew the core may reopen.+ retainContributions(dir, 'machine', [crewRow('standing', { stopRequested: true }), row('pm', { lead: true })], now)+ expect([...retainedLeads(dir)]).toEqual(['pm'])+ retainContributions(dir, 'machine', [row('standing', { active: false }), row('pm', { lead: true })], now)+ expect([...retainedHarnesses(dir, now)]).toEqual(['pm'])+ expect([...retainedLeads(dir)]).toEqual(['pm'])+})diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.tsindex 2270212fd..d69ad4c32 100644--- a/cli/src/superTabs/retention.ts+++ b/cli/src/superTabs/retention.ts@@ -8,6 +8,7 @@* discussion and running assignments continue. */import { existsSync, mkdirSync, readFileSync, renameSync, statSync, utimesSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'+import { isCrewRow } from './crew.js'import { identifier, object } from './wire.js'/** `leads`: the Leads of active projects here, which never lapse (owner, 2026-10-23: the Lead of an active project is never@@ -15,8 +16,10 @@ import { identifier, object } from './wire.js'* `buddies`: the Buddies here, which a close never stops (Diego, 10-30): only their person removing them, or the machine's* owner with Stop Harness. Absent in a file from before Buddies were kept, which names none until the next roster.* `assigned`: when the host first received each assignment its harnesses hold, epoch ms. Such a harness is in `harnesses`- * while it holds it and for ASSIGNED_GRACE_MS after it came, whatever its groups (task #2744). Absent in older files. */-interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[]; buddies?: string[]; assigned?: Record<string, number> }+ * while it holds it and for ASSIGNED_GRACE_MS after it came, whatever its groups (task #2744). Absent in older files.+ * `crew`: its project's crew here (crew.ts isCrewRow, task #3397), kept as Leads are: in no open group and past the lapse,+ * and reopened by the core when gone. Absent in older files. */+interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[]; crew?: string[]; buddies?: string[]; assigned?: Record<string, number> }export const retentionFile = (dataDir: string) => join(dataDir, 'super-tabs', 'retained.json')export const RETENTION_LAPSE_MS = 7 * 24 * 60 * 60_000const REFRESH_MS = 60 * 60_000@@ -30,6 +33,7 @@ function read(file: string): Retention {try { value = object(JSON.parse(readFileSync(file, 'utf8'))) } catch { /* reported below */ }if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)|| (value.leads !== undefined && (!Array.isArray(value.leads) || !value.leads.every(identifier)))+ || (value.crew !== undefined && (!Array.isArray(value.crew) || !value.crew.every(identifier)))|| (value.buddies !== undefined && (!Array.isArray(value.buddies) || !value.buddies.every(identifier)))|| (value.assigned !== undefined && !Object.entries(object(value.assigned)).every(([id, at]) => identifier(id) && Number.isFinite(at)))) {throw new Error('Super Tab retention is unreadable. Automatic cleanup is paused.')@@ -45,9 +49,10 @@ export function retainedHarnesses(dataDir: string, now = Date.now()): Set<stringreturn new Set(read(file).harnesses)}-/** The Leads here the host may reopen: only those a valid roster named. */+/** The sessions here the host may reopen, the Leads and the crew: only those a valid roster named. The core reads it as its+ * Leads (core/main.ts, inCore/agents.ts keepLeadAlive), so a crew member reopens exactly as a Lead does. */export function retainedLeads(dataDir: string): Set<string> {- try { return new Set(read(retentionFile(dataDir)).leads) } catch { return new Set() }+ try { const kept = read(retentionFile(dataDir)); return new Set([...kept.leads ?? [], ...kept.crew ?? []]) } catch { return new Set() }}/** Whether a stop may reach a Lead, for the core's guard, which fails closed (the review of #1635): with no file this@@ -83,7 +88,7 @@ export function retainContributions(dataDir: string, machineId: string, rows: un// file and another identity's entry. Unchanged rosters only refresh the lapse clock.let previous: Retention | null = nulltry { if (existsSync(file)) previous = read(file) } catch { /* rebuilt below */ }- const ids = new Set<string>(), leads = new Set<string>(), buddies = new Set<string>()+ const ids = new Set<string>(), leads = new Set<string>(), crew = new Set<string>(), buddies = new Set<string>()for (const item of rows) {const row = object(item), agent = object(row.agent)if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue@@ -97,6 +102,8 @@ export function retainContributions(dataDir: string, machineId: string, rows: un// agent's buddyOf, set when a person adds their Buddy); a row that ends it carries no agent record, so it is no Buddy.if (identifier(object(agent.buddyOf).personId)) buddies.add(agent.harnessId)if (row.lead === true) leads.add(agent.harnessId)+ // One whose stop is asked for is no crew the core may reopen (security review 1 of #3222).+ else if (isCrewRow(row) && row.stopRequested !== true) crew.add(agent.harnessId)else if (row.active === false && !buddies.has(agent.harnessId)) continueids.add(agent.harnessId)}@@ -108,7 +115,7 @@ export function retainContributions(dataDir: string, machineId: string, rows: un}for (const [id, at] of Object.entries(before)) if (!(id in assigned) && now - at < ASSIGNED_GRACE_MS) assigned[id] = atfor (const id of Object.keys(assigned)) ids.add(id)- const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort(), buddies: [...buddies].sort(),+ const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort(), ...(crew.size ? { crew: [...crew].sort() } : {}), buddies: [...buddies].sort(),assigned: Object.fromEntries(Object.entries(assigned).sort(([a], [b]) => a.localeCompare(b))) }if (previous && JSON.stringify(previous) === JSON.stringify(next)) {if (now - statSync(file).mtimeMs > REFRESH_MS) utimesSync(file, new Date(now), new Date(now))diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex c72a0bea6..5dd9fd3ad 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -389,11 +389,15 @@ it('asks for a task\'s priority on conversation.create, says what P0 to P3 mean,const answer = await t.ask({ action: 'help' }, owner) as { help: { command: string; mine: string; commands: Array<Record<string, unknown>> } }expect(answer.help.mine).toContain('one line per task, P0 first (number, priority, title,')const creates = answer.help.commands.filter(c => c.type === 'conversation.create')- expect(creates.find(c => !('step' in c))).toMatchObject({ title: 'Outcome', priority: 'P0|P1|P2|P3' })+ expect(creates.find(c => !('step' in c))).toMatchObject({ title: 'Outcome', priority: 'P0|P1|P2|P3', requesterId: 'PERSON' })// A step carries no priority.expect(creates.find(c => 'step' in c)).not.toHaveProperty('priority')expect(answer.help.commands).toContainEqual({ type: 'work.priority', conversationId: 'GROUP', priority: 'P0' })- expect(answer.help.command).toContain('A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create, or it gets P2; only the PM or a person sets P0, or changes a priority later with work.priority.')+ // Task #3389: an agent\'s task needs its goal, a check, a priority and who asked, or a reason nobody did.+ expect(answer.help.command).toContain('TASK_CONTRACT_MISSING')+ expect(answer.help.command).toContain('noRequesterReason')+ expect(answer.help.command).not.toContain('checks may be empty')+ expect(answer.help.command).toContain('A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create (a person\'s without one gets P2); only the PM or a person sets P0, or changes a priority later with work.priority.')})it('tells the Lead that start works only on a machine in the Swarm\'s Machines list', async () => {const t = setup()diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 34d5271fd..2d0ab7177 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -53,7 +53,7 @@ const MENTION_HELP = ' --mention tags a person, by the username, display name or/** What the command entry says after how its JSON is passed, the same for everyone. A task's review plan (#2382) is said in* its brief (backend superTabs/model.ts renderWorkTask), for whoever opens its review (project instructions, phase 4). */const COMMAND_ABOUT = 'send one of the commands below.'-const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns), and checks may be empty. A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create, or it gets P2; only the PM or a person sets P0, or changes a priority later with work.priority. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it. machine.projects keeps a machine for some projects (projectIds null: every project); the route leaves it out for the others: the machine\'s owner sets it, or the PM passing on the owner\'s chat message, with askedIn naming it.'+const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns). An agent\'s task (the PM\'s too) needs a goal, at least one check, a priority and requesterId, or the Swarm refuses it with TASK_CONTRACT_MISSING, naming what is missing; work no person asked for gives noRequesterReason (a few words on why) in place of requesterId, and it is shown in the task. A task\'s priority is P0 (hotfix: something shipped is broken, loses data, or stops people\'s or agents\' work), P1 (needed by users soon), P2 (planned goal) or P3 (tools, docs or process): give one on conversation.create (a person\'s without one gets P2); only the PM or a person sets P0, or changes a priority later with work.priority. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it. machine.projects keeps a machine for some projects (projectIds null: every project); the route leaves it out for the others: the machine\'s owner sets it, or the PM passing on the owner\'s chat message, with askedIn naming it.'/** A Buddy's guard refuses `command` itself and every JSON read from stdin, so its help never offers - and stdin there either* (a Buddy that follows a stdin form is refused and tries again, #2360); it quotes the JSON, as its usage hints do. */const BUDDY_COMMAND_HELP = `command OPERATION_ID JSON: ${COMMAND_ABOUT} The JSON is one argument, in single quotes: command OPERATION_ID '{...}' (an apostrophe inside it as \\u0027). ${COMMAND_RULES}`@@ -105,7 +105,7 @@ const HELP = {{ type: 'project.digest', projectId: 'PROJECT', time: '08:00', timeZone: 'Asia/Ho_Chi_Minh' },{ type: 'tab.tidy', enabled: false, askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },- { type: 'conversation.create', title: 'Outcome', priority: 'P0|P1|P2|P3', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'],+ { type: 'conversation.create', title: 'Outcome', priority: 'P0|P1|P2|P3', requesterId: 'PERSON', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'],review: { focus: 'Optional: what every review of it checks first, such as the most-likely-wrong list (up to 2,000 characters)', reviews: 2 } }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },// A step of a task (task steps design): its name is the one the project's instructions give.{ type: 'conversation.create', title: 'STEP_NAME', reviewOf: 'GROUP', step: 'STEP_NAME', task: { goal: 'What this step delivers for the task', changes: 'What it changes, or None', constraints: 'The task\'s constraints', owns: ['What it works on'] }, checks: [{ description: 'Its verdict, with evidence', independent: false }] },diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.tsindex a833a619a..bcba553cd 100644--- a/cli/src/superTabs/terminal.spec.ts+++ b/cli/src/superTabs/terminal.spec.ts@@ -503,6 +503,21 @@ describe('progress for the machine report', () => {expect(t.core.superTabs!.screen).toHaveBeenCalledTimes(3)})+ // Task #3397: a crew session whose whole screen, status line and timer too, never changes while its engine works is frozen+ // (crew.ts). The watch's own reads tell it, so the crew keeper reads no screen of its own.+ it('records when the whole screen last changed, its status line included, from the same reads', async () => {+ const t = setup({ screen: showing('✻ Working… (3s · esc to interrupt)\n❯ ') })+ await t.host.tick([row()])+ expect(t.host.stillSince('h1')).toBe(1_000_000)+ t.showing(showing('✻ Working… (18s · esc to interrupt)\n❯ ')); t.wait(15_000); await t.host.tick([row()])+ expect(t.host.progressOf(['h1'])).toEqual({ h1: 1_000_000 })+ expect(t.host.stillSince('h1')).toBe(1_015_000)+ t.wait(15_000); await t.host.tick([row()])+ expect(t.host.stillSince('h1')).toBe(1_015_000)+ expect(t.host.stillSince('h2')).toBeUndefined()+ expect(t.core.superTabs!.screen).toHaveBeenCalledTimes(3)+ })+it('names only running agents, and forgets one once it stops or leaves', async () => {const t = setup({ live: ['h1', 'h2'] })await t.host.tick([row(), row('a2', 'h2', { stopRequested: true }), row('a3', 'h3')])diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.tsindex 1366a75c8..9f97a9da3 100644--- a/cli/src/superTabs/terminal.ts+++ b/cli/src/superTabs/terminal.ts@@ -206,6 +206,8 @@ export class TerminalHost {private readonly alertRetries = new CommandRetries(() => this.now())/** Per running harness here, its last screen's digest and when that last changed. */private readonly progress = new Map<string, { digest: string; at: number }>()+ /** When each harness's whole screen, status lines too, last changed: one still while its engine works is frozen (crew.ts). */+ private readonly still = new Map<string, { digest: string; at: number }>()private readonly now: () => numberprivate readonly log: (message: string) => void/** Whether the server is known to push now (the host's delivery push lease). */@@ -225,7 +227,7 @@ export class TerminalHost {* the host never waits on it, so a slow screen read never delays deliveries. */tick(rows: unknown[]): Promise<void> {const here = this.here = this.agentsHere(rows)- if (!here.length) { this.watched.clear(); this.progress.clear(); return Promise.resolve() }+ if (!here.length) { this.watched.clear(); this.progress.clear(); this.still.clear(); return Promise.resolve() }const own = here.filter(agent => agent.running)const now = this.now()if (!this.serving && !this.pushes() && now - this.servedAt >= SERVE_EVERY_MS) this.startServing()@@ -255,6 +257,12 @@ export class TerminalHost {/** When each of these harnesses' screens last changed, epoch ms, for those running here that the watch has read. An* agent's first read counts as a change: the host cannot know what its screen showed before. */+ /** When [harnessId]'s whole screen last changed, status lines included, from the reads the watch already makes; undefined+ * for one it has not read. A working engine redraws its timer, so a screen that stays the same while it works is frozen. */+ stillSince(harnessId: string): number | undefined {+ return this.still.get(harnessId)?.at+ }+progressOf(harnessIds: readonly string[]): Record<string, number> {return Object.fromEntries(harnessIds.flatMap(id => {const seen = this.progress.get(id)@@ -322,6 +330,7 @@ export class TerminalHost {this.alertRetries.keepIf(key => agents.has(key.split('-')[2] ?? ''))const harnesses = new Set(own.map(a => a.harnessId))for (const id of this.progress.keys()) if (!harnesses.has(id)) this.progress.delete(id)+ for (const id of this.still.keys()) if (!harnesses.has(id)) this.still.delete(id)this.relay?.keep(harnesses)for (const agent of own) {const key = `${agent.tabId}:${agent.agentId}`@@ -336,6 +345,8 @@ export class TerminalHost {const failing = unanswered(read.text)// A model being retried is not the agent's work moving, whatever else the screen shows meanwhile.if (!seen || (seen.digest !== digest && !failing)) this.progress.set(agent.harnessId, { digest, at: now })+ const whole = createHash('sha256').update(read.text).digest('base64url')+ if (this.still.get(agent.harnessId)?.digest !== whole) this.still.set(agent.harnessId, { digest: whole, at: now })state.prompt = await this.episode(agent, 'prompt', state.prompt, read.hold !== null && WAITING.has(read.hold), now, since => now - since >= PROMPT_WAIT_MS, {})const limit = limitOf(read.text, now)state.limit = await this.episode(agent, 'limit', state.limit, limit !== null, now, () => true, limit ?? {})diff --git a/desktop/lib/super_tabs/crew_panel.dart b/desktop/lib/super_tabs/crew_panel.dartnew file mode 100644index 000000000..26ffe1c11--- /dev/null+++ b/desktop/lib/super_tabs/crew_panel.dart@@ -0,0 +1,140 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'detail_dialog.dart';+import 'dialog_scope.dart';+import 'model.dart';++/// How long a crew member's session may be gone while its machine reopens it, as the server keeps its task for (backend+/// crew.ts `CREW_REOPEN_GRACE_MS`): shown as Reopening, then Down.+const superTabCrewReopenGrace = Duration(minutes: 5);++/// What the panel says when the project has no crew.+const superTabCrewEmpty = 'No crew yet. The PM adds crew in this project.';++/// The statuses of a task its agent still holds (backend model.ts `activeWork`).+const _open = {'working', 'review', 'needs_human', 'blocked', 'reconciling'};++/// One crew member as the panel shows it (task #3397).+class SuperTabCrewRow {+ const SuperTabCrewRow({+ required this.name,+ required this.role,+ required this.machine,+ required this.state,+ required this.task,+ });++ final String name, role, machine, state, task;+}++String _engine(Object? engine) => switch (engine) {+ 'claude' => 'Claude',+ 'codex' => 'Codex',+ final String other when other.isNotEmpty =>+ '${other[0].toUpperCase()}${other.substring(1)}',+ _ => '',+};++/// The crew of [projectId] in [swarm], in the order the Swarm lists its agents: each one's name, role (and lane), machine+/// and engine, state and the open task it holds.+List<SuperTabCrewRow> superTabCrewRows(+ SuperTabSnapshot swarm,+ String projectId, {+ DateTime? now,+}) {+ final at = now ?? DateTime.now();+ return [+ for (final agent in swarm.teamAgents)+ if (agent.crewRole != null && agent.projectId == projectId)+ SuperTabCrewRow(+ name: agent.displayName ?? agent.name,+ role: [agent.crewRole!, ?agent.crewLane].join(' · '),+ machine: [+ swarm.pool(agent.machineId)?['name'] as String? ?? agent.machineId,+ _engine(agent.configuration['engine']),+ ].where((part) => part.isNotEmpty).join(' · '),+ state: switch (agent.downSince) {+ _ when agent.crewAsleep => 'Asleep',+ null => 'Running',+ final DateTime since when at.difference(since) < superTabCrewReopenGrace =>+ 'Reopening',+ final DateTime since => 'Down ${at.difference(since).inMinutes}m',+ },+ task: switch (swarm.conversations+ .where(+ (c) =>+ c.assignment?['agentId'] == agent.id &&+ _open.contains(c.assignment?['status']),+ )+ .firstOrNull) {+ null => 'No task',+ final SuperTabConversation c =>+ [if (c.number != null) '#${c.number}', c.title].join(' '),+ },+ ),+ ];+}++/// The crew list: a row per member, or one line when there is none.+class SuperTabCrewList extends StatelessWidget {+ const SuperTabCrewList({super.key, required this.rows});++ final List<SuperTabCrewRow> rows;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ if (rows.isEmpty) {+ return Text(superTabCrewEmpty, style: DesktopChrome.metadata());+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final (index, row) in rows.indexed)+ SuperTabDetailSection(+ title: row.name,+ first: index == 0,+ trailing: Text(row.state, style: DesktopChrome.metadata()),+ children: [+ SuperTabDetailRow(label: 'Role', value: row.role),+ SuperTabDetailRow(label: 'Machine', value: row.machine),+ SuperTabDetailRow(label: 'Task', value: row.task),+ ],+ ),+ ],+ );+ }+}++/// The project's crew in the Swarm's details frame: the agents the Swarm keeps running, which a crash or a frozen screen+/// reopens with their task and idle never closes (task #3397).+Future<void> showSuperTabCrew(+ BuildContext context,+ SuperTabController c,+ String projectId,+) => showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ projectId: projectId,+ requireWrite: false,+ child: ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final swarm = c.snapshot;+ return SuperTabDetailDialog(+ title: 'Crew',+ detail:+ 'Agents the Swarm keeps running. A crashed or frozen session reopens with its task, and idle never closes them.',+ body: SuperTabCrewList(+ rows: swarm == null ? const [] : superTabCrewRows(swarm, projectId),+ ),+ );+ },+ ),+ ),+);diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 5c76d65a1..46b13aaed 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -199,6 +199,15 @@ class SuperTabAgent {avatar = SuperTabAvatarPicture.fromJson(row['avatar']),downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),workDecision = row['workDecision'] as String?,+ crewRole = switch (row['crew']) {+ {'role': final String role} when role.isNotEmpty => role,+ _ => null,+ },+ crewLane = switch (row['crew']) {+ {'lane': final String lane} => lane,+ _ => null,+ },+ crewAsleep = row['asleep'] != null,confidential = row['confidential'] == true,configuration = Map.unmodifiable(superTabMap(row['configuration']));final String id, projectId, name, machineId, harnessId, contributorId;@@ -238,6 +247,15 @@ class SuperTabAgent {/// What its coordinator or a person chose for it once its work ended: `keep` or `stop`; `awaiting` while nobody has.final String? workDecision;+ /// Its role in its project's crew, the agents the Swarm keeps alive (backend crew.ts, task #3397); null when not crew.+ final String? crewRole;++ /// The lane a crew member works in (backend, cli, desktop, mobile or docs); null for none.+ final String? crewLane;++ /// A crew member put to sleep on purpose (task #3398): its session is closed and nothing reopens it.+ final bool crewAsleep;+/// Its session is closed on its machine and someone chose to keep the agent: the backend removes every other closed/// agent from the list (backend closedAgents.ts), so this one is shown as closed, never as Idle.bool get keptClosed => workDecision == 'keep' && downSince != null;diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 5cc542e2c..ba091b41b 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -57,6 +57,7 @@ import 'controller.dart';import 'file_links.dart';import 'dialog_scope.dart';import 'folder_zip.dart';+import 'crew_panel.dart';import 'instructions_panel.dart';import 'model.dart';import 'agent_details.dart';@@ -1792,6 +1793,11 @@ class _SuperTabViewState extends State<SuperTabView>}return;}+ if (action == 'crew') {+ final project = c.snapshot?.projectFor(group.id);+ if (project != null) await showSuperTabCrew(context, c, project.id);+ return;+ }if (action == 'switch-pm') {final project = c.snapshot?.projectFor(group.id);if (project != null) await showSwitchPm(context, c, project.id);@@ -3798,6 +3804,8 @@ class _SuperTabViewState extends State<SuperTabView>// them sends no coordinatorName.if (project.hasInstructions)item('Instructions', () => _groupAction('instructions', group)),+ // The crew the Swarm keeps alive (task #3397): every member reads it.+ item('Crew', () => _groupAction('crew', group)),if (editable && owner)item('Sharing', () => _groupAction('sharing', group)),_notifyMenu(group),diff --git a/desktop/test/super_tab_crew_panel_test.dart b/desktop/test/super_tab_crew_panel_test.dartnew file mode 100644index 000000000..12ccb8f15--- /dev/null+++ b/desktop/test/super_tab_crew_panel_test.dart@@ -0,0 +1,121 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/crew_panel.dart';+import 'package:harness/super_tabs/model.dart';++// Task #3397: the Crew panel lists a project's crew, the agents the Swarm keeps alive: each one's name, role, machine,+// state and task. Built from the snapshot alone, so no sign-in or store is needed (memory only).++final _now = DateTime.utc(2026, 11, 5, 15);++Map<String, dynamic> _agent(+ String id,+ String name, {+ Map<String, dynamic>? crew,+ String machineId = 'mac3',+ String engine = 'claude',+ DateTime? downSince,+ Map<String, dynamic>? asleep,+}) => {+ 'id': id,+ 'projectId': 'lead',+ 'name': name,+ 'machineId': machineId,+ 'harnessId': 'h-$id',+ 'contributorId': 'owner',+ 'configuration': {'engine': engine},+ 'crew': ?crew,+ 'downSince': ?downSince?.toIso8601String(),+ 'asleep': ?asleep,+};++SuperTabSnapshot _swarm(List<Map<String, dynamic>> agents) =>+ SuperTabSnapshot.fromJson({+ 'version': 1,+ 'id': 'tab',+ 'name': 'Pilot',+ 'ownerId': 'owner',+ 'people': const [],+ 'invitations': const [],+ 'agents': agents,+ 'machines': [+ {'machineId': 'mac3', 'name': 'Mac 3'},+ {'machineId': 'tim', 'name': 'Window of Tim'},+ ],+ 'conversations': [+ {+ 'id': 'lead',+ 'title': 'Lead',+ 'agentIds': const [],+ 'brief': 'Do it.',+ 'checks': const [],+ 'archived': false,+ },+ {+ 'id': 'g1',+ 'title': 'A standing crew',+ 'number': 3397,+ 'agentIds': ['keeper'],+ 'brief': 'Do it.',+ 'checks': const [],+ 'archived': false,+ 'assignment': {'id': 'w1', 'agentId': 'keeper', 'status': 'working'},+ },+ {+ 'id': 'g2',+ 'title': 'Finished work',+ 'number': 3300,+ 'agentIds': ['heron'],+ 'brief': 'Do it.',+ 'checks': const [],+ 'archived': false,+ 'assignment': {'id': 'w2', 'agentId': 'heron', 'status': 'done'},+ },+ ],+ });++const _engineer = {'role': 'Engineer', 'at': 1, 'by': 'pm'};++void main() {+ test('lists each crew member with name, role, machine, state and task, and nobody else', () {+ final rows = superTabCrewRows(+ _swarm([+ _agent('keeper', 'Keeper', crew: {..._engineer, 'lane': 'cli'}),+ _agent('heron', 'Heron', crew: {'role': 'Reviewer', 'at': 1, 'by': 'pm'}),+ _agent(+ 'sorrel',+ 'Sorrel',+ crew: {'role': 'Tester', 'at': 1, 'by': 'pm'},+ machineId: 'tim',+ engine: 'codex',+ downSince: _now.subtract(const Duration(minutes: 2)),+ ),+ _agent('aster', 'Aster', crew: _engineer, downSince: _now.subtract(const Duration(minutes: 6))),+ _agent('dozy', 'Dozy', crew: _engineer, asleep: {'since': 1}),+ _agent('plain', 'Plain'),+ ]),+ 'lead',+ now: _now,+ );+ expect(rows.map((r) => r.name), ['Keeper', 'Heron', 'Sorrel', 'Aster', 'Dozy']);+ expect(rows.first.role, 'Engineer · cli');+ expect(rows.first.machine, 'Mac 3 · Claude');+ expect(rows.first.state, 'Running');+ expect(rows.first.task, '#3397 A standing crew');+ expect(rows[1].task, 'No task');+ expect(rows[2].machine, 'Window of Tim · Codex');+ expect(rows[2].state, 'Reopening');+ expect(rows[3].state, 'Down 6m');+ expect(rows[4].state, 'Asleep');+ });++ testWidgets('shows the rows, and an empty line when the project has no crew', (tester) async {+ final rows = superTabCrewRows(_swarm([_agent('keeper', 'Keeper', crew: _engineer)]), 'lead', now: _now);+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabCrewList(rows: rows))));+ for (final text in ['Keeper', 'Engineer', 'Mac 3 · Claude', 'Running', '#3397 A standing crew']) {+ expect(find.text(text), findsOneWidget);+ }+ await tester.pumpWidget(const MaterialApp(home: Scaffold(body: SuperTabCrewList(rows: []))));+ expect(find.text(superTabCrewEmpty), findsOneWidget);+ });+}diff --git a/docs/plans/2026-11-05-ack-only-posts-plan.md b/docs/plans/2026-11-05-ack-only-posts-plan.mdnew file mode 100644index 000000000..97a067cfd--- /dev/null+++ b/docs/plans/2026-11-05-ack-only-posts-plan.md@@ -0,0 +1,53 @@+# An agent's post that only acknowledges is refused; a reaction settles it instead (task #3391) Plan++> Worked by the Engineer, test first (superpowers test-driven-development): each task's failing test is committed and+> seen red before the code that passes it.++**Goal:** An agent's post that says nothing beyond "on it", "got it", "thanks" or "will do" is refused with `ACK_ONLY`+and the next step (react instead). An agent's reaction to a message it was sent settles its delivery of that message,+as an answer does. People are never refused.++**Architecture:** A new `backend/src/superTabs/acknowledgements.ts` holds `isAcknowledgement(text)`: the text, lower-cased+and cut into clauses at punctuation, is an acknowledgement only when every clause is on the ack list, at least one is a+real acknowledgement (not just "ok"), and the text has no question mark, digit, link or tag. `commands.ts` `message.send`+refuses an agent's such post (no files, no tags, not a note to itself, not in a Buddy chat) with `ACK_ONLY`. `message.react`+in `commands.ts` records `effects.settles` for an agent's reaction that is on; `store.ts` closes that agent's own open+deliveries of the message as `answered`, with the same update a reply uses (shared helper, one place).++**Tech Stack:** TypeScript, vitest (unit), vitest with a Mongo replica set (`npm run test:super-tabs`).++**Spec:** task #3391 brief; project instructions ("Never post an acknowledgement ... react instead").++## Global Constraints++- Owned files: `backend/src/superTabs/` (and `backend/integration/superTabs.test.ts` for the store test, this plan).+- `ACK_ONLY` is a new name; none of the codes in `removedRefusals.test.ts` returns. The classifier errs toward letting a+ post through: anything not wholly on the list passes.+- No schema change, no numeric threshold: the list is the whole rule, so no length constant either.+- A reaction by a person settles nothing (people have no deliveries to settle); only the recipient agent's own rows move.++## Review Focus++- A real short answer ("Yes at 1a2b3c", "Done: PR #12", a link, a question) is never refused.+- The reaction settles only the reacting agent's deliveries of that message, in the open states a reply settles.++## Task 1: The classifier and the refusal++**Files:** `backend/src/superTabs/acknowledgements.ts`, `acknowledgements.test.ts`, `commands.ts`, `commands.test.ts`+**Interfaces:** `isAcknowledgement(text: string): boolean`++- [ ] Failing test: `isAcknowledgement` is true for "on it", "Got it, thanks!", "Will do." and false for "Yes at 1a2b3c", a+ link, "on it?", "on it #12", "thanks, merged", "ok".+- [ ] Failing test: an agent's `message.send` of "on it" throws `ACK_ONLY`; the same text from a person, with a file, with a+ tag, as a note to itself or in a Buddy chat passes; "Yes at 1a2b3c" passes.+- [ ] Implement the classifier and the refusal; both tests pass.++## Task 2: A reaction settles the delivery++**Files:** `backend/src/superTabs/commands.ts`, `store.ts`, `reactions.test.ts`, `backend/integration/superTabs.test.ts`+**Interfaces:** `effects.settles?: { messageId: string; agentId: string }`++- [ ] Failing test: an agent's `message.react` (on) returns `settles`; a person's, or an agent removing its reaction, does not.+- [ ] Failing integration test: an agent's 👀 on a message closes its own queued and claimed delivery of it as `answered`+ and not another agent's.+- [ ] Implement `settles` and the store update (shared with the reply path); both tests pass.diff --git a/docs/plans/2026-11-05-standing-crew-plan.md b/docs/plans/2026-11-05-standing-crew-plan.mdnew file mode 100644index 000000000..80ffd4ffb--- /dev/null+++ b/docs/plans/2026-11-05-standing-crew-plan.md@@ -0,0 +1,129 @@+# A standing crew Implementation Plan++> Implemented by the task's Engineer, test first, task by task (project instructions: Engineer). No Execution Handoff.++**Goal:** A project names agents as its crew (role, machine, engine). The Swarm keeps each one alive: a crashed or+frozen session is reopened in place with its task, and no idle path (the CLI's 30-minute idle close, the server's idle+notice, the server's removal of closed agents) closes or removes a crew member. A Crew panel lists each member's+name, role, machine, state and task.++**Architecture:** The backend stores `crew` on the agent record (`crew.add` / `crew.remove`, by the project's PM or a+person of the project). The record already reaches every reader and each machine's host, so status shows it and the+host reads it from its roster row. The host keeps crew rows alive with the same keep-alive the PM has (reopen a gone+session in place), adds a frozen-screen restart for crew, and writes crew into its retention file, which the CLI's idle+cleanup and the core's reopen guard read. The backend gives a crashed crew member's task a short grace, so its reopened+session still holds it, and the host types one continue line into the reopened session. Desktop adds a Crew panel.++**Tech Stack:** TypeScript (backend: vitest; CLI: vitest), Flutter (desktop: flutter_test).++**Spec:** Task #3397 (anh Dee, Swarm redesign approved 11-05). Constants live in one place per component+(`backend/src/superTabs/crew.ts`, `cli/src/superTabs/crew.ts`) until the project rules record (sibling task) lands.++## Global Constraints++- Owns only `backend/src/superTabs/`, `cli/src/superTabs/`, `cli/src/services/agentCleanup.ts`, `desktop/lib/super_tabs/`.+ Swarm code stays out of `cli/src/core` (no change to `core/api.ts` or `core/main.ts`).+- Lifecycle code is tested with a fake host and fake core; no test signs the Mac out of the real CLI; never two PMs.+- Non-crew behaviour is unchanged, and each test file pins that next to the crew case.+- PR body first line: "Requested by dee through Harness." One review and one security review.++## Design++- **Growth:** one small object per crew agent (`{ role, at, by }`), deleted by `crew.remove` or with the agent.+- **Concurrency:** `crew.add`/`crew.remove` write the agent's own part (the command names `agentId`, parts/touches.ts D3)+ and read the project's Lead conversation for the PM check (`leadCheck`), as `agent.release` does.+- **Read cost:** no new read; the field rides the agent part and the host roster row already sent.+- **Scale:** crew is a handful per project. At 10x the cost is one screen read a minute per crew member on its host;+ the host log line "reopened crew" rate warns first.+- **Compatibility:** an older client ignores the field. An older host ignores `crew` and treats the agent as today+ (closed when idle); a newer host on an older server sees no `crew` and changes nothing.+- **Migration + rollback:** none; an absent field is "not crew". Rollback leaves a harmless field.+- **Audience:** the server enforces who may mark crew (the project's PM, or a non-viewer person who reads the project).+- **Identity:** the actor is the command's own (person or agent); never the machine owner's login.+- **Failure:** a reopen or restart that fails backs off and is logged once per reason; a frozen confidential session on+ a Team account is not restarted (closing one deletes its data) and the log says so.+- **Platforms:** host code is platform-neutral (core close/resume); the panel is the shared Desktop UI.++## Review Focus++- A crew member that is also the PM: refused by `crew.add` (the PM is already kept alive), so it never has two paths.+- A frozen check must never restart a session that is only waiting at its prompt or running a long silent command:+ frozen means the engine says it is working and the whole screen, status line included, did not change for 30 min.+- A crew member's task is kept only for the reopen grace (5 min); a session that stays gone still loses it as today.+- A crew member removed from the crew goes back to normal idle handling at once (retention rewritten on next roster).+- A person who cannot read the project, or a viewer, cannot add or remove crew; the refusal names no hidden agent.++---++### Task 1: Backend crew flag and commands++**Files:**+- Create: `backend/src/superTabs/crew.ts`, `backend/src/superTabs/crew.test.ts`+- Modify: `backend/src/superTabs/model.ts` (Agent `crew?`), `backend/src/superTabs/commands.ts` (schema, WORDS, switch)++**Interfaces:**+- Produces: `Agent.crew?: { role: string; at: number; by: string }`; commands+ `{ type: 'crew.add', agentId, role? }` (role defaults to the agent's role name, 1 to 40 characters) and+ `{ type: 'crew.remove', agentId }`; `isCrew(agent): boolean` and `CREW_REOPEN_GRACE_MS = 5 * 60_000` in `crew.ts`.++- [ ] Failing tests in `crew.test.ts`: the PM adds and removes a crew member; a project person adds one; a viewer,+ another project's agent and a non-PM agent are refused (`FORBIDDEN`); the PM itself and a Buddy are refused+ (`CREW_LEAD`, `CREW_BUDDY`); the role defaults to the agent's role name; status (the agent part) carries `crew`.+- [ ] Implement `addCrew`/`removeCrew` in `crew.ts`, wire them in `commands.ts`.+- [ ] Commit test, then code.++### Task 2: Backend idle and removal paths skip crew, crashed crew keeps its task briefly++**Files:**+- Modify: `backend/src/superTabs/tidy.ts` (`idleNotices`), `backend/src/superTabs/closedAgents.ts` (`removable`),+ `backend/src/superTabs/liveness.ts` (`lostReason`)+- Test: `backend/src/superTabs/tidy.test.ts`, `closedAgents.test.ts`, `liveness.test.ts`++- [ ] Failing tests: no idle notice for a crew member (one for the same agent without crew); `closedAgents` never+ returns a crew member (returns the same agent without crew); a crew worker whose session is listed stopped keeps its+ task until `CREW_REOPEN_GRACE_MS` after `downSince`, then loses it; a non-crew worker loses it at once.+- [ ] Implement; commit test, then code.++### Task 3: CLI retention keeps crew++**Files:**+- Create: `cli/src/superTabs/crew.ts` (constants, `isCrewRow`)+- Modify: `cli/src/superTabs/retention.ts`+- Test: `cli/src/superTabs/retention.spec.ts`, `cli/src/services/agentCleanup.spec.ts`++**Interfaces:**+- Produces: retention file `crew?: string[]`; crew harnesses are always in `harnesses` (also with no open group) and+ never lapse; `retainedLeads(dataDir)` returns Leads and crew (the sessions the core may reopen, read by+ `core/main.ts` unchanged). `isCrewRow(row): boolean` (row.agent.crew has a role).++- [ ] Failing tests: a crew row in no active group is retained; after the lapse a crew harness is still retained;+ `retainedLeads` names crew; the idle cleanup never closes a crew member that sat idle 31 minutes, and still closes+ the same harness without crew.+- [ ] Implement; commit test, then code.++### Task 4: CLI host keeps crew alive, restarts a frozen one, continues its task++**Files:**+- Modify: `cli/src/superTabs/crew.ts` (`CrewKeeper`), `cli/src/superTabs/host.ts` (keep-alive for crew rows, tick)+- Test: `cli/src/superTabs/crew.spec.ts`, `cli/src/superTabs/host.spec.ts`++**Interfaces:**+- `CREW_FROZEN_MS = 30 * 60_000`, `CREW_LOOK_MS = 60_000`, `CREW_CONTINUE` (the line typed after a reopen).+- `new CrewKeeper(core, { now, log, owns })`, `tick(rows)`, `reopened(harnessId)`.++- [ ] Failing tests (fake core): a crew row whose session is gone is reopened through `keepLeadAlive`; a non-crew row+ is not; after the reopen the continue line is typed once, only while the session holds its assignment and no prompt+ waits; a crew session working with an unchanged screen for 30 min is closed (`closeMember`) and then reopened; one+ idle at its prompt, or whose screen changes, is not; a confidential one is not restarted.+- [ ] Implement; commit test, then code.++### Task 5: Desktop Crew panel++**Files:**+- Create: `desktop/lib/super_tabs/crew_panel.dart`, `desktop/test/super_tab_crew_panel_test.dart`+- Modify: `desktop/lib/super_tabs/model.dart` (`SuperTabAgent.crew`), `desktop/lib/super_tabs/view.dart` (menu item)++- [ ] Mockup posted in the task first.+- [ ] Failing widget test (memory store, fake sign-in): the panel lists each crew member with name, role, machine,+ state (Running, Reopening, Down) and task title, or "No task"; no crew shows the empty line; non-crew agents are absent.+- [ ] Implement; commit test, then code.diff --git a/docs/plans/2026-11-05-task-contract-plan.md b/docs/plans/2026-11-05-task-contract-plan.mdnew file mode 100644index 000000000..1f50ce515--- /dev/null+++ b/docs/plans/2026-11-05-task-contract-plan.md@@ -0,0 +1,49 @@+# Task Contract Implementation Plan++> Implement task by task, test first, following the project's Engineer workflow (project instructions, Engineer).++**Goal:** A task an agent opens (the PM included) says its goal, how to tell it is done (at least one check), its priority and who asked. Without them the server refuses with `TASK_CONTRACT_MISSING`, naming the missing fields and an example. People keep today's defaults.++**Architecture:** One new pure module `backend/src/superTabs/taskContract.ts` (the fields, the message, the example). `conversation.create` in `commands.ts` calls it for an agent author after the requester is resolved, before the group number is taken. Nothing else changes for people, steps (`reviewOf`/`step`) and private chats (`audience`).++**Tech Stack:** Backend TypeScript (zod commands, Vitest).++**Spec:** Swarm task #3389 brief (Dee's Swarm redesign, 2026-11-05): code over prompts; refuse only at named guards, each refusal naming the next step; #2414's removed refusals stay removed.++## Global Constraints++- The code is new: `TASK_CONTRACT_MISSING` (status 400). No code from `removedRefusals.test.ts` returns.+- Only agent authors are checked. A person's create is unchanged (priority defaults to P2 with the existing warning).+- A step (`reviewOf` or `step`) and a private chat (`audience`) are no task of their own and are not checked.+- A field a Buddy's proposal supplies counts as given: its brief (goal), its priority, its person (requester).+- The warning `REQUESTER_UNKNOWN` can no longer happen for an agent, so it goes with its dead branch.+- Swarm code stays out of cli/src/core. Desktop tests use a memory store and a fake sign-in.++## Design++- growth: N/A because it stores nothing.+- concurrency: N/A because it runs inside the existing per-Swarm command transaction before anything is written.+- read cost: N/A because it reads only the command and the requester already resolved.+- scale: N/A because it is a constant-time check per create.+- compatibility: old clients and CLIs that send a create without the fields now get a 400 naming them with an example; every field already exists on the command. People's clients are unaffected.+- migration + rollback: no migration; rolling back removes the refusal.+- audience: the server enforces it, by actor kind.+- identity: N/A because it uses the command's actor, never the machine owner's login.+- failure: the refusal names every missing field at once and the next step.+- platforms: backend only.++## Review Focus++- Every way an agent can open a task still works when it gives all four (task form or brief form, requesterId, a proposal, a request message).+- A step, a private chat and a person's create are never refused.++## Task 1: the check++**Files:** Create `backend/src/superTabs/taskContract.ts`, `backend/src/superTabs/taskContract.test.ts`; modify `backend/src/superTabs/commands.ts`.++**Interfaces:** `missingContract(given: { goal: boolean; checks: number; priority: boolean; requester: boolean }): ContractField[]`; `contractRefusal(missing): string`.++- [ ] Write the failing tests: an agent's create missing each field (alone and together) is refused naming them; a person's with defaults opens; steps, private chats, proposals and request messages are not refused.+- [ ] Watch them fail.+- [ ] Add the module and call it in `conversation.create`.+- [ ] Update the tests of the replaced `REQUESTER_UNKNOWN` warning; run the tests of what changed, then `npm test`.diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex b8b83a98b..8fa36ee4f 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -203,6 +203,15 @@ class SuperTabAgent {decision,_ => null,},+ crewRole = switch (row['crew']) {+ {'role': final String role} when role.isNotEmpty => role,+ _ => null,+ },+ crewLane = switch (row['crew']) {+ {'lane': final String lane} => lane,+ _ => null,+ },+ crewAsleep = row['asleep'] != null,confidential = row['confidential'] == true,configuration = Map.unmodifiable(superTabMap(row['configuration']));@@ -257,6 +266,16 @@ class SuperTabAgent {static const _workDecisions = {'awaiting', 'keep', 'stop'};+ /// Its role in its project's crew, the agents the Swarm keeps alive (backend crew.ts, task #3397), as the desktop's model+ /// reads it; null when not crew.+ final String? crewRole;++ /// The lane a crew member works in (backend, cli, desktop, mobile or docs); null for none.+ final String? crewLane;++ /// A crew member put to sleep on purpose (task #3398): its session is closed and nothing reopens it.+ final bool crewAsleep;+/// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.final String machineOwnerId;