Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Keep proposals and PM decisions on their cards (#3387)

harness-for-autonomous[bot]50f5248782f5
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index 33da42364..7c996280f 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -483,6 +483,30 @@ describe('a Buddy through the store', () => {
await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: '', replyTo: null, recipientIds: [], attachmentIds: [loose] }, peer, agentId))
.rejects.toThrow('Attach this file again')
})
+ it('persists approved files on a proposal card for the PM to open after the switch', async () => {
+ const f = await swarm()
+ const { chat, agentId } = await buddy(f)
+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })
+ const upload = async (name: string, asBuddy: boolean) =>
+ (await f.store.upload(peer, f.tab, chat, { name, mime: 'text/plain', body: Readable.from([Buffer.from(name)]) }, asBuddy ? agentId : undefined)).attachment.id
+ const plan = await upload('plan.txt', true), log = await upload('sync.log', false)
+ await f.execute({ type: 'message.send', conversationId: chat, text: 'Here is my log', replyTo: null, recipientIds: [], attachmentIds: [log] }, peer)
+ const ask = async () => String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Send these files to the PM', replyTo: null, recipientIds: [] }, peer)).result.messageId)
+ const propose = async (attachmentIds: string[]) => f.execute({ type: 'buddy.propose', conversationId: chat,
+ ownerMessageId: await ask(), text: 'Send these files to the PM', goal: 'Offline sync', scope: 'Desktop only', priority: 'normal',
+ why: 'Drafts disappear', doneWhen: 'Drafts return', evidence: ['Network-off reproduction'], attachmentIds }, peer, agentId)
+ const sent = await propose([plan, log]), cardId = String(sent.result.conversationId)
+ const read = (await f.store.messages(owner, f.tab, cardId, {}, f.lead)).messages.find(m => (m.source as { kind?: string })?.kind === 'proposal-card')!
+ expect(read.attachments?.map(a => a.name)).toEqual(['plan.txt', 'sync.log'])
+ expect(read.attachments!.map(a => f.files.open(a.link!)?.toString())).toEqual(['plan.txt', 'sync.log'])
+ expect(sent.result.messageId).toBe(read.id)
+ const card = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: cardId } } })
+ expect(card.data).toHaveProperty('proposal.scope', 'Desktop only')
+ expect(await db.superTabAttachment.findUniqueOrThrow({ where: { id: plan } })).toHaveProperty('usedBy', read.id)
+ await expect(propose([plan])).rejects.toThrow('Upload this file again')
+ await expect(propose([log])).rejects.toThrow('already went with a proposal')
+ })
+
it('never carries a file the expiry sweep took, its owner\'s or its own (Diego, 10-30)', async () => {
const f = await swarm()
const { chat, agentId } = await buddy(f)
diff --git a/backend/integration/superTabProposalCards.test.ts b/backend/integration/superTabProposalCards.test.ts
new file mode 100644
index 000000000..73b687426
--- /dev/null
+++ b/backend/integration/superTabProposalCards.test.ts
@@ -0,0 +1,214 @@
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { commandSchema } from '../src/superTabs/commands.js'
+import type { Conversation } from '../src/superTabs/model.js'
+import { SwarmReads } from '../src/superTabs/read/service.js'
+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'
+import { runTimeCheckPass } from '../src/superTabs/timeChecks.js'
+import { planDatabase, profiled, reads, plan } from './plans.test-support.js'
+
+let replica: MongoMemoryReplSet, db: PrismaClient
+const owner: AuthUser = { sub: '540000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const peer: AuthUser = { sub: '540000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'codex', model: 'fixture', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const DAY = 86_400_000
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('proposal_cards'))
+ await listNamedIndexes(db)
+ for (const u of [owner, peer]) await db.user.create({ data: { id: u.sub, externalId: `fixture-${u.sub}`, email: u.email, autonomousEnv: 'prod' } })
+ await db.machine.create({ data: { machineId: 'proposal-mac', userId: owner.sub, apiKey: 'fixture-proposal-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+})
+afterAll(async () => { await db?.$disconnect(); await replica?.stop() })
+
+async function fixture() {
+ let now = Date.now()
+ const store = new SuperTabStore(db, () => now, null, { readCache: null })
+ const tab = (await store.create(owner, randomUUID(), 'Proposal cards', 'public')).id
+ const execute = (command: unknown, user = owner, asAgentId?: string, operationId = randomUUID()) =>
+ store.execute(user, tab, { operationId, command: commandSchema.parse(command) }, asAgentId)
+ const invitation = await execute({ type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' })
+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId }, peer)
+ const pm = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'proposal-mac', harnessId: randomUUID(), name: 'PM', configuration: config, lead: true })).result.agentId)
+ // #3819 owns the switch command; this test isolates its agreed stored input.
+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${tab}:head` } })
+ const data = head.data as unknown as { projects: Array<{ boardMode?: true }> }
+ data.projects[0]!.boardMode = true
+ await db.swarmHead.update({ where: { id: head.id }, data: { data: data as never, version: head.version + 1 } })
+ const create = async (user = peer, priority = 'P2') => String((await execute({ type: 'proposal.create', projectId: 'lead', title: 'Keep drafts', text: 'Keep offline drafts',
+ goal: 'Preserve work', why: 'Reconnect loses drafts', doneWhen: 'Draft returns', evidence: ['Network-off reproduction'], priority }, user)).result.conversationId)
+ const card = async (id: string) => (await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: tab, key: id } } })).data as unknown as Conversation
+ return { store, tab, pm, execute, create, card, clock: { get now() { return now }, set now(value: number) { now = value } } }
+}
+
+describe('durable proposal cards', () => {
+ it('turns verified unanswered original messages into cards once on switch, preserving words and ownership', async () => {
+ const f = await fixture()
+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: false })
+ const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Keep these original words', recipientIds: [f.pm], replyTo: null })
+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })
+ const { legacyProposalId } = await import('../src/superTabs/proposalCards.js')
+ const id = legacyProposalId('lead', String(sent.result.messageId))
+ expect((await f.card(id)).proposal).toMatchObject({ text: 'Keep these original words', legacyMessageId: sent.result.messageId,
+ senders: [{ personId: owner.sub }] })
+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })
+ expect(await db.swarmGroup.count({ where: { tabId: f.tab, key: id } })).toBe(1)
+ expect((await f.card('lead')).owed ?? []).toHaveLength(0)
+ })
+
+ it('tells senders the PM was excluded and persists only the recipients that will receive a chat post', async () => {
+ const f = await fixture()
+ const group = String((await f.execute({ type: 'conversation.create', title: 'Follow-up', brief: 'Resolve the question', checks: [{ description: 'Question answered', independent: false }] })).result.conversationId)
+ const worker = String((await f.execute({ type: 'agent.add', conversationId: group, machineId: 'proposal-mac', harnessId: randomUUID(), name: 'Worker', configuration: config, lead: false })).result.agentId)
+ const question = await f.execute({ type: 'message.send', conversationId: group, text: 'Which work should we keep?', recipientIds: [worker], replyTo: null }, owner, f.pm)
+ for (const asAgent of [undefined, worker]) {
+ const sent = await f.execute({ type: 'message.send', conversationId: group, text: 'Keep the offline draft work', recipientIds: [f.pm], replyTo: String(question.result.messageId) }, owner, asAgent)
+ expect(sent.result.reachedNoAgent).toEqual(expect.any(String))
+ expect(sent.result.notReached).toContain('PM')
+ expect(sent.result.notReached).toContain('proposal card')
+ const row = await db.superTabMessage.findUniqueOrThrow({ where: { id: String(sent.result.messageId) } })
+ expect(row.recipientIds).toEqual([])
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: row.id } })).toBe(0)
+ }
+ const partial = await f.execute({ type: 'message.send', conversationId: group, text: 'For both', recipientIds: [f.pm, worker], replyTo: null })
+ expect(partial.result.notReached).toContain('PM')
+ expect(partial.result).not.toHaveProperty('reachedNoAgent')
+ expect((await db.superTabMessage.findUniqueOrThrow({ where: { id: String(partial.result.messageId) } })).recipientIds).toEqual([worker])
+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: String(partial.result.messageId) } })).map(d => d.agentId)).toEqual([worker])
+ })
+
+ it('delivers a decided notice inside the sending person’s private Buddy chat', async () => {
+ const f = await fixture()
+ const added = await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', setup: { name: 'Fixture Mac', cwd: '/fixture', engines: ['codex'] } })
+ const startId = String(added.result.startId)
+ const host = (command: unknown) => f.store.execute(owner, f.tab, { operationId: randomUUID(), command: commandSchema.parse(command) }, undefined, 'proposal-mac')
+ await host({ type: 'agent.startDispatch', startId })
+ const buddyId = String((await host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)
+ await host({ type: 'agent.startSettled', startId, warning: null })
+ const id = await f.create(owner)
+ await f.execute({ type: 'proposal.decide', conversationId: id, decision: 'no', reason: 'Outside positioning' }, owner, f.pm)
+ const delivered = await f.store.deliveries(owner, f.tab, buddyId)
+ const notices = await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: String(added.result.conversationId) } })
+ const decision = notices.find(m => (m.source as any)?.moment === 'decided')!
+ expect(decision).toBeDefined()
+ expect(delivered.some(d => d.messageId === decision.id)).toBe(true)
+ })
+
+ it('keeps a dormant card loaded when its person has a dormant default Buddy chat', async () => {
+ const f = await fixture()
+ await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', setup: { name: 'Fixture Mac', cwd: '/fixture', engines: ['codex'] } })
+ const second = await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', name: 'Research' })
+ await f.execute({ type: 'buddy.default', conversationId: second.result.conversationId })
+ const id = await f.create(owner)
+ for (const key of [id, String(second.result.conversationId)]) {
+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key } } })
+ await db.swarmGroup.update({ where: { id: row.id }, data: { dormant: true, version: { increment: 1 },
+ data: { ...(row.data as object), dormant: true } } })
+ }
+ await f.execute({ type: 'proposal.decide', conversationId: id, decision: 'no', reason: 'Outside positioning' }, owner, f.pm)
+ expect((await f.card(id)).proposal!.decision).toMatchObject({ kind: 'no', reason: 'Outside positioning' })
+ const notices = await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: String(second.result.conversationId) } })
+ expect(notices.some(m => (m.source as { moment?: string } | null)?.moment === 'decided')).toBe(true)
+ })
+
+ it('routes a dormant proposal overdue notice to the dormant default Buddy chat', async () => {
+ const f = await fixture()
+ await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', setup: { name: 'Fixture Mac', cwd: '/fixture', engines: ['codex'] } })
+ const second = await f.execute({ type: 'buddy.create', machineId: 'proposal-mac', engine: 'codex', name: 'Research' })
+ await f.execute({ type: 'buddy.default', conversationId: second.result.conversationId })
+ const id = await f.create(owner)
+ for (const key of [id, String(second.result.conversationId)]) {
+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key } } })
+ await db.swarmGroup.update({ where: { id: row.id }, data: { dormant: true, version: { increment: 1 },
+ data: { ...(row.data as object), dormant: true } } })
+ }
+ f.clock.now += 31 * 60_000
+ await runTimeCheckPass(db, f.store, f.clock.now)
+ expect((await f.card(id)).proposal!.overdue).toBe(true)
+ const notices = await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: String(second.result.conversationId) } })
+ expect(notices.some(m => (m.source as { kind?: string } | null)?.kind === 'proposal-overdue')).toBe(true)
+ })
+
+ it('delivers urgent proposals first on both a full poll and its fast repeat', async () => {
+ const f = await fixture(), low = await f.create(), urgent = await f.create(owner, 'P0')
+ for (let i = 0; i < 2; i++) {
+ const deliveries = await f.store.deliveries(owner, f.tab, f.pm)
+ expect(deliveries.filter(d => [low, urgent].includes(d.conversationId)).map(d => d.conversationId)).toEqual([urgent, low])
+ }
+ })
+
+ it('does not hide a new P0 behind the bounded page of older nonurgent inputs', async () => {
+ const f = await fixture(), low = await f.create()
+ const row = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, conversationId: low, agentId: f.pm } })
+ await db.superTabDelivery.createMany({ data: Array.from({ length: 105 }, (_, i) => ({ ...row, id: randomUUID(), createdAt: new Date(f.clock.now - i - 1000) })) })
+ const urgent = await f.create(owner, 'P0')
+ const prof = await profiled(db, async () => expect((await f.store.deliveries(owner, f.tab, f.pm))[0]?.conversationId).toBe(urgent))
+ const priority = plan(reads(prof, 'SuperTabDelivery', ['inputPriority']))
+ expect(priority).toEqual([expect.objectContaining({ plan: expect.stringContaining('IXSCAN { tabId: 1, agentId: 1, status: 1, inputPriority: 1, createdAt: 1 }') })])
+ expect(priority[0]!.docsExamined).toBeLessThanOrEqual(110)
+ console.info('Proposal priority read:', priority)
+ expect((await f.store.deliveries(owner, f.tab, f.pm))[0]?.conversationId).toBe(urgent)
+ })
+
+ it('withholds queued ordinary chat after switching and still delivers a proposal', async () => {
+ const f = await fixture()
+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } })
+ const data = head.data as any
+ delete data.projects[0].boardMode
+ await db.swarmHead.update({ where: { id: head.id }, data: { data, version: { increment: 1 } } })
+ const chat = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Old ordinary chat', recipientIds: [f.pm], replyTo: null })
+ data.projects[0].boardMode = true
+ await db.swarmHead.update({ where: { id: head.id }, data: { data, version: { increment: 1 } } })
+ const id = await f.create()
+ const deliveries = await f.store.deliveries(owner, f.tab, f.pm)
+ expect(deliveries.some(d => d.messageId === chat.result.messageId)).toBe(false)
+ expect(deliveries.some(d => d.conversationId === id)).toBe(true)
+ })
+
+ it('persists viewer proposals and answers through the real store and changed-parts read', async () => {
+ const f = await fixture(), read = new SwarmReads(f.store)
+ const before = await read.firstLoad(peer, f.tab)
+ const id = await f.create()
+ const question = await f.execute({ type: 'proposal.ask', conversationId: id, personId: peer.sub,
+ question: 'Seven days?', defaultAnswer: 'Seven days', deadline: f.clock.now + 60_000 }, owner, f.pm)
+ const answered = await f.execute({ type: 'proposal.answer', conversationId: id, questionId: question.result.questionId, text: 'Fourteen days' }, peer)
+ expect(answered.result.applied).toBe(true)
+ expect((await f.card(id)).proposal!.questions[0]!.answer!.text).toBe('Fourteen days')
+ const changes = await read.changes(peer, f.tab, before.cursor)
+ expect(changes.groups.some(g => g.key === id && !g.deleted && 'data' in g && g.data?.proposal?.text === 'Keep offline drafts')).toBe(true)
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: f.pm, messageId: answered.result.messageId as string } })).toBe(1)
+ })
+
+ it('applies questions after long inactivity including dormant cards, using the due index', async () => {
+ const { dueProposalCards } = await import('../src/superTabs/proposalDue.js')
+ const f = await fixture(), id = await f.create(), deadline = f.clock.now + 30 * DAY
+ await f.execute({ type: 'proposal.ask', conversationId: id, personId: peer.sub, question: 'Wait?', defaultAnswer: 'Proceed', deadline }, owner, f.pm)
+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: id } } })
+ await db.swarmGroup.update({ where: { id: row.id }, data: { dormant: true, lastActivityAt: new Date(f.clock.now - 60 * DAY), data: { ...(row.data as object), dormant: true } } })
+ f.clock.now = deadline
+ const prof = await profiled(db, () => dueProposalCards(db, deadline, 200))
+ const due = plan(reads(prof, 'SwarmGroup', ['proposalDueAt']))
+ expect(due).toEqual([expect.objectContaining({ plan: 'IXSCAN { deleted: 1, proposalDueAt: 1, tabId: 1, key: 1 }' })])
+ expect(due[0]!.docsExamined).toBeLessThanOrEqual(due[0]!.returned ?? 0)
+ await runTimeCheckPass(db, f.store, deadline)
+ expect((await f.card(id)).proposal!.questions[0]!.answer).toMatchObject({ text: 'Proceed', defaulted: true })
+ await runTimeCheckPass(db, f.store, deadline + 1)
+ expect(await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: id, text: 'Proceed' } })).toBe(1)
+ })
+
+ it('guards answer races and denies receipt replay after private-project revocation', async () => {
+ const f = await fixture(), id = await f.create(), deadline = f.clock.now + 1000
+ const q = await f.execute({ type: 'proposal.ask', conversationId: id, personId: peer.sub, question: 'Keep?', defaultAnswer: 'Yes', deadline }, owner, f.pm)
+ const answer = { type: 'proposal.answer', conversationId: id, questionId: q.result.questionId, text: 'No' }
+ const results = await Promise.all([f.execute(answer, peer), f.execute({ ...answer, text: 'Maybe' }, peer)])
+ expect(results.map(r => r.result.applied).sort()).toEqual([false, true])
+ await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [peer.sub] })
+ const op = randomUUID()
+ await f.execute({ ...answer, text: 'Visible late comment' }, peer, undefined, op)
+ await f.execute({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })
+ await expect(f.execute({ ...answer, text: 'Visible late comment' }, peer, undefined, op)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+})
diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.ts
index e5d369177..336076661 100644
--- a/backend/integration/workerIndexPlans.test.ts
+++ b/backend/integration/workerIndexPlans.test.ts
@@ -474,5 +474,6 @@ describe('what a PM owes', () => {
expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, agentId: 1, status: 1, createdAt: 1/)
// The two unanswered rows of the last day, at most one key past each status's range.
expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(2)
+ expect(rows[0]!.keysExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(7)
})
})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 7d5adda42..84f6ee975 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1508,6 +1508,8 @@ model SuperTabDelivery {
// A row gathered for its PM's inbox rather than the notice digest (inbox.ts, task #3545): "people" or "crew". At idle the
// inbox goes at once only for these; unset on notices and on older rows.
inboxSection String?
+ /// Server-derived proposal priority, 0 first. Absent on rows before proposal cards; retained until existing delivery compaction.
+ inputPriority Int?
// A queued delivery whose claims keep answering SWARM_BUSY (prod 10-30, v1.3.71): written outside the failed claim, unset by
// the claim that gets in. The settle pass alarms on them and page reads show the sender (store.ts recordFailedClaim).
claimFailingSince DateTime?
@@ -1520,6 +1522,7 @@ model SuperTabDelivery {
updatedAt DateTime @updatedAt
@@index([tabId, agentId, status, createdAt])
+ @@index([tabId, agentId, status, inputPriority, createdAt])
@@index([machineId, status])
// A page of messages reads its deliveries by message (pageReads.ts).
@@index([tabId, messageId])
@@ -1974,6 +1977,8 @@ model SwarmGroup {
messageSeq Int @default(0)
reportSeq Int @default(0)
lastActivityAt DateTime
+ /// Next proposal deadline/revisit; null once none is due. Existing card history lives until project/Swarm deletion.
+ proposalDueAt DateTime?
/// The machines whose hosts this group's last write concerned: its agents' and its work's, before and after (host reads).
hostMachineIds String[] @default([])
/// A short hash of the fields host rows read (read/hostRows.ts); a post leaves it. Missing on a part written before it.
@@ -1985,6 +1990,7 @@ model SwarmGroup {
/// Not indexed on `data.kind` (Atlas advisor, 2026-11-04, task #2841): no backend read filters by it, the only one that
/// does is the rollback script scripts/buddy-sessions/end-all.ts, across every Swarm; and every hot read keeps its plan
/// with such an index (the numbers are in task #2841's pull request). The top-level `kind` holds the same value.
+ @@index([deleted, proposalDueAt, tabId, key])
@@unique([tabId, key])
@@index([tabId, changedAt])
@@index([tabId, dormant, changedAt])
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
index cde7efd83..fde37f26d 100644
--- a/backend/src/superTabs/buddies.ts
+++ b/backend/src/superTabs/buddies.ts
@@ -281,6 +281,7 @@ const BUDDY_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.re
'agent.stopLease', 'agent.stopRefused', 'agent.remove', 'buddy.modelResult'])
export function requireBuddyCommand(buddy: Agent, command: { type: string; conversationId?: unknown; agentId?: unknown }, groups: readonly Conversation[]): void {
+ if (command.type === 'proposal.answer') return // The card handler checks the current sender and question before receipt replay.
if (!BUDDY_COMMANDS.has(command.type)) fail('BUDDY_FORBIDDEN', 'A Buddy only talks with its owner and sends the proposals they ask for.', 403)
if ('agentId' in command && command.agentId !== buddy.id) fail('BUDDY_FORBIDDEN', 'A Buddy acts only for itself.', 403)
if (command.type === 'message.send' || command.type === 'message.react' || command.type === 'buddy.propose') {
diff --git a/backend/src/superTabs/buddyNews.ts b/backend/src/superTabs/buddyNews.ts
index c018843d2..90f224983 100644
--- a/backend/src/superTabs/buddyNews.ts
+++ b/backend/src/superTabs/buddyNews.ts
@@ -61,6 +61,7 @@ export function tellBuddies(state: SuperTabState, message: MessageDraft, threadS
/** Work [group]'s requester asked for was just assigned: one line for their Buddy alone, inside the task, saying only what
* its person reads there (its number, title and status, Lead's ruling 10-29). None when the Buddy cannot read the task. */
export function assignedNotice(state: SuperTabState, group: Conversation, author: Author, operationId: string): MessageDraft | null {
+ if (groupProject(state, group).boardMode) return null
const buddy = group.requesterId ? listeningBuddy(state, group.requesterId, group) : undefined
if (!buddy || !group.assignment) return null
return { id: stableId(operationId, 'buddy-news'), conversationId: group.id, author, replyTo: null, recipients: [buddy.id], source: AGENT_ONLY,
@@ -70,6 +71,7 @@ export function assignedNotice(state: SuperTabState, group: Conversation, author
/** Work [group]'s requester asked for just shipped: the news the Shipped line brought their Buddy, now that the task's line
* says it (taskLine.ts), as one line for their Buddy alone inside the task, like the assignment's. */
export function shippedNotice(state: SuperTabState, group: Conversation, author: Author, operationId: string): MessageDraft | null {
+ if (group.proposal) return null
const buddy = group.requesterId ? listeningBuddy(state, group.requesterId, group) : undefined
if (!buddy) return null
return { id: stableId(operationId, 'buddy-news', 'shipped'), conversationId: group.id, author, replyTo: null, recipients: [buddy.id], source: AGENT_ONLY,
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 6aec6030e..e719b6920 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,3 +1,4 @@
+import { migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'
import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'
import { applyPushOrigin, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import { crewMoveFailed, takeOverCrewMember, wakeCrewMember } from './crewKeep.js'
@@ -198,6 +199,13 @@ const task = z.object({
const MAX_REMOVED_MACHINES = 64
export const commandSchema = z.discriminatedUnion('type', [
+ proposalCreateSchema,
+ z.object({ type: z.literal('proposal.decide'), conversationId: id, decision: z.enum(['accept', 'reshape', 'later', 'no']), reason: text,
+ task: task.optional(), checks: z.array(check).min(1).max(50).optional(), revisitAt: z.number().int().positive().max(8_640_000_000_000_000).optional() }).strict(),
+ z.object({ type: z.literal('proposal.ask'), conversationId: id, personId: id, question: text, defaultAnswer: text,
+ deadline: z.number().int().positive().max(8_640_000_000_000_000), requiresConsent: z.boolean().optional() }).strict(),
+ z.object({ type: z.literal('proposal.answer'), conversationId: id, questionId: id, text }).strict(),
+ z.object({ type: z.literal('proposal.merge'), conversationId: id, intoConversationId: id, reason: text }).strict(),
z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(swarmEngine).min(1).max(2), maxAgents,
// Its Agents setting (machines.ts agentLimit): an older client leaves it out.
agents: z.enum(['memory', 'atMost']).optional(),
@@ -343,7 +351,8 @@ export const commandSchema = z.discriminatedUnion('type', [
// showed them before their ok, as long as any message. `title` is an older Buddy's, which is refused for its missing text.
z.object({ type: z.literal('buddy.propose'), conversationId: id, ownerMessageId: id, projectId: id.optional(), text: text.optional(),
title: z.string().trim().min(1).max(80).optional(), goal: z.string().trim().min(1).max(2000),
- scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']),
+ scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high', 'P0', 'P1', 'P2', 'P3', 'hotfix']),
+ why: proposalFields.why.optional(), doneWhen: proposalFields.doneWhen.optional(), evidence: proposalFields.evidence.optional(),
attachmentIds: z.array(id).max(MAX_PROPOSAL_ATTACHMENTS, `Attach at most ${MAX_PROPOSAL_ATTACHMENTS} files to a proposal.`).optional() }).strict(),
// Without `projectId`, the person's one Buddy (Dee, 10-31); an older app names a project, and removes that same one Buddy.
// `conversationId`: which of the person's Buddies, by its chat (task #3818); without it, their default.
@@ -555,6 +564,8 @@ export function withoutCredentials(command: Command, removed: CredentialKind[]):
/** A message row a group names as its proposal, as the store loads it. */
interface ProposalRow { id: string; conversationId: string; author: Author; source: Record<string, unknown> | null }
export interface CommandContext {
+ /** Indexed original bodies verified by the store for the staged Board handover. */
+ legacyProposals?: LegacyProposalAsk[]
operationId: string
now: number
/** For a terminal request: its agent's session is confidential in some Swarm, read by the store (confidential.ts). */
@@ -809,6 +820,13 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS
const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'message.edit', 'message.delete', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd',
// Which of a person's several Buddies (task #3818).
'buddy.create', 'buddy.remove', 'buddy.default', 'buddy.model'])
+function viewerProposal(state: SuperTabState, actor: Actor, command: Command): boolean {
+ if (command.type === 'proposal.create' || command.type === 'proposal.answer') return true
+ if (command.type !== 'buddy.propose' || actor.kind !== 'agent') return false
+ const self = state.agents.find(a => a.id === actor.agentId && isBuddy(a))
+ return !!self && !!projectsOf(state).find(p => p.id === (command.projectId ?? agentProjectId(state, self)))?.boardMode
+}
+
export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {
if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return
@@ -820,9 +838,16 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if (command.type === 'mention.done' || command.type === 'decision.answer' || command.type === 'member.username'
|| command.type === 'member.name' || command.type === 'member.timeZone') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
- author(state, actor, !leaving)
+ author(state, actor, !leaving && !viewerProposal(state, actor, command))
const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
if (buddy) requireBuddyCommand(buddy, command, state.conversations)
+ if (command.type === 'proposal.create') authorizePersonProposal(state, actor, command)
+ if (command.type === 'buddy.propose' && buddy) {
+ if (isSwarmBuddy(buddy) && !command.projectId) fail('BUDDY_PROPOSE_PROJECT', 'Name the project to send this to, from your status. If it is unclear which, ask your owner.', 400)
+ const project = readProject(state, actor, command.projectId ?? agentProjectId(state, buddy))
+ if (project.boardMode) cardPriority(state, project, buddy.buddyOf!.personId, command.priority)
+ }
+ if (command.type === 'proposal.decide' || command.type === 'proposal.ask' || command.type === 'proposal.answer' || command.type === 'proposal.merge') authorizeProposalAction(state, actor, command)
// An invitation's group is only where the person lands, and invite.create replaces a deleted one (inviteLanding).
// A Buddy command names a chat only to pick one of the person's Buddies (task #3818): without one, it names none.
if ('conversationId' in command && command.conversationId && command.type !== 'invite.create') {
@@ -992,6 +1017,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
let sender: Author | undefined
try { sender = author(effects.state, actor) } catch { sender = undefined }
syncTaskLines(original, effects, sender, stableId(original.id, actorKey(actor), context.operationId))
+ for (const row of effects.messages) row.recipients = row.recipients.filter(id => pmAcceptsMessage(effects.state, id, row.source))
// Every open group is loaded for a command (parts/load.ts): the board's pulse is worked out on it (pulse.ts), for the project
// of the conversation the command names when it names one (it moves no other), else for every project.
recordPulse(effects.state, context.now, pulseProjectOf(effects.state, input))
@@ -1103,7 +1129,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (command.type === 'swarm.delete' && (actor.kind !== 'person' || actor.userId !== state.ownerId)) notThere()
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username'
- && command.type !== 'member.name' && command.type !== 'member.timeZone')
+ && command.type !== 'member.name' && command.type !== 'member.timeZone' && !viewerProposal(state, actor, command))
authorizeCommandAccess(state, actor, command, context)
/** A machine's owner said so: they sent the command, or the Lead of the chat [askedIn] names passes on a message they wrote
* there in the last day, as routing rules are (machine.engineResume, machine.projects). */
@@ -1727,6 +1753,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
/** Every check work.assign makes before [worker] takes [group]'s work, throwing its refusal; nothing changes here, so a
* caller trying candidates in turn (openReviewSteps) catches the refusal and tries the next. */
const assignRefusal = (group: Conversation, worker: Agent) => {
+ if (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '')) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before assigning work.', 409)
if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === worker.machineId && s.harnessId === worker.harnessId)) {
fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')
}
@@ -2096,7 +2123,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
case 'project.boardMode': {
const project = boardOwned(command.projectId)
- if (command.on) project.boardMode = true
+ if (command.on) {
+ project.boardMode = true
+ effects.messages.push(...migrateLegacyProposals(state, project, context.legacyProposals ?? [], context.now))
+ }
else delete project.boardMode
break
}
@@ -3027,6 +3057,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
break
}
case 'agent.start': {
+ const proposed = conversation(state, command.request.conversationId).proposal
+ if (proposed && !['accept', 'reshape'].includes(proposed.decision?.kind ?? '')) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before starting work.', 409)
chatOnly(command.request.conversationId)
projectChatWork(command.request.conversationId)
// A coordinator starts there through lead.start alone.
@@ -3108,6 +3140,20 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
break
}
+ case 'proposal.decide': case 'proposal.ask': case 'proposal.answer': case 'proposal.merge': {
+ const outcome = applyProposalAction(state, actor, command, operationId, context.now)
+ effects.messages.push(...outcome.messages)
+ Object.assign(result, outcome.result)
+ break
+ }
+ case 'proposal.create': {
+ const card = createPersonProposal(state, actor, command, operationId, context.now)
+ effects.messages.push(proposalRoot(state, card, stableId(operationId, 'root'), sender))
+ result.messageId = stableId(operationId, 'root')
+ result.conversationId = card.id
+ result.number = card.number
+ break
+ }
case 'buddy.propose': {
const self = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
if (!self) fail('BUDDY_ONLY', 'Only a Buddy sends a proposal, for its owner.', 403)
@@ -3148,6 +3194,21 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))
chat.proposals = [...chat.proposals ?? [], command.ownerMessageId].slice(-MAX_PROPOSAL_ASKS)
const project = readProject(state, actor, command.projectId ?? agentProjectId(state, self)), home = conversation(state, project.leadConversationId)
+ if (project.boardMode) {
+ const card = createProposalCard(state, project, { personId: owner.id, generation: owner.generation, buddyId: self.id }, {
+ title: command.title ?? command.goal.slice(0, 160), text: words, goal: command.goal, why: command.why!,
+ doneWhen: command.doneWhen!, evidence: command.evidence!, priority: cardPriority(state, project, owner.id, command.priority),
+ }, operationId, context.now)
+ card.proposal!.scope = command.scope
+ const root = proposalRoot(state, card, stableId(operationId, 'root'), author(state, { kind: 'person', userId: owner.id, email: owner.email }))
+ if (attachments.length) root.attachments = attachments
+ effects.messages.push(root)
+ result.messageId = root.id
+ result.conversationId = card.id
+ result.number = card.number
+ break
+ }
+ if (!['low', 'normal', 'high'].includes(command.priority)) fail('BOARD_MODE_REQUIRED', 'P0–P3 proposal priorities require proposal cards.', 409)
// One message, its owner's, delivered to the PM: its goal, scope and priority ride in its source for the PM and the task's
// brief (proposalBrief), with no reply from the Buddy in the chat (anh Dee, task #2926).
message(home.id, words, home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [], null,
@@ -4029,7 +4090,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
&& group.assignment?.agentId === automatic && group.assignment.status === 'done' && group.leadId && group.leadId !== automatic
&& group.agentIds.includes(group.leadId) ? group.leadId : null
// An agent the post named and may not be named is no recipient by any route: not the assignee, nor the author it answers.
- const recipients = [...new Set([...addressed, ...answeredAgent ? [answeredAgent] : [], ...(addressed.length ? [] : [below, automatic, doneWith].filter((id): id is string => !!id))])].filter(id => !barred.includes(id))
+ let recipients = [...new Set([...addressed, ...answeredAgent ? [answeredAgent] : [], ...(addressed.length ? [] : [below, automatic, doneWith].filter((id): id is string => !!id))])].filter(id => !barred.includes(id))
for (const id of recipients) {
const target = agent(state, id)
// In a Buddy chat a session hears its own thread alone, and the main Buddy none of it.
@@ -4049,6 +4110,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('INVALID_RECIPIENT', 'An agent sends an agent-only notice to itself alone.', 400)
}
if (command.notice && !command.agentOnly) fail('VALIDATION_ERROR', 'A skills notice is an agent-only notice to the agent itself.', 400)
+ // Apply the Board's PM boundary before reporting delivery or recording work that depends on who heard the post.
+ const excludedPm = command.agentOnly ? [] : recipients.filter(id => !pmAcceptsMessage(state, id, undefined))
+ recipients = recipients.filter(id => !excludedPm.includes(id))
// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.
message(group.id, text, recipients, command.replyTo, command.agentOnly ? { ...AGENT_ONLY, ...command.notice ? { notice: command.notice } : {} } : undefined, attachments, tagged,
tagged.length ? command.mentionsIfNoWorker : undefined)
@@ -4059,8 +4123,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
// After the person's message: nobody answers it, so its person is told why (Dee, review of #2447).
if (buddyDown) buddyDownLine(group, buddyDown)
- if (poster && !command.agentOnly && !recipients.length) effects.result.reachedNoAgent = REACHED_NO_AGENT
+ if ((poster || excludedPm.length) && !command.agentOnly && !recipients.length) effects.result.reachedNoAgent = REACHED_NO_AGENT
if (barred.length) effects.result.notReached = notReachedLine(barred.map(id => agent(state, id).displayName ?? agent(state, id).name))
+ if (excludedPm.length) {
+ const names = excludedPm.map(id => agent(state, id).displayName ?? agent(state, id).name).join(', ')
+ effects.result.notReached = [effects.result.notReached, `This post did not reach ${names}: the PM takes proposals and proposal answers from cards. Use a proposal card when the PM must act.`].filter(Boolean).join('\n')
+ }
// A Personal Swarm project chat with no Lead: the message waits for the Lead its person's Desktop starts (task #2633).
// A Team Swarm's says Not sent, as before.
const unled = actor.kind === 'person' && !recipients.length && !isBuddyChat(group) && isPersonalSwarm(state) ? groupProject(state, group) : undefined
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 4bc9d9a1a..ef2e58fd1 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -467,6 +467,8 @@ export interface Conversation {
lostAttempt?: { id: string; agentId: string; machineId?: string; engine?: string }
/** Counts reaction changes here (reactions.ts), so readers see a new reaction on an older message. */
reactionSeq?: number
+ /** A durable proposal on this card (#3817); retained when its accepted work becomes a task. */
+ proposal?: import('./proposalCards.js').ProposalRecord
/** A Buddy chat's owner messages its Buddy already proposed for (buddies.ts): each asks once. */
proposals?: string[]
/** The name a Buddy chat's owner chose for their Buddy (buddies.ts renameBuddy): kept here, which outlives the Buddy, so
@@ -802,6 +804,8 @@ export const NOTICE_READERS = {
// A member removed one of the coordinator's notes: told to the coordinator alone (instructions.ts).
'note-removed': 'recipients',
'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people', 'buddy-proposal-sent': 'people', 'buddy-session-ended': 'people',
+ // Proposal history and private Buddy notices are visible to the people who can read their card/chat.
+ 'proposal-card': 'people', 'proposal-answer': 'people', 'proposal-notice': 'people', 'proposal-merged': 'people', 'proposal-overdue': 'people',
'decision-delegated': 'people', 'machine-removed': 'people', ship: 'people',
// A computer signed in as another account now, told to its old owner in their Buddy chat (commands.ts machine.moved, #3122).
'computer-moved': 'people',
diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.ts
index 54faf3d1a..502424157 100644
--- a/backend/src/superTabs/pageReads.ts
+++ b/backend/src/superTabs/pageReads.ts
@@ -103,11 +103,19 @@ export async function agentGatheredCount(tx: Transaction, tabId: string, agentId
/** An agent's open deliveries, oldest first and each conversation's tied rows in its order: one indexed read, and the tied
* messages' sequences only when there are ties. */
-export async function agentOpenDeliveries(tx: Transaction, tabId: string, agentId: string): Promise<SuperTabDelivery[]> {
+export async function agentOpenDeliveries(tx: Transaction, tabId: string, agentId: string, prioritized = false): Promise<SuperTabDelivery[]> {
// By the agent index (parts/indexed.ts): Prisma sent `status: { in }` as an $expr $or, planned as one scan per status.
const rows = await readBy(tx, 'SuperTabDelivery', 'agentOpen', [{ $match: { tabId, agentId, status: { $in: [...OPEN_DELIVERY] } } },
{ $sort: { createdAt: 1 } }, { $limit: 100 }])
- return inConversationOrder(tx, tabId, rows.map(row => prismaRow<SuperTabDelivery>('SuperTabDelivery', row)))
+ const priority = prioritized ? await readBy(tx, 'SuperTabDelivery', 'agentProposal', [
+ { $match: { tabId, agentId, status: { $in: [...OPEN_DELIVERY] }, inputPriority: { $gte: 0 } } },
+ { $sort: { inputPriority: 1, createdAt: 1 } }, { $limit: 100 },
+ ]) : []
+ const joined = [...new Map([...priority, ...rows].map(r => [String(r._id), r])).values()]
+ const ordered = await inConversationOrder(tx, tabId, joined.map(row => prismaRow<SuperTabDelivery>('SuperTabDelivery', row)))
+ // Old notices remain readable; missing priority means a normal server notice, below P0.
+ if (prioritized) ordered.sort((a, b) => (a.inputPriority ?? 1) - (b.inputPriority ?? 1) || a.createdAt.getTime() - b.createdAt.getTime())
+ return ordered
}
/** An agent's open deliveries, read by creation time, with each conversation's tied rows put in its message order. One
diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.ts
index efa843278..49326507b 100644
--- a/backend/src/superTabs/parts/indexed.ts
+++ b/backend/src/superTabs/parts/indexed.ts
@@ -13,6 +13,7 @@ type Transaction = Prisma.TransactionClient
/** The SwarmGroup indexes hot reads name, as prisma/schema.prisma declares them. */
export const GROUP_INDEX = {
+ proposalDue: { deleted: 1, proposalDueAt: 1, tabId: 1, key: 1 },
key: { tabId: 1, key: 1 },
running: { tabId: 1, executionMachineId: 1 },
agents: { tabId: 1, agentIds: 1 },
@@ -82,6 +83,7 @@ export const NAMED_INDEX = {
SuperTabDelivery: {
/** An agent's deliveries by status and age: its open ones, oldest first. */
agentOpen: { tabId: 1, agentId: 1, status: 1, createdAt: 1 },
+ agentProposal: { tabId: 1, agentId: 1, status: 1, inputPriority: 1, createdAt: 1 },
/** Finished deliveries by their last change: those old enough to compact (deliveryCompaction.ts). */
compaction: { status: 1, updatedAt: 1 },
/** Unfinished deliveries in id order, a page at a time (deliverySettle.ts). Named: with a fourth status Mongo planned the pass on
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index f66921a4b..6ad1086ca 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -70,6 +70,7 @@ const conversation: Required<Conversation> = {
pin: { agentId: 'a', why: 'ci', at: 1 },
priority: 'P0',
projectId: 'p',
+ proposal: { version: 1, text: 'Words', goal: 'Goal', why: 'Why', doneWhen: 'Done', evidence: ['Evidence'], priority: 'P2', createdAt: 0, senders: [], questions: [] },
proposals: [],
pullRequestChecks: {},
pullRequestEvents: {},
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index be7235b3f..517568dda 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -39,6 +39,7 @@ export const GROUP_FIELDS = {
'kind',
'leadId',
'projectId',
+ 'proposal',
'pulse',
'reviewOf',
],
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index b9058be75..9599b825c 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -61,6 +61,26 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'machine.contribute':
if (!before.machines?.some(m => m.machineId === command.machineId)) head()
break
+ case 'proposal.create':
+ head()
+ group(leadGroupOf(command.projectId))
+ break
+ case 'proposal.decide': case 'proposal.ask': case 'proposal.answer': case 'proposal.merge': {
+ head()
+ const card = before.conversations.find(c => c.id === command.conversationId)
+ leadCheck(card && groupProject(before, card).id)
+ for (const identity of card?.proposal?.senders ?? []) member(identity.personId)
+ if (command.type === 'proposal.merge') {
+ group(command.intoConversationId)
+ for (const id of card?.proposal?.mergedFrom ?? []) group(id)
+ }
+ break
+ }
+ case 'buddy.propose':
+ head()
+ leadCheck(command.projectId)
+ if (actor.kind === 'agent') member(before.agents.find(a => a.id === actor.agentId)?.buddyOf?.personId)
+ break
case 'buddy.create':
// It may record a Buddy-only machine, or count on one that a concurrent removal of its last Buddy ends.
slots(command.machineId)
diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.ts
index f5e15bb96..5ab3ff99e 100644
--- a/backend/src/superTabs/parts/write.ts
+++ b/backend/src/superTabs/parts/write.ts
@@ -1,3 +1,4 @@
+import { proposalDueAt } from '../proposalClock.js'
import { createHash } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { activeWork, stableId, type AgentStart, type Agent } from '../model.js'
@@ -105,8 +106,9 @@ function hostDigest(group: GroupData): string {
export function extracted(kind: PartKind, data: unknown, stamp: number): Record<string, unknown> {
switch (kind) {
case 'group': {
- const group = data as GroupData
+ const group = data as GroupData, dueAt = proposalDueAt(group.proposal)
return { projectId: group.projectId ?? null, kind: group.kind ?? null, archived: group.archived, dormant: !!group.dormant,
+ proposalDueAt: dueAt == null ? null : new Date(dueAt),
agentIds: group.agentIds, executionMachineId: activeWork(group) ? group.assignment!.execution.machineId : null,
messageSeq: group.messageSeq ?? 0, reportSeq: group.reportSeq ?? 0,
lastActivityAt: group.lastActivityAt ? new Date(group.lastActivityAt) : new Date(stamp), hostDigest: hostDigest(group),
diff --git a/backend/src/superTabs/pollMemory.ts b/backend/src/superTabs/pollMemory.ts
index 1802d4c00..02c7c4688 100644
--- a/backend/src/superTabs/pollMemory.ts
+++ b/backend/src/superTabs/pollMemory.ts
@@ -11,7 +11,7 @@ export interface PollRedis {
const grant = z.object({ contributorId: z.string(), machineId: z.string(), machineOwnerId: z.string(), hostGrant: z.string().nullable() })
const polled = z.object({
at: z.number().finite(),
- open: z.object({ stamp: z.number().finite(), seen: z.array(z.string()), allowed: z.array(z.string()),
+ open: z.object({ prioritized: z.boolean().optional(), stamp: z.number().finite(), seen: z.array(z.string()), allowed: z.array(z.string()),
swarm: z.object({ workspaceId: z.string().optional(), environment: z.string() }), grants: z.record(z.string(), grant) }).optional(),
})
diff --git a/backend/src/superTabs/proposalCards.test.ts b/backend/src/superTabs/proposalCards.test.ts
new file mode 100644
index 000000000..893c853d5
--- /dev/null
+++ b/backend/src/superTabs/proposalCards.test.ts
@@ -0,0 +1,368 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, authorizeCommandAccess, commandSchema, type CommandContext } from './commands.js'
+import { fullSwarm, NOW, owner, peer, outsider, config } from './read/fixture.test-support.js'
+import { type Actor, type Conversation, type SuperTabState } from './model.js'
+import { queueSiblings } from './taskQueue.js'
+import { groupView } from './read/views.js'
+import { GROUP_FIELDS } from './parts/light.js'
+
+const words = 'Keep edits offline until the connection returns.'
+const proposal = { title: 'Offline edits', text: words, goal: 'Keep drafts', why: 'People lose offline work',
+ doneWhen: 'Reconnect restores edits', evidence: ['Reproduced with network disabled'], priority: 'P2' as const }
+function fixture(switched = true) {
+ const f = fullSwarm(NOW)
+ if (switched) Object.assign(f.state.projects![0]!, { boardMode: true })
+ let seq = 0
+ const run = (input: unknown, actor: Actor = peer, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(f.state, actor, commandSchema.parse(input), { now: NOW, operationId: `proposal-test-${++seq}`, ...context })
+ f.edit(state => Object.assign(state, effects.state))
+ return effects
+ }
+ const create = (actor: Actor = peer, extra = {}) => run({ type: 'proposal.create', projectId: 'lead', ...proposal, ...extra }, actor)
+ const card = (id: unknown) => f.state.conversations.find(c => c.id === id)!
+ const pm: Actor = { kind: 'agent', agentId: f.lead, machineOwnerId: `${owner.userId}-machine` }
+ const base: Omit<typeof f, 'run'> = f
+ return Object.assign(base, { run, create, card, pm })
+}
+
+// Removing record creation, membership/consent checks or the queue exclusion breaks these caller-visible assertions.
+describe('proposal card creation', () => {
+ it.each(['collaborator', 'viewer'] as const)('lets a current %s propose without a Buddy and keeps it out of the task queue', role => {
+ const f = fixture()
+ f.state.people.find(p => p.id === peer.userId)!.role = role
+ const sent = f.create(), card = f.card(sent.result.conversationId)
+ expect(card).toMatchObject({ title: 'Offline edits', projectId: 'lead', requesterId: peer.userId, priority: 'P2', assignment: null,
+ proposal: { version: 1, text: words, goal: 'Keep drafts', why: 'People lose offline work', doneWhen: 'Reconnect restores edits', evidence: ['Reproduced with network disabled'], priority: 'P2', createdAt: NOW, senders: [{ personId: peer.userId,
+ generation: f.state.people.find(p => p.id === peer.userId)!.generation }], questions: [] } })
+ expect(card.task).toBeUndefined()
+ expect(queueSiblings(f.state, f.state.projects![0]!)).not.toContainEqual(card)
+ expect(sent.messages.find(m => m.conversationId === card.id)).toMatchObject({ text: words, recipients: [f.lead], source: { kind: 'proposal-card' } })
+ expect(groupView(card, new Set())).toHaveProperty('proposal.text', words)
+ })
+
+ it.each(['goal', 'why', 'doneWhen', 'evidence'] as const)('refuses a missing %s', field => {
+ const f = fixture(), input: Record<string, unknown> = { type: 'proposal.create', projectId: 'lead', ...proposal }
+ delete input[field]
+ expect(commandSchema.safeParse(input).success).toBe(false)
+ expect(f.state.conversations.some(c => 'proposal' in c)).toBe(false)
+ })
+
+ it('refuses board proposals before switching and private projects the member cannot read', () => {
+ const legacy = fixture(false)
+ expect(() => legacy.create()).toThrow(expect.objectContaining({ code: 'BOARD_MODE_REQUIRED' }))
+ const f = fixture()
+ expect(() => f.create(outsider, { projectId: f.secret })).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ })
+
+ it('allows P0/hotfix only for an entitled person, including through their Buddy', () => {
+ const f = fixture()
+ expect(() => f.create(peer, { priority: 'P0' })).toThrow(expect.objectContaining({ code: 'PRIORITY_FORBIDDEN' }))
+ for (const priority of ['P0', 'hotfix']) expect(f.card(f.create(owner, { priority }).result.conversationId).priority).toBe('P0')
+ Object.assign(f.state.projects![0]!, { decider: peer.userId })
+ expect(f.card(f.create(peer, { priority: 'P0' }).result.conversationId).priority).toBe('P0')
+ })
+
+ it('preserves exact consent and person/Buddy attribution on switched buddy.propose', () => {
+ const f = fixture(), buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }
+ const input = { type: 'buddy.propose', conversationId: f.buddyChat, ownerMessageId: 'ask', projectId: 'lead',
+ ...proposal, scope: 'Persist drafts', priority: 'normal' }
+ const ask: NonNullable<CommandContext['proposalAsk']> = { id: 'ask', conversationId: f.buddyChat, source: false,
+ author: { kind: 'person', id: peer.userId, name: peer.email, membershipGeneration: f.state.people.find(p => p.id === peer.userId)!.generation },
+ text: words, createdAt: NOW, newestOwnerMessageId: 'ask', shown: [] }
+ const sent = f.run(input, buddy, { proposalAsk: ask }), card = f.card(sent.result.conversationId)
+ expect(card.proposal?.senders[0]).toMatchObject({ personId: peer.userId, buddyId: f.buddy })
+ expect(sent.messages.find(m => m.conversationId === card.id)?.author.id).toBe(peer.userId)
+ expect(() => f.run({ ...input, ownerMessageId: 'ask2', text: 'Private extra detail' }, buddy,
+ { proposalAsk: { ...ask, id: 'ask2', newestOwnerMessageId: 'ask2' } })).toThrow(expect.objectContaining({ code: 'PROPOSAL_UNSHOWN' }))
+ expect(() => f.run({ ...input, ownerMessageId: 'ask3', priority: 'P0' }, buddy,
+ { proposalAsk: { ...ask, id: 'ask3', newestOwnerMessageId: 'ask3' } })).toThrow(expect.objectContaining({ code: 'PRIORITY_FORBIDDEN' }))
+ })
+
+ it('lets a viewer’s Buddy propose, but rechecks P0 rights before replay', () => {
+ const f = fixture(), buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }
+ f.state.people.find(p => p.id === peer.userId)!.role = 'viewer'
+ const input = { type: 'buddy.propose', conversationId: f.buddyChat, ownerMessageId: 'ask', projectId: 'lead',
+ ...proposal, scope: 'Persist drafts', priority: 'normal' }
+ const consent: NonNullable<CommandContext['proposalAsk']> = { id: 'ask', conversationId: f.buddyChat, source: false,
+ author: { kind: 'person', id: peer.userId, name: peer.email, membershipGeneration: f.state.people.find(p => p.id === peer.userId)!.generation },
+ text: words, createdAt: NOW, newestOwnerMessageId: 'ask', shown: [] }
+ expect(f.card(f.run(input, buddy, { proposalAsk: consent }).result.conversationId).proposal?.text).toBe(words)
+ expect(() => authorizeCommandAccess(f.state, buddy, commandSchema.parse({ ...input, priority: 'P0' })))
+ .toThrow(expect.objectContaining({ code: 'PRIORITY_FORBIDDEN' }))
+ })
+
+ it('keeps the approved files and scope when a Buddy sends a proposal card', () => {
+ const f = fixture(), buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }
+ const file = { id: 'plan', name: 'plan.md', mime: 'text/markdown', size: 120, url: 'https://cdn.example.test/plan.md' }
+ const sent = f.run({ type: 'buddy.propose', conversationId: f.buddyChat, ownerMessageId: 'ask', projectId: 'lead',
+ ...proposal, scope: 'Persist drafts', priority: 'normal', attachmentIds: ['plan'] }, buddy, {
+ attachments: [file], proposalAsk: { id: 'ask', conversationId: f.buddyChat, source: false,
+ author: { kind: 'person', id: peer.userId, name: peer.email, membershipGeneration: f.state.people.find(p => p.id === peer.userId)!.generation },
+ text: words, createdAt: NOW, newestOwnerMessageId: 'ask', shown: [] },
+ })
+ expect(sent.messages.find(m => m.conversationId === sent.result.conversationId)?.attachments).toEqual([file])
+ expect(f.card(sent.result.conversationId).proposal).toHaveProperty('scope', 'Persist drafts')
+ })
+
+ it('refuses hand assignment until the proposal is accepted', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ expect(() => f.run({ type: 'work.assign', conversationId: id, agentId: f.worker }, f.pm))
+ .toThrow(expect.objectContaining({ code: 'PROPOSAL_UNDECIDED' }))
+ })
+
+ it('refuses a manual agent start before a decision', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ expect(() => f.run({ type: 'agent.start', request: { conversationId: id, machineId: 'host', name: 'Builder', engine: 'codex', cwd: '/fixture', worktree: false, requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } } }, f.pm))
+ .toThrow(expect.objectContaining({ code: 'PROPOSAL_UNDECIDED' }))
+ })
+
+ it('rejects dates outside the supported timestamp range at the command boundary', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ expect(commandSchema.safeParse(ask(id, { deadline: 1e20 })).success).toBe(false)
+ expect(commandSchema.safeParse(decide(id, 'later', { revisitAt: 1e20 })).success).toBe(false)
+ })
+
+ it('keeps unswitched Buddy proposals as project-chat roots and refuses new priorities there', () => {
+ const f = fixture(false), buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }
+ const input = { type: 'buddy.propose', conversationId: f.buddyChat, ownerMessageId: 'ask', projectId: 'lead',
+ title: 'Offline edits', text: words, goal: proposal.goal, scope: 'Persist drafts', priority: 'high' }
+ const ask: NonNullable<CommandContext['proposalAsk']> = { id: 'ask', conversationId: f.buddyChat, source: false,
+ author: { kind: 'person', id: peer.userId, name: peer.email, membershipGeneration: f.state.people.find(p => p.id === peer.userId)!.generation },
+ text: words, createdAt: NOW, newestOwnerMessageId: 'ask', shown: [] }
+ const sent = f.run(input, buddy, { proposalAsk: ask })
+ expect(sent.messages[0]).toMatchObject({ conversationId: 'lead', source: { kind: 'buddy-proposal', priority: 'high' } })
+ expect(sent.result.conversationId).toBeUndefined()
+ expect(() => f.run({ ...input, ownerMessageId: 'ask2', priority: 'P0' }, buddy, { proposalAsk: { ...ask, id: 'ask2', newestOwnerMessageId: 'ask2' } })).toThrow(expect.objectContaining({ code: 'BOARD_MODE_REQUIRED' }))
+ })
+
+ it('retains proposal authorization metadata in light delivery loads', () => {
+ expect(GROUP_FIELDS.always).toContain('proposal')
+ })
+
+ it('imports an unanswered legacy message once with stable identity and original words', async () => {
+ const cards = await import('./proposalCards.js')
+ const f = fixture(), ask = { messageId: 'legacy-ask', conversationId: 'lead', personId: peer.userId, text: 'Please keep these exact words', at: NOW - 1000 }
+ const id = cards.importLegacyProposal(f.state, f.state.projects![0]!, ask, NOW)
+ expect(cards.importLegacyProposal(f.state, f.state.projects![0]!, ask, NOW)).toBe(id)
+ expect(f.state.conversations.filter(c => c.id === id)).toHaveLength(1)
+ expect(f.card(id)).toMatchObject({ requesterId: peer.userId, proposal: { text: ask.text, legacyMessageId: 'legacy-ask', createdAt: NOW - 1000 } })
+ })
+})
+
+const acceptedTask = { goal: 'Keep drafts', changes: 'Persist offline edits', constraints: 'No dependencies', owns: ['backend/src/drafts.ts'] }
+const checks = [{ description: 'Reconnect restores edits', independent: false }]
+const deadline = NOW + 60_000
+const decide = (conversationId: unknown, decision = 'accept', extra = {}) => ({ type: 'proposal.decide', conversationId,
+ decision, reason: 'Prevents lost work for contributors', ...(['accept', 'reshape'].includes(decision) ? { task: acceptedTask, checks } : {}), ...extra })
+const ask = (conversationId: unknown, extra = {}) => ({ type: 'proposal.ask', conversationId, personId: peer.userId,
+ question: 'Keep drafts for seven days?', defaultAnswer: 'Keep seven days', deadline, ...extra })
+
+describe('PM decisions and card questions', () => {
+ it('sends shipped notices once to every proposer after verified release, never at merge', async () => {
+ const { notePendingRelease, pendingKey, settleReleases } = await import('./releases.js')
+ const { shippedNotice } = await import('./buddyNews.js')
+ const { author } = await import('./model.js')
+ const f = fixture(), id = f.create().result.conversationId, other = f.create(owner).result.conversationId
+ f.run({ type: 'proposal.merge', conversationId: other, intoConversationId: id, reason: 'Same request' }, f.pm)
+ f.run(decide(id), f.pm)
+ const card = f.card(id), project = f.state.projects![0]!
+ expect(shippedNotice(f.state, card, author(f.state, f.pm), 'merge')).toBeNull()
+ notePendingRelease(project, card, 'https://github.com/o/r/pull/1', NOW)
+ const entry = project.releases!.pending[0]!
+ const facts = { resolved: [{ ...entry, components: ['backend' as const] }], releases: {} }
+ expect(settleReleases(f.state, 'lead', facts, NOW).messages.filter(m => m.source?.moment === 'shipped')).toHaveLength(0)
+ const verified = { resolved: [], releases: { backend: { tag: 'v1.0.0_backend', sha: 'verified', at: NOW + 1000, carries: [pendingKey(entry)] } } }
+ const result = settleReleases(f.state, 'lead', verified, NOW + 1000)
+ expect(result.messages.filter(m => m.source?.moment === 'shipped')).toHaveLength(2)
+ expect(settleReleases(f.state, 'lead', verified, NOW + 2000).messages.filter(m => m.source?.moment === 'shipped')).toHaveLength(0)
+ })
+
+ it.each(['accept', 'reshape', 'later', 'no'])('records %s with its reason on the same card exactly once', decision => {
+ const f = fixture(), id = f.create().result.conversationId
+ const result = f.run(decide(id, decision, decision === 'later' ? { revisitAt: deadline } : {}), f.pm)
+ expect(f.card(id).proposal?.decision).toMatchObject({ kind: decision, reason: 'Prevents lost work for contributors', at: NOW, by: f.lead })
+ expect(result.messages.some(m => m.conversationId === id && m.text.includes('Prevents lost work'))).toBe(true)
+ expect(result.messages.some(m => m.source?.kind === 'proposal-notice' && m.source.moment === 'decided')).toBe(true)
+ if (['accept', 'reshape'].includes(decision)) {
+ expect(f.card(id).task).toEqual(acceptedTask)
+ expect(queueSiblings(f.state, f.state.projects![0]!)).toContainEqual(f.card(id))
+ expect(f.card(id).checks[0]).toMatchObject({ description: 'Reconnect restores edits' })
+ } else expect(f.card(id).task).toBeUndefined()
+ if (decision === 'no') expect(f.card(id).archived).toBe(true)
+ expect(() => f.run(decide(id), f.pm)).toThrow(expect.objectContaining({ code: 'PROPOSAL_DECIDED' }))
+ })
+
+ it('refuses decisions without accepted work/date and refuses non-PMs before receipt replay', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ for (const actor of [owner, peer, { kind: 'agent', agentId: f.worker, machineOwnerId: `${owner.userId}-machine` } as Actor]) {
+ expect(() => f.run(decide(id), actor)).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
+ }
+ for (const input of [decide(id, 'accept', { task: undefined }), decide(id, 'reshape', { checks: [] }), decide(id, 'later')]) {
+ expect(() => f.run(input, f.pm)).toThrow()
+ }
+ const input = commandSchema.parse(decide(id))
+ f.state.conversations.find(c => c.id === 'lead')!.leadId = f.worker
+ expect(() => authorizeCommandAccess(f.state, f.pm, input)).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
+ })
+
+ it('routes a question to its sender, and allows only that person or their sending Buddy to answer', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ // A direct Board proposal has no sending Buddy: its current default may answer for its person.
+ const asked = f.run(ask(id), f.pm), q = f.card(id).proposal!.questions[0]!
+ expect(q).toMatchObject({ personId: peer.userId, question: 'Keep drafts for seven days?', defaultAnswer: 'Keep seven days', deadline, requiresConsent: false })
+ expect(asked.messages.some(m => m.source?.kind === 'proposal-notice' && m.source.moment === 'needs-you')).toBe(true)
+ const answer = { type: 'proposal.answer', conversationId: id, questionId: q.id, text: 'Keep fourteen days' }
+ expect(() => f.run(answer, outsider)).toThrow(expect.objectContaining({ code: 'PROPOSAL_ANSWER_FORBIDDEN' }))
+ f.state.people.find(p => p.id === peer.userId)!.role = 'viewer'
+ f.run(answer, peer)
+ expect(f.card(id).proposal!.questions[0]!.answer).toMatchObject({ text: 'Keep fourteen days', by: peer.userId, at: NOW })
+ const late = f.run({ ...answer, text: 'Actually thirty' }, peer)
+ expect(late.result.applied).toBe(false)
+ expect(late.messages[0]!.text).toContain('Actually thirty')
+ expect(f.card(id).proposal!.questions[0]!.answer!.text).toBe('Keep fourteen days')
+ })
+
+ it('permits the sending Buddy on its own card and keeps arbitrary posts and other Buddies forbidden', () => {
+ const f = fixture(), id = f.create().result.conversationId, generation = f.state.people.find(p => p.id === peer.userId)!.generation
+ f.card(id).proposal!.senders[0]!.buddyId = f.buddy
+ const qid = f.run(ask(id), f.pm).result.questionId
+ const buddy: Actor = { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` }
+ f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Seven days is fine' }, buddy)
+ expect(f.card(id).proposal!.questions[0]!.answer!.by).toBe(f.buddy)
+ expect(() => f.run({ type: 'message.send', conversationId: id, text: 'Arbitrary new scope', recipientIds: [], replyTo: null }, buddy)).toThrow(expect.objectContaining({ code: 'BUDDY_FORBIDDEN' }))
+ f.state.agents.push({ ...f.state.agents.find(a => a.id === f.buddy)!, id: 'other-buddy', harnessId: 'other', buddyOf: { personId: outsider.userId, generation: f.state.people.find(p => p.id === outsider.userId)!.generation } })
+ expect(() => f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Foreign' },
+ { kind: 'agent', agentId: 'other-buddy', machineOwnerId: `${owner.userId}-machine` })).toThrow()
+ f.state.people.find(p => p.id === peer.userId)!.generation = 'rejoined'
+ expect(() => authorizeCommandAccess(f.state, buddy, commandSchema.parse({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Stale' }))).toThrow()
+ })
+
+ it('never accepts a Buddy answer in place of explicit person consent', () => {
+ const f = fixture(), id = f.create().result.conversationId
+ f.card(id).proposal!.senders[0]!.buddyId = f.buddy
+ const qid = f.run(ask(id, { requiresConsent: true }), f.pm).result.questionId
+ expect(() => f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Yes' },
+ { kind: 'agent', agentId: f.buddy, machineOwnerId: `${owner.userId}-machine` })).toThrow(expect.objectContaining({ code: 'PROPOSAL_CONSENT_REQUIRED' }))
+ })
+
+ it('allows the current default to answer after the sending Buddy is removed, but not while it remains', async () => {
+ const { openSwarmBuddyChat } = await import('./buddies.js')
+ const f = fixture(), id = f.create().result.conversationId
+ const member = f.state.people.find(p => p.id === peer.userId)!
+ const chat = openSwarmBuddyChat(f.state, member)
+ const original = f.state.agents.find(a => a.id === f.buddy)!
+ const fallback = { ...original, id: 'fallback', harnessId: 'fallback', buddyScope: 'swarm' as const }
+ f.state.agents.push(fallback)
+ chat.agentIds.push(fallback.id)
+ f.card(id).proposal!.senders[0]!.buddyId = f.buddy
+ const qid = f.run(ask(id), f.pm).result.questionId
+ const answer = { type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Seven days' }
+ const actor: Actor = { kind: 'agent', agentId: fallback.id, machineOwnerId: fallback.machineOwnerId }
+ expect(() => f.run(answer, actor)).toThrow(expect.objectContaining({ code: 'PROPOSAL_ANSWER_FORBIDDEN' }))
+ f.state.agents = f.state.agents.filter(a => a.id !== f.buddy)
+ f.run(answer, actor)
+ expect(f.card(id).proposal!.questions[0]!.answer?.by).toBe(fallback.id)
+ })
+
+ it('merges duplicates into one card, preserving attribution and notifying every proposer', () => {
+ const f = fixture(), first = f.create().result.conversationId, second = f.create(outsider).result.conversationId
+ const merged = f.run({ type: 'proposal.merge', conversationId: second, intoConversationId: first, reason: 'Same reconnect loss' }, f.pm)
+ expect(f.card(second)).toMatchObject({ archived: true, proposal: { mergedInto: first } })
+ expect(f.card(first).proposal!.senders.map(s => s.personId).sort()).toEqual([peer.userId, outsider.userId].sort())
+ expect(merged.messages.filter(m => m.source?.kind === 'proposal-notice')).toHaveLength(2)
+ expect(() => f.run({ type: 'proposal.merge', conversationId: first, intoConversationId: second, reason: 'Cycle' }, f.pm)).toThrow()
+ expect(() => f.run({ type: 'proposal.merge', conversationId: first, intoConversationId: f.secretGroup, reason: 'Other project' }, f.pm)).toThrow()
+ const third = f.create(owner).result.conversationId
+ f.run({ type: 'proposal.merge', conversationId: first, intoConversationId: third, reason: 'Canonical combined card' }, f.pm)
+ expect(f.card(second).proposal!.mergedInto).toBe(third)
+ expect(f.card(first).proposal!.mergedInto).toBe(third)
+ })
+
+ it('does not abandon open questions or allow merge/ask metadata to grow without a bound', () => {
+ const f = fixture(), id = f.create().result.conversationId, other = f.create(owner).result.conversationId
+ f.run(ask(id), f.pm)
+ expect(() => f.run({ type: 'proposal.merge', conversationId: id, intoConversationId: other, reason: 'Duplicate' }, f.pm)).toThrow(expect.objectContaining({ code: 'PROPOSAL_QUESTION_OPEN' }))
+ for (let i = 1; i < 20; i++) f.run(ask(id), f.pm)
+ expect(() => f.run(ask(id), f.pm)).toThrow(expect.objectContaining({ code: 'PROPOSAL_LIMIT' }))
+ })
+})
+
+describe('proposal time and delivery boundaries', () => {
+ it('applies a default exactly at the deadline once, preserving a later answer as discussion', async () => {
+ const { advanceProposalCards } = await import('./proposalCards.js')
+ const f = fixture(), id = f.create().result.conversationId
+ const qid = f.run(ask(id), f.pm).result.questionId
+ expect(advanceProposalCards(f.state, deadline - 1)).toEqual([])
+ const messages = advanceProposalCards(f.state, deadline)
+ expect(f.card(id).proposal!.questions[0]!.answer).toEqual({ text: 'Keep seven days', at: deadline, by: 'default', defaulted: true })
+ expect(messages.some(m => m.source?.kind === 'proposal-answer' && m.recipients.includes(f.lead))).toBe(true)
+ expect(advanceProposalCards(f.state, deadline + 1)).toEqual([])
+ expect(f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Late correction' }, peer, { now: deadline + 2 }).result.applied).toBe(false)
+ expect(f.card(id).proposal!.questions[0]!.answer!.text).toBe('Keep seven days')
+ })
+
+ it('checks the deadline within an answer transaction even before the worker runs', () => {
+ const f = fixture(), id = f.create().result.conversationId, qid = f.run(ask(id), f.pm).result.questionId
+ const answer = f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'Too late' }, peer, { now: deadline })
+ expect(answer.result.applied).toBe(false)
+ expect(f.card(id).proposal!.questions[0]!.answer!.defaulted).toBe(true)
+ })
+
+ it('marks explicit consent overdue without defaulting, and still permits the named person', async () => {
+ const { advanceProposalCards } = await import('./proposalCards.js')
+ const f = fixture(), id = f.create().result.conversationId, qid = f.run(ask(id, { requiresConsent: true }), f.pm).result.questionId
+ advanceProposalCards(f.state, deadline)
+ expect(f.card(id).proposal!.questions[0]).toMatchObject({ overdue: true })
+ expect(f.card(id).proposal!.questions[0]!.answer).toBeUndefined()
+ expect(advanceProposalCards(f.state, deadline + 1)).toEqual([])
+ expect(f.run({ type: 'proposal.answer', conversationId: id, questionId: qid, text: 'I agree' }, peer, { now: deadline + 2 }).result.applied).toBe(true)
+ })
+
+ it('reopens Later on its date even after a month, and marks unanswered proposals overdue once', async () => {
+ const { advanceProposalCards } = await import('./proposalCards.js')
+ const f = fixture(), id = f.create().result.conversationId, date = NOW + 30 * 86_400_000
+ f.run(decide(id, 'later', { revisitAt: date }), f.pm)
+ expect(advanceProposalCards(f.state, date - 1)).toEqual([])
+ expect(advanceProposalCards(f.state, date).some(m => m.recipients.includes(f.lead))).toBe(true)
+ expect(f.card(id).proposal!.decision).toBeUndefined()
+ const overdue = advanceProposalCards(f.state, date + 30 * 60_000)
+ expect(f.card(id).proposal!.overdue).toBe(true)
+ expect(overdue.some(m => m.source?.kind === 'proposal-overdue')).toBe(true)
+ expect(advanceProposalCards(f.state, date + 31 * 60_000)).toEqual([])
+ })
+
+ it.each(['person', 'agent'] as const)('tells a %s when their ordinary post reaches no switched PM', kind => {
+ const f = fixture(), actor: Actor = kind === 'person' ? owner : { kind: 'agent', agentId: f.worker, machineOwnerId: `${owner.userId}-machine` }
+ const sent = f.run({ type: 'message.send', conversationId: f.web, text: 'Answer for the PM', recipientIds: [f.lead], replyTo: null }, actor)
+ expect(sent.messages.find(m => m.id === sent.result.messageId)?.recipients).toEqual([])
+ expect(sent.result.reachedNoAgent).toEqual(expect.any(String))
+ expect(sent.result.notReached).toContain('lead-harness')
+ expect(sent.result.notReached).toContain('proposal card')
+ })
+
+ it('reports the excluded PM while delivering to another recipient and leaves legacy delivery alone', () => {
+ const f = fixture()
+ const input = { type: 'message.send', conversationId: f.web, text: 'For both of you', recipientIds: [f.lead, f.worker], replyTo: null }
+ const sent = f.run(input, owner)
+ expect(sent.messages.find(m => m.id === sent.result.messageId)?.recipients).toEqual([f.worker])
+ expect(sent.result.notReached).toContain('lead-harness')
+ expect(sent.result.notReached).not.toContain('worker-harness')
+ expect(sent.result).not.toHaveProperty('reachedNoAgent')
+ delete f.state.projects![0]!.boardMode
+ const legacy = f.run(input, owner)
+ expect(legacy.messages.find(m => m.id === legacy.result.messageId)?.recipients).toEqual([f.lead, f.worker])
+ expect(legacy.result).not.toHaveProperty('notReached')
+ expect(legacy.result).not.toHaveProperty('reachedNoAgent')
+ })
+
+ it('blocks ordinary messages to a switched PM, retaining proposals, answers, server notices and all legacy inputs', async () => {
+ const { pmAcceptsMessage } = await import('./proposalCards.js')
+ const f = fixture(), id = f.create().result.conversationId
+ expect(pmAcceptsMessage(f.state, f.lead, undefined)).toBe(false)
+ for (const kind of ['proposal-card', 'proposal-answer', 'work-status', 'system']) expect(pmAcceptsMessage(f.state, f.lead, { kind })).toBe(true)
+ const posted = f.run({ type: 'message.send', conversationId: id, text: 'New scope via chat', recipientIds: [f.lead], replyTo: null }, peer)
+ expect(posted.messages[0]!.recipients).toEqual([])
+ delete f.state.projects![0]!.boardMode
+ expect(pmAcceptsMessage(f.state, f.lead, undefined)).toBe(true)
+ })
+})
diff --git a/backend/src/superTabs/proposalCards.ts b/backend/src/superTabs/proposalCards.ts
new file mode 100644
index 000000000..03f8f7775
--- /dev/null
+++ b/backend/src/superTabs/proposalCards.ts
@@ -0,0 +1,270 @@
+import { steers } from './boardRights.js'
+import { expireProposalQuestion } from './proposalClock.js'
+export { advanceProposalCards, proposalDueAt } from './proposalClock.js'
+/** Durable proposal metadata lives on its existing version-guarded card. Discussion stays in message rows. */
+import { z } from 'zod'
+import { author, fail, nextConversationNumber, person, stableId, type Actor, type Author, type Conversation, type MessageDraft, renderWorkTask, type SuperTabState } from './model.js'
+import { buddyFor, defaultBuddy, isBuddy } from './buddies.js'
+import { recordAsked } from './leaderboard/record.js'
+import { stampLane } from './dispatch.js'
+import { groupProject, ledProject, readConversation, canReadProject, readProject, type SwarmProject } from './projects.js'
+import { proposalPriority, type TaskPriority } from './taskPriority.js'
+
+export interface ProposalSender { personId: string; generation: string; buddyId?: string }
+export interface ProposalRecord {
+ version: 1
+ text: string
+ goal: string
+ scope?: string
+ why: string
+ doneWhen: string
+ evidence: string[]
+ priority: TaskPriority
+ createdAt: number
+ senders: ProposalSender[]
+ questions: ProposalQuestion[]
+ legacyMessageId?: string
+ decision?: { kind: 'accept' | 'reshape' | 'later' | 'no'; reason: string; at: number; by: string; revisitAt?: number }
+ mergedInto?: string
+ mergedFrom?: string[]
+ overdue?: true
+ waitSince?: number
+}
+export interface ProposalQuestion {
+ id: string; personId: string; question: string; defaultAnswer: string; deadline: number; requiresConsent: boolean
+ answer?: { text: string; at: number; by: string; defaulted?: true }
+ overdue?: true
+}
+const field = z.string().trim().min(1).max(4000)
+export const proposalFields = {
+ text: z.string().trim().min(1).max(32_000), goal: field, why: field, doneWhen: field,
+ evidence: z.array(z.string().trim().min(1).max(2000)).min(1).max(5),
+}
+export const proposalCreateSchema = z.object({ type: z.literal('proposal.create'), projectId: z.string().min(1).max(160),
+ title: z.string().trim().min(1).max(160), ...proposalFields, priority: z.enum(['P0', 'P1', 'P2', 'P3', 'hotfix']) }).strict()
+export type CreateProposal = z.infer<typeof proposalCreateSchema>
+
+export function requireBoard(project: SwarmProject): void {
+ if (project.boardMode !== true) fail('BOARD_MODE_REQUIRED', 'This project has not switched to proposal cards.', 409)
+}
+/** Legacy low/normal/high keep their old meaning; only an entitled person can originate a hotfix. */
+export function cardPriority(state: SuperTabState, project: SwarmProject, ownerId: string, value: string): TaskPriority {
+ const priority = value === 'hotfix' ? 'P0' : /^P[0-3]$/.test(value) ? value as TaskPriority : proposalPriority(value)
+ const member = person(state, ownerId)
+ if (priority === 'P0' && !steers(state, project, member.id)) {
+ fail('PRIORITY_FORBIDDEN', 'Only the project owner, Swarm owner or top decider may propose P0 or a hotfix.', 403)
+ }
+ return priority
+}
+
+export function createProposalCard(state: SuperTabState, project: SwarmProject, sender: ProposalSender,
+ input: Omit<CreateProposal, 'type' | 'projectId'>, id: string, now: number): Conversation {
+ requireBoard(project)
+ const member = state.people.find(p => p.id === sender.personId && p.generation === sender.generation)
+ if (!member || !canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) fail('NOT_FOUND', 'This project is unavailable.', 404)
+ const parsed = proposalCreateSchema.parse({ type: 'proposal.create', projectId: project.id, ...input })
+ const priority = cardPriority(state, project, member.id, input.priority)
+ const leadId = state.conversations.find(c => c.id === project.leadConversationId)?.leadId ?? null
+ const number = nextConversationNumber(state)
+ state.groupCounter = number
+ const card: Conversation = { id, number, projectId: project.id, title: input.title, leadId, agentIds: leadId ? [leadId] : [],
+ archived: false, brief: input.text, checks: [], assignment: null, lastMessageSequence: 0, lastActivityAt: new Date(now).toISOString(),
+ requesterId: member.id, priority, codePullRequestUrls: [],
+ proposal: { version: 1, text: parsed.text, goal: parsed.goal, why: parsed.why, doneWhen: parsed.doneWhen,
+ evidence: parsed.evidence, priority, createdAt: now, senders: [sender], questions: [] } }
+ state.conversations.push(card)
+ return card
+}
+export function authorizePersonProposal(state: SuperTabState, actor: Actor, input: CreateProposal): void {
+ if (actor.kind !== 'person') fail('PROPOSAL_PERSON', 'A person proposes from the Board; a Buddy uses buddy.propose with their consent.', 403)
+ const project = readProject(state, actor, input.projectId)
+ requireBoard(project)
+ cardPriority(state, project, actor.userId, input.priority)
+}
+export function createPersonProposal(state: SuperTabState, actor: Actor, input: CreateProposal, id: string, now: number): Conversation {
+ if (actor.kind !== 'person') fail('PROPOSAL_PERSON', 'A person proposes from the Board; a Buddy uses buddy.propose with their consent.', 403)
+ authorizePersonProposal(state, actor, input)
+ const member = person(state, actor.userId), project = readProject(state, actor, input.projectId)
+ return createProposalCard(state, project, { personId: member.id, generation: member.generation }, input, id, now)
+}
+export function proposalRoot(state: SuperTabState, card: Conversation, id: string, sender: Author): MessageDraft {
+ return { id, conversationId: card.id, author: sender, text: card.proposal!.text, replyTo: null,
+ recipients: card.leadId ? [card.leadId] : [], source: { kind: 'proposal-card', priority: card.priority } }
+}
+export const legacyProposalId = (projectId: string, messageId: string): string => stableId('legacy-proposal', projectId, messageId)
+export interface LegacyProposalAsk { messageId: string; conversationId: string; personId: string; text: string; at: number; generation?: string }
+/** Caller loads this stable id (including dormant cards) before importing; no scan or second interpretation of consent. */
+export function importLegacyProposal(state: SuperTabState, project: SwarmProject, ask: LegacyProposalAsk, now: number): string {
+ requireBoard(project)
+ const id = legacyProposalId(project.id, ask.messageId)
+ if (state.conversations.some(c => c.id === id)) return id
+ const member = person(state, ask.personId)
+ const original = state.conversations.find(c => c.id === ask.conversationId)
+ if (!original || original.kind || original.audience || groupProject(state, original).id !== project.id
+ || (ask.generation && member.generation !== ask.generation)) fail('NOT_FOUND', 'The original request is unavailable.', 404)
+ const card = createProposalCard(state, project, { personId: member.id, generation: member.generation }, {
+ title: ask.text.trim().slice(0, 160) || 'Earlier request', text: ask.text, goal: ask.text.slice(0, 4000),
+ why: 'Imported unanswered request; details remain to be clarified.', doneWhen: 'To be clarified on this card.',
+ evidence: ['Original project message'], priority: 'P2',
+ }, id, now)
+ card.proposal!.legacyMessageId = ask.messageId
+ card.proposal!.createdAt = ask.at
+ return id
+}
+
+export const MAX_CARD_QUESTIONS = 20
+export const MAX_CARD_SENDERS = 50
+export type ProposalAction =
+ | { type: 'proposal.decide'; conversationId: string; decision: 'accept' | 'reshape' | 'later' | 'no'; reason: string;
+ task?: import('./model.js').WorkTask; checks?: Array<{ description: string; independent?: boolean }>; revisitAt?: number }
+ | { type: 'proposal.ask'; conversationId: string; personId: string; question: string; defaultAnswer: string; deadline: number; requiresConsent?: boolean }
+ | { type: 'proposal.answer'; conversationId: string; questionId: string; text: string }
+ | { type: 'proposal.merge'; conversationId: string; intoConversationId: string; reason: string }
+
+function namedCard(state: SuperTabState, actor: Actor, id: string): Conversation & { proposal: ProposalRecord } {
+ const group = readConversation(state, actor, id)
+ if (!group.proposal || group.kind || group.audience) fail('NOT_FOUND', 'This proposal is unavailable.', 404)
+ return group as Conversation & { proposal: ProposalRecord }
+}
+function currentSender(state: SuperTabState, card: Conversation & { proposal: ProposalRecord }, personId: string): ProposalSender[] {
+ const member = state.people.find(p => p.id === personId)
+ return member ? card.proposal.senders.filter(s => s.personId === member.id && s.generation === member.generation) : []
+}
+function answerer(state: SuperTabState, actor: Actor, card: Conversation & { proposal: ProposalRecord }, questionId: string): ProposalQuestion {
+ const q = card.proposal.questions.find(q => q.id === questionId) ?? fail('NOT_FOUND', 'This question is unavailable.', 404)
+ const senders = currentSender(state, card, q.personId)
+ const self = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
+ const own = actor.kind === 'person' ? actor.userId === q.personId : !!self && self.buddyOf!.personId === q.personId
+ && senders.some(s => s.generation === self.buddyOf!.generation && (s.buddyId === self.id ||
+ ((!s.buddyId || !state.agents.some(a => a.id === s.buddyId && a.buddyOf?.personId === s.personId && a.buddyOf.generation === s.generation))
+ && defaultBuddy(state, s.personId)?.id === self.id)))
+ if (!senders.length || !own) fail('PROPOSAL_ANSWER_FORBIDDEN', 'Only the person asked or the Buddy that sent this card may answer.', 403)
+ if (q.requiresConsent && actor.kind !== 'person') fail('PROPOSAL_CONSENT_REQUIRED', 'This question needs the named person’s own agreement.', 403)
+ return q
+}
+/** Called before receipt replay as well as apply; a recorded operation retains no revoked right. */
+export function authorizeProposalAction(state: SuperTabState, actor: Actor, command: ProposalAction): void {
+ const card = namedCard(state, actor, command.conversationId), project = groupProject(state, card)
+ if (command.type === 'proposal.answer') { answerer(state, actor, card, command.questionId); return }
+ if (actor.kind !== 'agent' || ledProject(state, actor.agentId)?.id !== project.id) fail('COORDINATOR_REQUIRED', 'Only this project’s current PM decides, asks or merges proposals.', 403)
+ if (command.type === 'proposal.merge') {
+ const target = namedCard(state, actor, command.intoConversationId)
+ if (groupProject(state, target).id !== project.id) fail('NOT_FOUND', 'This proposal is unavailable.', 404)
+ }
+}
+
+/** Notices stay inside the consenting person's private Buddy chat, including when no Buddy can currently run. */
+export function proposalNotices(state: SuperTabState, card: Conversation & { proposal: ProposalRecord }, moment: 'decided' | 'needs-you' | 'shipped',
+ text: string, sender: Author, operationId: string, recipients = card.proposal.senders): MessageDraft[] {
+ const project = groupProject(state, card)
+ return recipients.flatMap((identity, i) => {
+ const member = state.people.find(p => p.id === identity.personId && p.generation === identity.generation)
+ if (!member || !canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) return []
+ const route = buddyFor(state, member, identity.buddyId ?? null)
+ return [{ id: stableId(operationId, 'proposal-notice', String(i), moment), conversationId: route.chat.id, author: sender,
+ text, replyTo: null, recipients: route.agent ? [route.agent.id] : [], buddyProject: project.id,
+ source: { kind: 'proposal-notice', moment, projectId: project.id, cardId: card.id } }]
+ })
+}
+function pending(card: Conversation & { proposal: ProposalRecord }): void {
+ if (card.proposal.decision || card.proposal.mergedInto) fail('PROPOSAL_DECIDED', 'This proposal already has a decision or was merged.', 409)
+}
+const hasOpenQuestion = (card: Conversation & { proposal: ProposalRecord }) => card.proposal.questions.some(q => !q.answer)
+
+export function applyProposalAction(state: SuperTabState, actor: Actor, command: ProposalAction, operationId: string, now: number):
+ { messages: MessageDraft[]; result: Record<string, unknown> } {
+ authorizeProposalAction(state, actor, command)
+ const card = namedCard(state, actor, command.conversationId), sender = author(state, actor)
+ const messages: MessageDraft[] = []
+ const result: Record<string, unknown> = { conversationId: card.id, messageId: operationId }
+ const row = (text: string, source: Record<string, unknown>, recipients: string[] = [], id = operationId) =>
+ messages.push({ id, conversationId: card.id, author: sender, text, recipients, replyTo: null, source })
+ if (command.type === 'proposal.answer') {
+ const q = answerer(state, actor, card, command.questionId)
+ messages.push(...expireProposalQuestion(state, card, q, now))
+ result.applied = !q.answer
+ if (!q.answer) q.answer = { text: command.text, at: now, by: sender.id }
+ row(command.text, { kind: 'proposal-answer', questionId: q.id, applied: result.applied }, card.leadId ? [card.leadId] : [])
+ } else if (command.type === 'proposal.ask') {
+ pending(card)
+ if (!currentSender(state, card, command.personId).length) fail('PROPOSAL_ANSWER_FORBIDDEN', 'Ask a current proposer on this card.', 403)
+ if (command.deadline <= now) fail('PROPOSAL_DEADLINE', 'Choose a future deadline.', 400)
+ if (card.proposal.questions.length >= MAX_CARD_QUESTIONS) fail('PROPOSAL_LIMIT', 'This card has 20 questions; decide it or reshape a new proposal.', 409)
+ const q: ProposalQuestion = { id: operationId, personId: command.personId, question: command.question, defaultAnswer: command.defaultAnswer,
+ deadline: command.deadline, requiresConsent: command.requiresConsent ?? false }
+ card.proposal.questions.push(q)
+ result.questionId = q.id
+ row(`${q.question}\nDefault: ${q.defaultAnswer}\nBy: ${new Date(q.deadline).toISOString()}`, { kind: 'proposal-question', questionId: q.id })
+ messages.push(...proposalNotices(state, card, 'needs-you', `${card.title}: ${q.question}`, sender, operationId,
+ currentSender(state, card, command.personId)))
+ } else if (command.type === 'proposal.decide') {
+ pending(card)
+ if (hasOpenQuestion(card)) fail('PROPOSAL_QUESTION_OPEN', 'Answer the open questions before deciding.', 409)
+ if (command.decision === 'later' && (!command.revisitAt || command.revisitAt <= now)) fail('PROPOSAL_DATE', 'Later needs a future revisit date.', 400)
+ if (command.decision === 'accept' || command.decision === 'reshape') {
+ if (!command.task || !command.checks?.length) fail('TASK_CONTRACT_MISSING', 'Accepted work needs its task and done-when checks.', 400)
+ card.task = command.task
+ card.brief = renderWorkTask(command.task)
+ card.briefAt = now
+ card.stepIds = []
+ card.checks = command.checks.map((check, i) => ({ id: stableId(operationId, 'check', String(i)), description: check.description, independent: check.independent ?? false, evidence: null, passedBy: null, verdicts: [] }))
+ stampLane(card)
+ recordAsked(card, card.requesterId, now)
+ }
+ card.proposal.decision = { kind: command.decision, reason: command.reason, at: now, by: sender.id,
+ ...(command.decision === 'later' ? { revisitAt: command.revisitAt } : {}) }
+ delete card.proposal.overdue
+ if (command.decision === 'no') card.archived = true
+ row(`${command.decision}: ${command.reason}`, { kind: 'proposal-decision', decision: command.decision })
+ messages.push(...proposalNotices(state, card, 'decided', `${card.title}: ${command.decision}. ${command.reason}`, sender, operationId))
+ } else {
+ pending(card)
+ const target = namedCard(state, actor, command.intoConversationId)
+ pending(target)
+ if (target.id === card.id) fail('PROPOSAL_MERGE_SELF', 'Merge another proposal into this card.', 400)
+ if (hasOpenQuestion(card)) fail('PROPOSAL_QUESTION_OPEN', 'Answer the source card’s questions before merging.', 409)
+ const senders = [...target.proposal.senders, ...card.proposal.senders].filter((s, i, all) =>
+ all.findIndex(p => p.personId === s.personId && p.generation === s.generation && p.buddyId === s.buddyId) === i)
+ const mergedFrom = [...new Set([...target.proposal.mergedFrom ?? [], card.id, ...card.proposal.mergedFrom ?? []])]
+ if (senders.length > MAX_CARD_SENDERS || mergedFrom.length > MAX_CARD_SENDERS) fail('PROPOSAL_LIMIT', 'A combined card holds at most 50 senders and merged cards.', 409)
+ for (const id of card.proposal.mergedFrom ?? []) {
+ const child = namedCard(state, actor, id)
+ if (child.proposal.mergedInto !== card.id) fail('PROPOSAL_MERGE_STALE', 'A merged card changed; read the cards again.', 409)
+ child.proposal.mergedInto = target.id
+ }
+ target.proposal.senders = senders
+ target.proposal.mergedFrom = mergedFrom
+ card.proposal.mergedInto = target.id
+ card.archived = true
+ row(`Merged into #${target.number}: ${command.reason}`, { kind: 'proposal-merged', intoConversationId: target.id })
+ messages.push({ id: stableId(operationId, 'merge-target'), conversationId: target.id, author: sender, text: `Merged #${card.number}: ${command.reason}`,
+ recipients: target.leadId ? [target.leadId] : [], replyTo: null, source: { kind: 'proposal-merged' } })
+ messages.push(...proposalNotices(state, target, 'decided', `${card.title} was merged into ${target.title}. ${command.reason}`, sender, operationId))
+ result.conversationId = target.id
+ }
+ return { messages, result }
+}
+
+/** Server-written sources are the only notices. A raw chat line never enters a switched PM's delivery queue. */
+export function pmAcceptsMessage(state: SuperTabState, recipientId: string, source: unknown): boolean {
+ const project = ledProject(state, recipientId)
+ return !project?.boardMode || !!source && typeof source === 'object' && typeof (source as { kind?: unknown }).kind === 'string'
+}
+
+/** Verified originals are supplied by the store in bounded primary-key batches. Keep every other ask owed. */
+export function migrateLegacyProposals(state: SuperTabState, project: SwarmProject, originals: LegacyProposalAsk[], now: number): MessageDraft[] {
+ const messages: MessageDraft[] = []
+ for (const ask of originals) {
+ const id = legacyProposalId(project.id, ask.messageId)
+ const existed = state.conversations.some(c => c.id === id)
+ importLegacyProposal(state, project, ask, now)
+ if (!existed) {
+ const card = state.conversations.find(c => c.id === id)!
+ messages.push(proposalRoot(state, card, stableId(id, 'root'), author(state, { kind: 'person', userId: ask.personId, email: '' })))
+ }
+ const original = state.conversations.find(c => c.id === ask.conversationId)!
+ original.owed = (original.owed ?? []).filter(a => a.id !== ask.messageId)
+ if (!original.owed.length) delete original.owed
+ }
+ return messages
+}
diff --git a/backend/src/superTabs/proposalClock.ts b/backend/src/superTabs/proposalClock.ts
new file mode 100644
index 000000000..85521af66
--- /dev/null
+++ b/backend/src/superTabs/proposalClock.ts
@@ -0,0 +1,62 @@
+/** Timed proposal transitions run in the existing singleton worker and the answering card's transaction. */
+import { author, stableId, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
+import { groupProject } from './projects.js'
+import { proposalNotices, type ProposalQuestion, type ProposalRecord } from './proposalCards.js'
+
+export const PROPOSAL_WAIT_MS = 30 * 60_000
+export type ProposalCard = Conversation & { proposal: ProposalRecord }
+export function proposalDueAt(proposal: ProposalRecord | undefined): number | null {
+ if (!proposal || proposal.mergedInto || proposal.decision?.kind === 'no') return null
+ if (proposal.decision?.kind === 'later') return proposal.decision.revisitAt ?? null
+ const times = proposal.questions.filter(q => !q.answer && !q.overdue).map(q => q.deadline)
+ if (!proposal.decision && !proposal.overdue) times.push((proposal.waitSince ?? proposal.createdAt) + PROPOSAL_WAIT_MS)
+ return times.length ? Math.min(...times) : null
+}
+function clockAuthor(state: SuperTabState, card: ProposalCard): Author {
+ const project = groupProject(state, card)
+ const pm = state.conversations.find(c => c.id === project.leadConversationId)?.leadId
+ const agent = pm && state.agents.find(a => a.id === pm)
+ if (agent) return author(state, { kind: 'agent', agentId: agent.id, machineOwnerId: agent.machineOwnerId })
+ // No PM is running: the server still records expiry and tells the current project owner, without impersonating a former PM.
+ const member = state.people.find(p => p.id === project.ownerId) ?? state.people.find(p => p.id === state.ownerId)!
+ return { kind: 'person', id: member.id, name: member.email, membershipGeneration: member.generation }
+}
+export function expireProposalQuestion(state: SuperTabState, card: ProposalCard, q: ProposalQuestion, now: number): MessageDraft[] {
+ if (q.answer || q.overdue || now < q.deadline) return []
+ const sender = clockAuthor(state, card), id = stableId(q.id, 'deadline')
+ if (q.requiresConsent) {
+ q.overdue = true
+ return proposalNotices(state, card, 'needs-you', `${card.title}: agreement is overdue. ${q.question}`, sender, id,
+ card.proposal.senders.filter(s => s.personId === q.personId))
+ }
+ q.answer = { text: q.defaultAnswer, at: q.deadline, by: 'default', defaulted: true }
+ return [{ id, conversationId: card.id, author: sender, text: q.defaultAnswer, recipients: card.leadId ? [card.leadId] : [], replyTo: null,
+ source: { kind: 'proposal-answer', questionId: q.id, defaulted: true, applied: true } }]
+}
+export function advanceProposalCards(state: SuperTabState, now: number): MessageDraft[] {
+ const messages: MessageDraft[] = []
+ for (const group of state.conversations) {
+ if (!group.proposal || group.proposal.mergedInto) continue
+ const card = group as ProposalCard, record = card.proposal, project = groupProject(state, card)
+ if (record.decision?.kind === 'later' && now >= record.decision.revisitAt!) {
+ const date = record.decision.revisitAt!
+ delete record.decision
+ record.waitSince = now
+ delete record.overdue
+ card.archived = false
+ messages.push({ id: stableId(card.id, 'revisit', String(date)), conversationId: card.id, author: clockAuthor(state, card), text: 'This proposal is due for another decision.',
+ recipients: card.leadId ? [card.leadId] : [], replyTo: null, source: { kind: 'proposal-card', priority: card.priority } })
+ }
+ for (const q of record.questions) messages.push(...expireProposalQuestion(state, card, q, now))
+ if (!record.decision && !record.overdue && now >= (record.waitSince ?? record.createdAt) + PROPOSAL_WAIT_MS) {
+ record.overdue = true
+ const owner = state.people.find(p => p.id === project.ownerId)
+ if (owner) {
+ const rows = proposalNotices(state, card, 'needs-you', `${card.title} has waited over 30 minutes for a PM decision.`, clockAuthor(state, card),
+ stableId(card.id, 'overdue', String(record.waitSince ?? record.createdAt)), [{ personId: owner.id, generation: owner.generation }])
+ messages.push(...rows.map(row => ({ ...row, source: { ...row.source, kind: 'proposal-overdue' } })))
+ }
+ }
+ }
+ return messages
+}
diff --git a/backend/src/superTabs/proposalDue.ts b/backend/src/superTabs/proposalDue.ts
new file mode 100644
index 000000000..e27245450
--- /dev/null
+++ b/backend/src/superTabs/proposalDue.ts
@@ -0,0 +1,12 @@
+import type { Prisma } from '@prisma/client'
+import { readBy } from './parts/indexed.js'
+
+/** One covered range for the singleton worker: old/dormant cards still keep their deadline. */
+export async function dueProposalCards(db: Prisma.TransactionClient, now: number, limit = 200): Promise<Array<{ tabId: string; key: string }>> {
+ const rows = await readBy(db, 'SwarmGroup', 'proposalDue', [
+ { $match: { deleted: false, proposalDueAt: { $gt: { $date: new Date(0).toISOString() }, $lte: { $date: new Date(now).toISOString() } } } },
+ { $sort: { proposalDueAt: 1, tabId: 1, key: 1 } }, { $limit: Math.max(1, Math.min(limit, 200)) },
+ { $project: { _id: 0, tabId: 1, key: 1 } },
+ ])
+ return rows.map(row => ({ tabId: row.tabId as string, key: row.key as string }))
+}
diff --git a/backend/src/superTabs/proposalMetrics.test.ts b/backend/src/superTabs/proposalMetrics.test.ts
new file mode 100644
index 000000000..d922cf21e
--- /dev/null
+++ b/backend/src/superTabs/proposalMetrics.test.ts
@@ -0,0 +1,11 @@
+import { expect, it } from 'vitest'
+import { metrics } from '../lib/metrics.js'
+import { proposalMeasures } from './proposalMetrics.js'
+
+it('counts only proposal events and bounded wait measures without identities or text', async () => {
+ proposalMeasures([{ event: 'decided', seconds: 90 }, { event: 'defaulted', seconds: 30 }])
+ const text = await metrics.registry.metrics()
+ expect(text).toContain('swarm_proposal_events_total{event="decided"} 1')
+ expect(text).toContain('swarm_proposal_wait_seconds_sum{event="decided"} 90')
+ expect(text).toContain('swarm_proposal_wait_seconds_count{event="defaulted"} 1')
+})
diff --git a/backend/src/superTabs/proposalMetrics.ts b/backend/src/superTabs/proposalMetrics.ts
new file mode 100644
index 000000000..4b1ebe35a
--- /dev/null
+++ b/backend/src/superTabs/proposalMetrics.ts
@@ -0,0 +1,34 @@
+import { Counter, Histogram } from 'prom-client'
+import { metrics } from '../lib/metrics.js'
+import type { MessageDraft, SuperTabState } from './model.js'
+
+type Event = 'created' | 'decided' | 'answered' | 'defaulted' | 'overdue' | 'revisited' | 'merged' | 'shipped'
+interface Measure { event: Event; seconds?: number }
+const events = new Counter({ name: 'swarm_proposal_events_total', help: 'Committed proposal transitions', labelNames: ['event'] as const, registers: [metrics.registry] })
+const waits = new Histogram({ name: 'swarm_proposal_wait_seconds', help: 'Proposal decision and answer waits', labelNames: ['event'] as const,
+ buckets: [1, 15, 60, 300, 900, 1800, 3600, 86400], registers: [metrics.registry] })
+
+/** Called after commit; retries and receipt replays contribute no event. No content or identity leaves the transaction. */
+export function proposalMeasures(values: Measure[]): void {
+ for (const value of values) {
+ events.inc({ event: value.event })
+ if (value.seconds !== undefined) waits.observe({ event: value.event }, Math.max(0, value.seconds))
+ }
+}
+export function proposalMessageMeasures(state: SuperTabState, messages: MessageDraft[], now: number): Measure[] {
+ return messages.flatMap<Measure>(m => {
+ if (m.source?.kind === 'proposal-overdue') return [{ event: 'overdue' }]
+ if (m.source?.kind === 'proposal-notice' && m.source.moment === 'shipped') return [{ event: 'shipped' }]
+ const record = state.conversations.find(c => c.id === m.conversationId)?.proposal
+ if (!record) return []
+ const source = m.source, kind = source?.kind
+ if (kind === 'proposal-card') return [{ event: record.waitSince ? 'revisited' : 'created' }]
+ if (kind === 'proposal-decision') return [{ event: 'decided', seconds: (now - (record.waitSince ?? record.createdAt)) / 1000 }]
+ if (kind === 'proposal-merged') return [{ event: 'merged' }]
+ if (kind === 'proposal-answer' && source?.applied) {
+ const q = record.questions.find(q => q.id === source.questionId)
+ return [{ event: source.defaulted ? 'defaulted' : 'answered', seconds: q ? (now - record.createdAt) / 1000 : undefined }]
+ }
+ return []
+ })
+}
diff --git a/backend/src/superTabs/releases.ts b/backend/src/superTabs/releases.ts
index 94b6618f8..b839690ab 100644
--- a/backend/src/superTabs/releases.ts
+++ b/backend/src/superTabs/releases.ts
@@ -1,3 +1,4 @@
+import { proposalNotices } from './proposalCards.js'
/**
* Releases scheduled by the Swarm (task #3405, anh Dee's Swarm redesign, 2026-11-05: the server does the routine). A merge
* recorded on a task puts it on its project's release list; the worker (releaseWatch.ts) reads GitHub for each component's
@@ -276,6 +277,15 @@ export function settleReleases(state: SuperTabState, projectId: string, facts: R
else delete group.releasing
}
+
+ if (lead) for (const id of new Set(outcome.shipped)) {
+ const group = state.conversations.find(c => c.id === id)
+ if (!group?.proposal || group.releasing) continue
+ const sender = { kind: 'agent' as const, id: lead.id, name: lead.name, membershipGeneration: lead.membershipGeneration }
+ outcome.messages.push(...proposalNotices(state, group as Conversation & { proposal: NonNullable<Conversation['proposal']> },
+ 'shipped', `${group.title} shipped.`, sender, stableId(group.id, 'shipped', String(group.released!.at))))
+ }
+
for (const component of RELEASE_COMPONENTS) {
const step = ledger.steps?.[component.id]
if (!step || !ended(state.conversations.find(c => c.id === step.groupId))) continue
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index d69782304..00272e846 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,3 +1,8 @@
+import { legacyAsks } from './boardRights.js'
+import { canReadProject } from './projects.js'
+import { proposalMeasures, proposalMessageMeasures } from './proposalMetrics.js'
+import { advanceProposalCards, pmAcceptsMessage, legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk } from './proposalCards.js'
+import { defaultBuddy } from './buddies.js'
import { refusalLogFields, type DeclaredClient } from './refusalLog.js'
import { applyCrewKeep, crewMoveRequest, crewNeedsMachine, type CrewDeps } from './crewKeep.js'
import { finishedWakes } from './crewTimes.js'
@@ -527,7 +532,7 @@ export interface Polled {
* it loaded: while all three are unchanged, a held delivery is answered without loading the Swarm (deliveries). The
* grants of the agent and of the agents that sent what it allowed, by agent id, are checked again on every such answer:
* they rest on Workspaces, machines and shares, which no Swarm write records. */
- open?: { stamp: number; seen: string[]; allowed: string[]; swarm: SwarmGrant; grants: Record<string, AgentGrant> }
+ open?: { prioritized?: boolean; stamp: number; seen: string[]; allowed: string[]; swarm: SwarmGrant; grants: Record<string, AgentGrant> }
}
/** Where `deliveries` remembers each caller's last full poll. Either call may throw: the poll then runs in full. */
@@ -964,6 +969,43 @@ export class SuperTabStore {
return { row, parts, state }
}
+ /** Only named, still-owed originals; deleted text, a former membership or a private audience never becomes a public card. */
+ private async legacyProposalBodies(tx: Transaction, state: SuperTabState, projectId: string): Promise<LegacyProposalAsk[]> {
+ const project = projectsOf(state).find(p => p.id === projectId)!
+ const asks = legacyAsks(state, project).slice(0, 100)
+ if (!asks.length) return []
+ const rows = await readBy(tx, 'SuperTabMessage', 'id', [
+ { $match: { tabId: state.id, _id: { $in: asks.map(a => a.messageId) }, deletedAt: null } },
+ { $project: { _id: 0, id: '$_id', conversationId: 1, author: 1, text: 1, source: 1 } },
+ ]) as unknown as Array<{ id: string; conversationId: string; author: Author; text: string; source?: unknown }>
+ return asks.flatMap(ask => {
+ const row = rows.find(r => r.id === ask.messageId), sender = row?.author as unknown as Author | undefined
+ const group = state.conversations.find(c => c.id === ask.conversationId)
+ const member = state.people.find(p => p.id === ask.personId)
+ if (!row || row.source || !row.text.trim() || row.text.length > 32000 || row.conversationId !== ask.conversationId
+ || !sender || sender.kind !== 'person' || sender.id !== ask.personId || sender.membershipGeneration !== member?.generation
+ || !group || group.kind || group.audience || !canReadGroup(state, { kind: 'person', userId: ask.personId, email: '' }, group)) return []
+ return [{ ...ask, text: row.text, generation: member!.generation }]
+ })
+ }
+
+ private async proposalNoticeParts(tx: Transaction, loaded: Loaded): Promise<Loaded> {
+ const groupIds: string[] = loaded.state.conversations.map(c => c.id), agentIds: string[] = []
+ for (const card of loaded.state.conversations) {
+ if (!card.proposal) continue
+ const project = groupProject(loaded.state, card)
+ for (const id of new Set([project.ownerId, ...card.proposal.senders.map(s => s.personId)])) {
+ const member = loaded.state.people.find(p => p.id === id)
+ if (member) groupIds.push(swarmBuddyChatId(member))
+ const fallback = defaultBuddy(loaded.state, id)
+ if (fallback) agentIds.push(fallback.id)
+ }
+ agentIds.push(...card.proposal.senders.flatMap(s => s.buddyId ? [s.buddyId] : []))
+ }
+ const named = await this.ensure(tx, loaded, { groupIds, agentIds })
+ return this.ensure(tx, named, { groupIds: listedBuddyChats(named.state) })
+ }
+
/** Loads again with more named groups, agents or starts when the first load lacks one a command needs. */
private async ensure(tx: Transaction, loaded: Loaded, named: Named): Promise<Loaded> {
const has = (ids: string[] | undefined, present: (id: string) => boolean) => (ids ?? []).every(present)
@@ -971,7 +1013,10 @@ export class SuperTabStore {
if (!named.allGroups && has(named.groupIds, id => state.conversations.some(c => c.id === id)) && has(named.startIds, id => !!state.starts?.some(s => s.id === id))
&& !named.agentIds?.length && !named.projectIds?.length && !named.startAgentIds?.length) return loaded
recordReload()
- return loadRow(tx, loaded.row, named)
+ // An additional named read must retain quiet groups already needed by this transaction, such as a proposal or merge source.
+ // Awake groups load automatically; only quiet keys need carrying through the next indexed read.
+ const groupIds = [...new Set([...named.groupIds ?? [], ...loaded.parts.groups.filter(g => g.dormant).map(g => g.key)])]
+ return loadRow(tx, loaded.row, { ...named, groupIds })
}
/** A Swarm with one start loaded even when finished, and the start's group even when dormant. */
@@ -1046,6 +1091,24 @@ export class SuperTabStore {
swarmChat(row.author.id)
}
}
+ if (command.type === 'project.boardMode' && command.on) {
+ const project = projectsOf(state).find(p => p.id === command.projectId)
+ if (project) groupIds.push(...legacyAsks(state, project).slice(0, 100).map(a => legacyProposalId(project.id, a.messageId)))
+ }
+ if (command.type === 'proposal.merge') {
+ groupIds.push(command.intoConversationId)
+ const card = state.conversations.find(c => c.id === command.conversationId)
+ groupIds.push(...card?.proposal?.mergedFrom ?? [])
+ }
+ if (command.type === 'proposal.decide' || command.type === 'proposal.ask' || command.type === 'proposal.answer' || command.type === 'proposal.merge') {
+ const cards = state.conversations.filter(c => c.id === command.conversationId || command.type === 'proposal.merge' && c.id === command.intoConversationId)
+ for (const card of cards) for (const identity of card.proposal?.senders ?? []) {
+ swarmChat(identity.personId)
+ if (identity.buddyId) agentIds.push(identity.buddyId)
+ const fallback = defaultBuddy(state, identity.personId)
+ if (fallback) agentIds.push(fallback.id)
+ }
+ }
// A proposal posts in the chat of the project it goes to, even quiet: the one a Swarm-wide Buddy names, else its session's.
if (command.type === 'buddy.propose') {
const self = asAgentId ? state.agents.find(a => a.id === asAgentId) : undefined
@@ -1083,6 +1146,17 @@ export class SuperTabStore {
/** Writes what changed between the loaded state and `next`, and touches the parts the change relied on. */
private async save(tx: Transaction, loaded: Loaded, next: SuperTabState, stamp: number, touches: Touch[] = []) {
+ const changedCards = next.conversations.filter(c => c.proposal && !isDeepStrictEqual(c.proposal, loaded.state.conversations.find(old => old.id === c.id)?.proposal))
+ // Timer/release transitions have no command actor: guard the same current rights that proposal commands guard.
+ if (changedCards.length) {
+ touches = [...touches, { kind: 'head', key: 'head' }]
+ for (const card of changedCards) {
+ touches.push({ kind: 'group', key: groupProject(next, card).leadConversationId })
+ for (const identity of card.proposal!.senders) {
+ if (loaded.state.people.some(p => p.id === identity.personId)) touches.push({ kind: 'member', key: identity.personId })
+ }
+ }
+ }
const committed = await commitParts(tx, loaded, next, { stamp, touches })
const told = this.hooks.hostsChanged
if (told && committed.hosts.length) afterCommit(tx, () => told({ tabId: loaded.parts.tabId, machineIds: committed.hosts, lastChangedAt: stamp }))
@@ -2061,6 +2135,7 @@ export class SuperTabStore {
const decisionId = command.type === 'route.override' || command.type === 'route.modelResult' ? command.decisionId
: command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined
if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
+ if (command.type === 'project.boardMode' && command.on) context.legacyProposals = await this.legacyProposalBodies(tx, original, command.projectId)
const effects = applyCommand(original, actor, command, context)
hasWorkers = effects.state.agents.some(a => !isBuddy(a) && !ledProject(effects.state, a.id))
// An agent-only notice changes nothing people see: no link, no unread mark, no project report.
@@ -3499,6 +3574,8 @@ export class SuperTabStore {
const kept = new Set(stored.filter(row => messages.some(m => m.id === row.id && row.tabId === tabId && row.conversationId === m.conversationId
&& isDeepStrictEqual(row.source ?? undefined, m.source))).map(row => row.id))
if (kept.size) logger.warn('Kept Swarm notices already stored', { tabId, ids: [...kept] })
+ const measured = proposalMessageMeasures(state, messages.filter(m => !kept.has(m.id)), this.now())
+ if (measured.length) afterCommit(tx, () => proposalMeasures(measured))
const rows: Prisma.SuperTabMessageCreateManyInput[] = []
let deliveries: Prisma.SuperTabDeliveryCreateManyInput[] = []
for (const message of messages) {
@@ -3510,6 +3587,7 @@ export class SuperTabStore {
thread: message.thread ?? message.id, ...(message.alsoInChat ? { alsoInChat: true } : {}),
...(message.buddySession ? { buddySession: true } : {}), ...(message.buddyProject ? { buddyProject: message.buddyProject } : {}) })
for (const recipient of [...message.recipients, ...message.buddyRecipients ?? []]) {
+ if (!pmAcceptsMessage(state, recipient, message.source)) continue
const target = agent(state, recipient)
const group = conversation(state, message.conversationId)
// Written as ever, so its readers see the message at once; only its coordinator's delivery waits for the digest (noticeDigest.ts).
@@ -3518,7 +3596,7 @@ export class SuperTabStore {
const forInbox = gathersForInbox(state, target, message)
const gathered = (gatheredMessage(state, message) && !!ledProject(state, recipient)) || forInbox
deliveries.push({ id: stableId(message.id, recipient), tabId,
- conversationId: message.conversationId, messageId: message.id, agentId: recipient, machineId: target.machineId,
+ conversationId: message.conversationId, messageId: message.id, inputPriority: group.proposal ? Number((group.priority ?? 'P2').slice(1)) : 1, agentId: recipient, machineId: target.machineId,
machineOwnerId: target.machineOwnerId,
assignmentId: activeWork(group) && group.assignment?.agentId === recipient ? group.assignment.id : null,
membershipGeneration: target.membershipGeneration, authorKind: message.author.kind,
@@ -4509,12 +4587,33 @@ export class SuperTabStore {
? { kind: 'person', userId: delivery.authorId, email: '' }
: { kind: 'agent', agentId: delivery.authorId, machineOwnerId: (sender as Agent).machineOwnerId }
// A private conversation's sender and receiver must still be in its audience or be its Lead (projects.ts canReadGroup).
- if (!canReadGroup(state, actor, group)) return false
+ if (!canReadGroup(state, actor, group) && !isBuddyChat(group)) return false
const generation = 'generation' in sender ? sender.generation : sender.membershipGeneration
- return generation === delivery.authorGeneration && (!('role' in sender) || sender.role !== 'viewer')
+ return generation === delivery.authorGeneration && (!('role' in sender) || sender.role !== 'viewer' || !!group.proposal)
}
- private async senderAllowed(tx: Transaction, state: SuperTabState, delivery: SuperTabDelivery): Promise<boolean> {
+ private async senderAllowed(tx: Transaction, state: SuperTabState, delivery: SuperTabDelivery, knownSource?: unknown): Promise<boolean> {
+ const group = state.conversations.find(c => c.id === delivery.conversationId)
+ const sender = delivery.authorKind === 'person' ? state.people.find(p => p.id === delivery.authorId) : state.agents.find(a => a.id === delivery.authorId)
+ if (!group || !sender) return false
+ const actor: Actor = delivery.authorKind === 'person' ? { kind: 'person', userId: delivery.authorId, email: '' }
+ : { kind: 'agent', agentId: delivery.authorId, machineOwnerId: (sender as Agent).machineOwnerId }
+ const outsideChat = !canReadGroup(state, actor, group)
+ if (ledProject(state, delivery.agentId)?.boardMode || outsideChat) {
+ const source = knownSource === undefined
+ ? (await tx.superTabMessage.findUnique({ where: { id: delivery.messageId }, select: { source: true } }))?.source : knownSource
+ if (!pmAcceptsMessage(state, delivery.agentId, source)) return false
+ if (outsideChat) {
+ // A server-written proposal notice may enter its person's private Buddy chat without giving its author read access.
+ const notice = source as { kind?: string; projectId?: string } | null
+ const project = projectsOf(state).find(p => p.id === notice?.projectId)
+ const target = state.agents.find(a => a.id === delivery.agentId)
+ if (!isBuddyChat(group) || !target || !isBuddy(target) || !project
+ || !['proposal-notice', 'proposal-overdue'].includes(notice?.kind ?? '')
+ || !canReadProject(state, actor, project)
+ || !canReadProject(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }, project)) return false
+ }
+ }
if (delivery.nativeContextId && !await this.native.allowsDelivery(tx, state, delivery.nativeContextId)) return false
if (delivery.authorKind !== 'agent') return true
try { await this.agentGrant(tx, state, agent(state, delivery.authorId)); return true }
@@ -4538,7 +4637,7 @@ export class SuperTabStore {
// whose gathered rows are due (inboxDue) skips the fast answer, by one indexed read.
const releasing = turn !== undefined && inboxDue(await agentGatheredDeliveries(this.db, tabId, agentId, NOTICE_DIGEST_MAX), this.now(), turn)
if (!releasing && last !== undefined && this.now() - last.at < SWEEP_EVERY_MS) {
- const open = await openDeliveries(this.db, tabId, agentId)
+ const open = await openDeliveries(this.db, tabId, agentId, last.open?.prioritized)
if (!open.length) return []
// A held delivery stays open for as long as its host cannot type it, possibly hours, polled each second (Diego, 10-28):
// the same open deliveries at the same main stamp are allowed as the full poll found them. Anything a Swarm write
@@ -4552,7 +4651,7 @@ export class SuperTabStore {
const view = await this.view([tabId]), stamp = view.mainStamp(tabId)
const { open, allowed, state } = await this.fullDeliveries(user, tabId, agentId, view, turn)
await this.polls.set(key, { at: this.now(), ...open.length && stamp !== undefined
- ? { open: { stamp, seen: open.map(d => d.id), allowed: allowed.map(d => d.id), ...grantsOf(state, agentId, allowed) } } : {} })
+ ? { open: { prioritized: !!ledProject(state, agentId)?.boardMode, stamp, seen: open.map(d => d.id), allowed: allowed.map(d => d.id), ...grantsOf(state, agentId, allowed) } } : {} })
.catch(pollMemoryFailed)
return allowed.map(d => withTurnEnd(d, this.now()))
}
@@ -4575,7 +4674,8 @@ export class SuperTabStore {
if (!seen.allowed.includes(delivery.id)) continue
if (delivery.authorKind !== 'agent' || seen.grants[delivery.authorId] && await sent(delivery.authorId)) allowed.push(delivery)
}
- return allowed
+ const order = new Map(seen.allowed.map((id, i) => [id, i]))
+ return allowed.sort((a, b) => order.get(a.id)! - order.get(b.id)!)
}
private async fullDeliveries(user: AuthUser, tabId: string, agentId: string, view: CacheView, turn?: 'idle' | 'busy') {
@@ -4792,12 +4892,24 @@ export class SuperTabStore {
/** The agent's open deliveries, and those of them its Swarm still lets reach it. */
private async allowedDeliveries(tx: Transaction, state: SuperTabState, tabId: string, agentId: string) {
- const open = await openDeliveries(tx, tabId, agentId)
+ const open = await openDeliveries(tx, tabId, agentId, !!ledProject(state, agentId)?.boardMode)
+ // One bounded primary-key batch, rather than a source lookup for every queued PM input or private Buddy notice.
+ const needsSources = !!ledProject(state, agentId)?.boardMode || open.some(d => isBuddyChat(state.conversations.find(c => c.id === d.conversationId) ?? { kind: undefined } as Conversation))
+ const sources = needsSources && open.length ? new Map((await readBy(tx, 'SuperTabMessage', 'id', [
+ { $match: { tabId, _id: { $in: open.map(d => d.messageId) } } }, { $project: { _id: 1, source: 1 } },
+ ])).map(m => [m._id as string, m.source ?? null])) : null
const allowed: SuperTabDelivery[] = []
for (const delivery of open) {
- if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)) allowed.push(delivery)
+ if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery, sources?.get(delivery.messageId) ?? (sources ? null : undefined))) allowed.push(delivery)
+ }
+ if (ledProject(state, agentId)?.boardMode) {
+ const rank = (d: SuperTabDelivery) => {
+ const card = state.conversations.find(c => c.id === d.conversationId)
+ return card?.proposal ? Number((card.priority ?? 'P2').slice(1)) : 1
+ }
+ allowed.sort((a, b) => rank(a) - rank(b))
}
- return { open, allowed, state }
+ return { open, allowed: allowed.slice(0, 100), state }
}
/** A withdrawn host can retire its own journal without regaining shared
@@ -5322,7 +5434,8 @@ export class SuperTabStore {
const head = (await tx.swarmHead.findUnique({ where: { id: `${tabId}:head` }, select: { data: true } }))?.data as { projects?: SwarmProject[] } | undefined
const ledger = head?.projects?.find(p => p.id === projectId)?.releases
if (!ledger) return null
- const loaded = await loadRow(tx, requireParts(row), { groupIds: ledgerGroupIds(ledger) })
+ let loaded = await loadRow(tx, requireParts(row), { groupIds: ledgerGroupIds(ledger) })
+ loaded = await this.proposalNoticeParts(tx, loaded)
const state = cloneData(loaded.state)
const before = JSON.stringify(projectsOf(loaded.state).find(p => p.id === projectId)?.releases)
// The project's rules record as it reads now: its saved window, pace and backend pause, or the seed until one is saved.
@@ -5344,17 +5457,26 @@ export class SuperTabStore {
* hours). Whatever they find is recorded in this same write, so a second run, or one racing it, finds nothing new. The
* messages written.
*/
- async runTimeChecks(tabId: string): Promise<number> {
+ async runTimeChecks(tabId: string, dueCards: string[] = []): Promise<number> {
return transaction(this.db, async tx => {
const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
if (!row || row.deletedAt || row.format !== 2) return 0
- let loaded = await loadRow(tx, requireParts(row), {})
+ let loaded = await loadRow(tx, requireParts(row), { groupIds: dueCards })
+ const migration = new Map<string, LegacyProposalAsk[]>()
+ for (const project of projectsOf(loaded.state).filter(p => p.boardMode)) {
+ const bodies = await this.legacyProposalBodies(tx, loaded.state, project.id)
+ if (bodies.length) migration.set(project.id, bodies)
+ }
+ if (migration.size) loaded = await this.ensure(tx, loaded, { groupIds: [...dueCards,
+ ...[...migration].flatMap(([id, bodies]) => bodies.map(a => legacyProposalId(id, a.messageId)))] })
+ loaded = await this.proposalNoticeParts(tx, loaded)
// A task its sweep may lose says Stuck in its project chat's thread (taskLine.ts endedReply, task #2693).
const chats = taskLineChats(loaded.state)
- if (chats.length) loaded = await this.ensure(tx, loaded, { groupIds: chats })
+ if (chats.length) loaded = await this.ensure(tx, loaded, { groupIds: [...loaded.state.conversations.map(c => c.id), ...chats] })
const state = cloneData(loaded.state), now = this.now()
const rulesFor = await this.projectDispatch(tx, state)
- const written = sweepForLead(state, now, rulesFor)
+ const written = [...sweepForLead(state, now, rulesFor), ...advanceProposalCards(state, now)]
+ for (const [id, bodies] of migration) written.push(...migrateLegacyProposals(state, projectsOf(state).find(p => p.id === id)!, bodies, now))
// What waits for each agent: an agent with a delivery open is not idle. Only loaded groups' active work keeps an agent
// from being idle (project instructions, phase 4).
const projects = projectsOf(state).filter(p => state.conversations.find(c => c.id === p.leadConversationId)?.leadId)
diff --git a/backend/src/superTabs/taskQueue.ts b/backend/src/superTabs/taskQueue.ts
index 1994a3d41..e182cd1fb 100644
--- a/backend/src/superTabs/taskQueue.ts
+++ b/backend/src/superTabs/taskQueue.ts
@@ -17,7 +17,7 @@ export const queueOrder = <T extends Queued>(tasks: readonly T[]): T[] =>
/** The tasks a project's Next up orders: open, never its chat, a Buddy chat, a private chat or a step. */
export function queueSiblings(state: SuperTabState, project: SwarmProject): Conversation[] {
- return state.conversations.filter(c => !c.archived && !c.kind && !c.audience && !c.reviewOf && c.id !== project.leadConversationId
+ return state.conversations.filter(c => (!c.proposal || ['accept', 'reshape'].includes(c.proposal.decision?.kind ?? '')) && !c.archived && !c.kind && !c.audience && !c.reviewOf && c.id !== project.leadConversationId
&& groupProject(state, c).id === project.id)
}
diff --git a/backend/src/superTabs/timeChecks.ts b/backend/src/superTabs/timeChecks.ts
index 023fd4459..c2649cd65 100644
--- a/backend/src/superTabs/timeChecks.ts
+++ b/backend/src/superTabs/timeChecks.ts
@@ -1,3 +1,4 @@
+import { dueProposalCards } from './proposalDue.js'
// The Swarm's time checks run in the singleton worker (task #3385, anh Dee's Swarm redesign, 11-05): lost and stalled work,
// failed starts and idle agents are found and told to each project's PM whether or not the PM is up. They ran only on the
// PM's own poll before: on 11-05 a hung PM left five people's asks unanswered for 3 to 10 hours and the board showed nothing
@@ -25,7 +26,8 @@ export async function owedAsk(db: Pick<PrismaClient, 'superTabDelivery'>, tabId:
{ $sort: { createdAt: 1 } },
{ $limit: 1 },
{ $project: { _id: 0, messageId: 1, createdAt: 1 } },
- ] }) as unknown as Array<{ messageId: string; createdAt: { $date: string } | string }>
+ // Proposal priority must not split the chronological range used to find the oldest unanswered ask.
+ ], options: { hint: { tabId: 1, agentId: 1, status: 1, createdAt: 1 } } }) as unknown as Array<{ messageId: string; createdAt: { $date: string } | string }>
if (!row) return null
const at = typeof row.createdAt === 'string' ? row.createdAt : row.createdAt.$date
return { messageId: row.messageId, since: Date.parse(at) }
@@ -64,7 +66,11 @@ export type TimeCheckMemory = Map<string, { at: string; checkedAt: number }>
* not checked for QUIET_CHECK_MS. One Swarm's failure is logged and skips that Swarm alone, and it is checked again next pass. */
export async function runTimeCheckPass(db: PrismaClient, store: Pick<SuperTabStore, 'runTimeChecks'>, now: number, limit = TIME_CHECK_SWARMS,
seen: TimeCheckMemory = new Map()) {
- const rows = await timeCheckCandidates(db, now, limit)
+ const due = await dueProposalCards(db, now, limit)
+ const dueByTab = new Map<string, string[]>()
+ for (const row of due) dueByTab.set(row.tabId, [...dueByTab.get(row.tabId) ?? [], row.key])
+ const recent = await timeCheckCandidates(db, now, limit)
+ const rows = [...[...dueByTab.keys()].map(tabId => ({ tabId, at: `due:${now}` })), ...recent.filter(r => !dueByTab.has(r.tabId))].slice(0, limit)
const pass = { swarms: rows.length, checked: 0, written: 0, failed: 0 }
const listed = new Set(rows.map(row => row.tabId))
for (const tabId of seen.keys()) if (!listed.has(tabId)) seen.delete(tabId)
@@ -73,7 +79,7 @@ export async function runTimeCheckPass(db: PrismaClient, store: Pick<SuperTabSto
if (last && last.at === at && now - last.checkedAt < QUIET_CHECK_MS) continue
pass.checked++
try {
- pass.written += await store.runTimeChecks(tabId)
+ pass.written += await store.runTimeChecks(tabId, dueByTab.get(tabId))
seen.set(tabId, { at, checkedAt: now })
} catch (error) {
pass.failed++
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 1052e6405..b1e3344c6 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,6 +1,6 @@
import { defineConfig } from 'vitest/config'
-export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
+export default defineConfig({ test: { include: ['integration/superTabProposalCards.test.ts', 'integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
'integration/superTabRead.test.ts', 'integration/superTabOneGroup.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabMessageEdits.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',
'integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts',
'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabMachineLiveness.test.ts', 'integration/superTabHeldParts.test.ts',
diff --git a/docs/plans/2026-11-06-buddy-board-final-spec.md b/docs/plans/2026-11-06-buddy-board-final-spec.md
index c07414904..b790dbf68 100644
--- a/docs/plans/2026-11-06-buddy-board-final-spec.md
+++ b/docs/plans/2026-11-06-buddy-board-final-spec.md
@@ -73,16 +73,23 @@ The fix is to split the two jobs:
## The Task Board
-What a person sees when they select a project. Five columns **[merge]** (Ken's; today's Board has Proposals, Next up, Working, Waiting, Shipped: Waiting folds into
-Working with a mark, and Merged is new):
+What a person sees when they select a project. Six columns **(Ken's decision, 2026-11-06, replacing the five)**; each
+column is one place where work waits, so where cards pile up is where the flow is stuck:
-| Column | Holds |
-|---|---|
-| Proposal | Proposals the PM has not decided yet, and those waiting on an answer from their sender |
-| Next | Accepted work not started yet, in priority order |
-| Working | Work being done, and work waiting (on review, test, CI, a person, a decision), marked on the card |
-| Merged | Merged, not yet released |
-| Shipped | Released |
+| Column | A card is here when | On the card |
+|---|---|---|
+| Proposal | the PM hasn't decided, or it waits on its sender's answer | who proposed and through which Buddy; an open question with its default and time |
+| Next up | accepted, not started | priority, in order |
+| Working | being done, including review, test, and waiting on a person or CI | one mark for where it is: in review, testing, waiting on X, CI red |
+| Done | review and test passed and the PR is green, waiting to merge; also finished work with no code | "waiting to merge" and for how long, turning to a warning past 1 hour so a merge bottleneck shows |
+| Merged | on main, waiting for a release | when the next release is due |
+| Shipped | in a release people have | the version (for example Desktop 1.3.84); leaves the Board after 7 days for the history |
+
+- A task with several PRs (backend and Desktop, say) sits in the column of its slowest PR; it is Shipped only when every
+ part is.
+- A proposal decided Later leaves Proposal and comes back on its date; one decided No goes to the history with its reason.
+- A project with no repository (GTM, research) shows four columns: Proposal → Next up → Working → Done.
+- Each column shows its count; "Mine" filters to the reader's cards.
On each card a person can see:
- the proposal's words, who proposed it, and through which Buddy;
@@ -116,7 +123,7 @@ work.
+- left (hide/show) ---+ +- harness . Board -----------------------------------------+ +- right (hide/show) ------+
| autonomous.ai v | | Needs you: 2 Search Mine Lane v | | (*) Code ( ) Planning |
| Decisions | | | | [+ New Buddy] |
-| Mentions | | PROPOSAL NEXT WORKING MERGED SHIPPED | |--------------------------|
+| Mentions | | PROPOSAL NEXT UP WORKING DONE MERGED SHIPPED | |--------------------------|
| | | +-------+ +-------+ +-------+ +------+ +------+ | | the selected Buddy's |
| Projects | | |[CLI] | |[Desk] | |[back] | |#3628 | |#3607 | | | chat (the person's main |
| > harness | | |title | |#3765 | |#3747 | | | |1.3.84| | | chat), or a clicked |
@@ -157,6 +164,19 @@ work.
If the Buddy that sent a proposal has been removed, its messages go to the person's default Buddy.
+## Who can write in the project chat *(Ken, 2026-11-06)*
+
+The Chat tab stays, and writing in it is a per-project right:
+- By default only the project owner (and the Swarm owner) can write in the project chat; everyone else reads it.
+- The project owner grants "Can chat" to a person in Project settings → People, and can take it back.
+- Without it, a person still does everything else: their Buddies, proposals, the card's chat of tasks they take part
+ in, answering what is asked of them. Agents write as today.
+- The server enforces it, not just the app, so older apps can't write either.
+- This replaces "the PM chat becomes read-only after the switch": the chat stays open to the owner and the people
+ granted.
+- Why not the existing roles: they are Swarm-wide, set only when inviting (no command changes a role later), and
+ `viewer` refuses every write in the whole Swarm (READ_ONLY, model.ts:1040), Buddies and proposals included.
+
## Steering and teaching the PM without chat
| A person wants to | They |
@@ -215,7 +235,8 @@ Until they have any Buddy, they can propose straight from the Board.
when it is ready.
- **[merge]** Desktop first, today (anh Dee: "focus on building desktop only, ship desktop asap"); phone and web follow
on the same spec, so in the end a person sees the same Board and the same Buddies on each.
-- The history of a switched project's chat with the PM stays readable, but nobody can write in it.
+- A switched project's chat stays readable to all and writable by the owner and the people granted "Can chat" (see
+ "Who can write in the project chat").
- When a project switches on, every message to the PM still unanswered becomes a proposal on the Board, under its
author's name, so nothing is dropped. When it switches back, undecided proposals stay open and the PM answers them
in the chat as today.
@@ -245,9 +266,11 @@ chat and that rule is dropped.
- any person may set any priority today (coordinatorOrPerson, commands.ts:728) and there is no pause command: the
server enforces priority and pause rights by role, and gains pause and resume;
- only crew members sleep (crewRules.ts): idle Buddies sleep and wake on their person or their proposal;
+ - a per-project "Can chat" right (Ken): owner and Swarm owner by default, granted and revoked by the project
+ owner in Project settings → People, enforced by the server on every app;
- the built-in "Swarm process v2" text (pmSchedule.ts:17-22) is one text for all projects: it follows each project's
switch, so a switched project's PM gets no inbox or answer-each-message lines.
-2. Desktop: Merged column and Waiting folded into Working; decision, question and "needs you" on the card; Needs you
+2. Desktop: the six columns (Ken) with Done's waiting-to-merge timer and warning; Project settings → People with the "Can chat" grant; the Chat tab read-only without it; decision, question and "needs you" on the card; Needs you
bar; propose from the Board; priority and pause by role; + New Buddy and Buddy list.
3. Phone and web: the same Board and Buddies.
4. Instructions and the PM: drop the chat rules (answer in threads, inbox, owed asks) for a project once it switches.
diff --git a/docs/plans/2026-11-06-proposal-cards-plan.md b/docs/plans/2026-11-06-proposal-cards-plan.md
new file mode 100644
index 000000000..c43f855ad
--- /dev/null
+++ b/docs/plans/2026-11-06-proposal-cards-plan.md
@@ -0,0 +1,109 @@
+# Proposal cards implementation plan
+
+> Native implementation, task by task, test first. One independent review of the complete change by each of two security Reviewers.
+
+**Goal:** Give switched projects durable proposal cards, PM decisions, timed questions and duplicate merging, with server-enforced person and Buddy rights.
+
+**Architecture:** Embed a bounded `Conversation.proposal` in the existing SwarmGroup card, retaining the card when accepted work becomes a task. Commands use the existing transactional receipts, version guards and changed-part feed. A due-time column/index lets the existing singleton time-check worker find questions and deferred proposals even after long inactivity.
+
+**Tech Stack:** TypeScript, Zod, Prisma/MongoDB, Vitest, existing Super Tab parts and delivery workers; no dependency.
+
+**Spec:** [Approved Buddy/Board spec](2026-11-06-buddy-board-final-spec.md), Phase 2, proposal/backend portion of #3817. #3818 owns multiple/default Buddies; #3819 owns project switch, migration orchestration, Board delta API, chat grants and priority/pause rights.
+
+## Global Constraints
+
+- Only projects with `boardMode === true` use new proposal entry and PM input rules. Switching back preserves cards and legacy chat behavior.
+- Identity is the consenting person and membership generation plus sending Buddy id, never the machine owner. Preserve existing exact-word consent and attachment checks.
+- Every current member, including viewers, may propose and answer questions addressed to them. Only the current project PM decides, asks or merges. Only entitled people originate P0/hotfix proposals.
+- Decisions and answers are recorded once. A late answer is visible but does not replace an applied answer/default. Explicit person consent never defaults.
+- Use indexed bounded reads, existing changed-part delivery and per-card transaction guards (plus existing head guard for shared rights); no whole-Board polling.
+- Run affected unit/importer tests locally. Full backend and four integration shards run in PR CI. Never touch a real CLI sign-in.
+- Before Ready, record failing-test commits and observed red/green evidence in a PR comment. Require two independent security reviews.
+
+## Design
+
+- **Growth:** Each card has at most 20 questions and 50 proposers/merged cards; refuse overflow rather than discard history. Proposal text fields and evidence are bounded. Full discussion/decision history uses existing message rows, never an unbounded embedded log. Declined and merged cards are archived/history immediately; shipped cards retain the existing seven-day Board/history policy. Card history remains until project/Swarm deletion, as existing tasks do.
+- **Concurrency:** Version-guard the card, both cards of a merge and its flattened merged sources, the current membership and project/coordinator rights. Existing operation receipts make retries once-only. Revisit clears the current Later decision but its message remains in history. Proposal commands retain the existing Swarm head guard to serialize project rights with membership changes; timer writes guard changed cards and the relevant current members/coordinator.
+- **Read cost:** Single named-card lookups use the existing unique key index; bounded merged source lookups use that same index. PM gets new proposal/answer messages through existing deliveries, in priority order. Optional `SuperTabDelivery.inputPriority` plus `[tabId,agentId,status,inputPriority,createdAt]` supports the first 100 prioritized rows even beyond an old backlog; union with the oldest 100 supports old rows without that field. Filter current rights before returning at most 100 inputs; source authorization reads up to 200 message ids in one primary-key batch. Existing part changes expose metadata to clients. Due work uses a bounded `proposalDueAt` range, including dormant cards; no scan of cards or messages.
+- **Scale:** Bounds stay fixed at ten times the people. Record counts and decision/answer wait durations without content or ids. Pending proposals carry a due time; the owner sees an overdue mark on the card and a needs-you notice. The indexed worker batch and elapsed metrics expose lag.
+- **Compatibility:** Extend JSON metadata/commands; existing clients ignore optional metadata. No new conversation kind. Legacy buddy.propose keeps its old schema/meaning unless the destination is switched; switched proposals must supply why/doneWhen/evidence. Rollout switch is owned by #3819. Switching back restores ordinary chat and old proposal creation; decisions, answers and clocks for already stored cards continue so rollback does not strand questions.
+- **Migration/rollback:** Export `importLegacyProposal(state, project, ask, now)` where ask is `{messageId,conversationId,personId,text,at,generation?}`. Stable project/message-derived card id is idempotent; migration must load that id before writing and clear the old ask only after creating it. It preserves original words as a legacy proposal and does not fabricate consent or missing details. The store wires it to #3819’s switch and worker: read at most 100 still-owed originals by message id, verify their original author generation, public project audience and unchanged words, and leave missing/inaccessible asks owed. No invented author/body or message-body read from the snapshot. Reverting the switch leaves cards intact; reverting the backend leaves optional data readable and the due index harmless.
+- **Audience/identity:** Current project membership checked before receipt replay and before application; merged proposers retain generation-bound identities. Buddy answers require the sender identity on that card (or its person's current default after removal) and a question to that person; no arbitrary card posting or foreign-project reads. Viewer exceptions apply only to these commands.
+- **Failure:** Named refusals for missing inputs, stale membership, duplicate decisions/answers, bounds and unavailable Buddy routing. At the proposal deadline mark overdue and notify the current owner, once. Explicit-consent deadlines mark overdue without answering. Worker failures use existing logged retry behavior.
+- **Platforms:** Server-only Linux runtime; contract consumed by Desktop macOS/Windows/Linux, web, iOS and Android. No process or UI changes.
+- **Storage/index scope:** Optional `SwarmGroup.proposalDueAt` and `[deleted,proposalDueAt,tabId,key]` support dormant timers; optional `SuperTabDelivery.inputPriority` and its index support bounded urgent delivery. Both use existing collection lifecycles (card history retained; delivery TTL unchanged). These columns/indexes in backend/prisma/schema.prisma are the only storage additions; all domain code remains under backend/src/superTabs. No new collection or production data write in implementation.
+
+## Review Focus
+
+1. Membership removal/rejoin and private-project revocation must remove card rights, even for an idempotent retry or queued delivery.
+2. Buddy consent must not authorize new private text or another Buddy's card; fallback only follows a removed sender of the same person.
+3. Question expiry racing an answer must produce one effective answer, while a later answer remains visible; explicit-consent asks cannot auto-answer.
+4. Duplicate merging must retain every proposer's attribution/notices without cycles, cross-project links or abandoned questions.
+5. Quiet projects and deferred dates beyond seven days must still wake; rollback must not eat legacy asks or leak ordinary chat to the switched PM.
+
+## Task 1: Create durable, authorized proposal cards
+
+**Files:** Create `backend/src/superTabs/proposalCards.ts` and `proposalCards.test.ts`; modify `model.ts`, `projects.ts`, `commands.ts`, `parts/light.ts`, `taskQueue.ts`, `dispatch.ts` as needed to keep undecided cards out of task dispatch.
+
+**Interfaces:** `ProposalRecord` on `Conversation.proposal`; `proposal.create {projectId,title,text,goal,why,doneWhen,evidence,priority}` for people; extend `buddy.propose` with why/doneWhen/evidence and P0–P3/hotfix priorities on switched projects only. `importLegacyProposal(state,project,ask,now): string` and `legacyProposalId(projectId,messageId): string`. New card ids are stable from command operation ids. `boardMode?: true` is shared with #3819.
+
+- [x] Write/commit tests that create a card as a member/viewer, preserve consenting Buddy identity/exact words, reject incomplete and unauthorized/private/P0 proposals, and preserve legacy output when not switched. Assert no task dispatch before acceptance. Test stable legacy import without inventing structured content.
+- [x] Run `cd backend && npm test -- src/superTabs/proposalCards.test.ts`; observe feature failures.
+- [x] Implement schema/domain and command integration with bounded metadata and the existing task card/change feed. Use the shared owner/top-decider P0 rule from #3819 when available; keep its identical semantics otherwise.
+- [x] Run that test and affected Buddy/queue/dispatch/light tests, then typecheck; commit fix and push.
+
+## Task 2: Decisions, scoped questions and duplicate merge
+
+**Files:** Modify `proposalCards.ts`, `proposalCards.test.ts`, `commands.ts`, `buddies.ts`, `buddyNews.ts`, `parts/touches.ts`.
+
+**Interfaces:** `proposal.decide {conversationId,decision:accept|reshape|later|no,reason,task?,checks?,revisitAt?}`; accept/reshape require the accepted task contract and checks. `proposal.ask {conversationId,personId,question,defaultAnswer,deadline,requiresConsent?}`; `proposal.answer {conversationId,questionId,text}`; `proposal.merge {conversationId,intoConversationId,reason}`. `applyProposalCommand` mutates the transaction state and returns MessageDrafts/result. Use #3818's `buddyFor(state,person,senderBuddyId)` for notices and generation-safe fallback.
+
+- [x] Write/commit tests for all four decisions/reasons, same-card task conversion, duplicate decision refusal, PM-only rights, own-card Buddy answers, viewer answers, removed sender fallback, late/second answers, merge attribution/cycle/cross-project/overflow guards and notifications to every proposer.
+- [x] Run focused tests; observe red.
+- [x] Implement command handlers, narrow Buddy exception, per-card/member/coordinator guards and notices only for decided/needs-you/shipped. Store full history in card messages; flatten duplicate links in one bounded transaction.
+- [x] Run focused tests and affected authorization/Buddy/news/touches tests, typecheck; commit fix and push.
+
+## Task 3: Timers, persistence and PM delivery boundary
+
+**Files:** Modify `proposalCards.ts`, `proposalCards.test.ts`, `store.ts`, `timeChecks.ts`, `parts/write.ts`, `parts/light.ts`, `parts/indexed.ts`, `backend/prisma/schema.prisma`; add focused unit and real-store integration tests under `backend/integration/`.
+
+**Interfaces:** `proposalDueAt(record): number|null`; `advanceProposalCards(state,now): MessageDraft[]`; bounded `dueProposalCards(db,now,limit)` by the due index. Worker loads due cards/chats by named ids. Store commandGroups loads source/canonical/merged/Buddy chats by id, including dormant. PM input policy accepts proposal roots, answers and server notices only when switched; recheck on claim and viewer sender policy. Extend existing privacy-safe metrics with proposal event/wait values.
+
+- [x] Write/commit tests for default-at-deadline exactly once, explicit consent, answer/expiry conflict, Later reentry, overdue owner notice, due cards after long inactivity/dormancy, persistence/delta visibility, revoked rights on receipt replay and delivery, ordinary chat suppressed only when switched, priority delivery ordering and index explain bounds.
+- [x] Run focused unit/integration files; observe red.
+- [x] Implement the timer and command/delivery loading paths with bounded indexed reads; maintain the due column on every card write. Keep existing worker and transaction retry behavior.
+- [x] Run focused unit/importer tests and specific real-store integrations plus typecheck; record query explain and same-workload before/after cost. Commit fix and push.
+
+## Finish
+
+- [x] Wire/test #3819 migration boundary once both helpers exist, without dropping asks. Keep dependency changes explicit in the PR.
+- [x] Add red/green, validation/platform/index evidence in the PR; mark ready; preserve head during CI/review.
+- [ ] Set task review status with exact head and PR. Two different security Reviewers independently review rights/legacy isolation. Fix Important/Critical findings test first; set done once reviews pass, with exact revision/evidence.
+
+## Implementation evidence
+
+- Task 1: tests `fe18324f4` failed 8/passed 4 before implementation `69a280f03`; 179 affected units and typecheck passed after.
+- Task 2: tests `637980493` failed 10/passed 12 before `78dd776e8`; 600 affected units and typecheck passed after.
+- Task 3: `751db914b` failed 5/passed 22 units; `6c18e1b20` failed 1/passed 2 integrations. Additional viewer/manual assignment, shipped-notice, notice-delivery and metric failures precede implementation `cedb46698`.
+- Shared switch migration: `3dc6c014a` failed 1/passed 6 integrations before `f2d9499ec`; all 7 passed after. P0 past 100-row backlog: `0fcaefdd3` failed 1/passed 7 before `fefb7acca`. Undecided manual start: `ed3159124` failed 1/passed 31 units before `58da9b468`.
+- Merged main at `b9c1a79c0`, #3819 at `34aae323d`, #3818 at `f5960398b`. Combined affected verification: 776 units in 16 files, 9 real-store checks in 2 files, and typecheck passed. The new multiple-Buddy overlap then had 2 observed behavior failures at `896fba119` (quiet card unavailable; overdue notice sent to wrong chat), fixed by `1555a55c5`.
+- Due query explain uses covered `IXSCAN { deleted: 1, proposalDueAt: 1, tabId: 1, key: 1 }`. Priority backlog read uses its intended index: 100 keys/docs/rows returned from 107 waiting rows.
+- Same workload, isolated Mongo, 100 source authorizations: per-row baseline 100 queries / 49.588 ms; primary-key batch 1 query / 1.167 ms, 100 keys/docs/returned. This is a source-read comparison, not a full-request latency claim.
+- Production statistics could not be collected: this Team environment has no read-only production environment file. Release owner must collect collection/index sizes and CPU/latency before/after the authorized schema release; no production writes performed here.
+
+- Final overlap verification at `1555a55c5`: 66 real-store checks across proposal cards, command loading and Swarm Buddy flows; 169 focused proposal/Buddy units; typecheck passed. Full component suites and all four integration shards remain PR CI responsibilities.
+- CI index repair after `f014e0915`: shard 2 passed 600 tests but its existing oldest-unanswered-delivery plan guard failed because Mongo chose the new priority index. The same focused test failed locally (2 documents, 3 keys, 1 row). Keep the worker on its existing chronological index with an aggregate hint, preserving the query, schema and rights. The original committed guard predates this fix; its new key bound also rejects a scan beyond the two recent rows plus one boundary key per unanswered status. Green: 39 real-store tests across worker plans, time checks and proposal cards, plus typecheck. The repaired query examines at most 2 documents and 7 keys in the same fixture; no production latency claim. No full local suite or manual CI run.
+
+## Security review repairs
+
+**Files:** `commands.ts`, `proposalCards.ts`, `proposalCards.test.ts`, `integration/superTabBuddies.test.ts`, `integration/superTabProposalCards.test.ts`.
+
+**Interfaces:** Keep validated Buddy attachments on the proposal root and optional bounded scope in its record. Return that root's message id so the existing attachment transaction consumes each upload once. Report excluded PM recipients in `message.send` results before delivery-dependent bookkeeping; preserve other recipients, server notices and unswitched behavior. No new query, index or collection.
+
+- [x] Commit and observe the lost-file/scope unit regression and real-store file-opening regression before code.
+- [x] Preserve files, scope and root id. Green: 34 proposal units and 3 real-store file flows (switched, legacy and expired uploads). Red unit `7c72f04bf`; red integration `8088bca73` failed because persisted attachments were absent.
+- [x] Commit and observe missing-delivery-feedback regressions for person, agent and partial recipients before code. Red `5a77e456c`: 3 unit cases lacked feedback; real-store regression (setup correction `8b4535537`) failed on the same absent feedback.
+- [x] Compute feedback from final recipients; run affected units, real-store proposal flows and typecheck. Green: 665 affected units across six files; 10 existing real-store proposal cases and the new sender/partial-delivery case passed. The worker fixture was corrected to post from its task (the project chat does not admit idle workers); its reply to a PM question now passes. Test-helper typing corrected; 37 proposal units and backend typecheck pass. No new query/index/storage lifecycle or production permission change.
+- [ ] Push one repair head including CI fixture repair, request focused independent re-reviews and platform confirmation.
+
+CI fixture repair `47da5780a`: nine automatic integration failures were expired reset holds fixed at 2026-11-06T09:00Z. Reproduced the phone needs-human case failing with HOLD_REASON_MISSING before replacing all 13 resets with each fixture clock plus its original interval. Green: 58 affected checks across seven integration files, then 10 host-attention/Stuck checks across two of those files. Full local suite and manual CI were not run.