The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-07 kH: #3345 #3346 #3357 #3392 #3487 #3432 #3326 (#3527)
0xken15c33c6f094f77
diff --git a/backend/integration/overdueDecisions.test.ts b/backend/integration/overdueDecisions.test.tsindex 2df5ad767..ef8f268f9 100644--- a/backend/integration/overdueDecisions.test.ts+++ b/backend/integration/overdueDecisions.test.ts@@ -268,3 +268,90 @@ describe('decisions left to the PM after 24 hours', () => {expect(OVERDUE_DECISION_MS).toBe(DAY)})})++// Task #3826: in a switched project an agent asks the person directly, always with a default and a time. Past the time the+// default applies, unless the ask says the person must agree: then it waits for them, and the PM is told once.+describe('a switched project’s direct asks at their default time', () => {+ const at = (delta: number) => new Date(NOW + delta).toISOString()++ /** A switched project with its PM and a worker on a task, asking peer directly; `ask` dates the decision `age` ago. */+ async function direct() {+ const f = await swarm()+ const app = (await f.execute({ type: 'project.create', name: 'App', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }+ await f.execute({ type: 'project.boardMode', projectId: app.projectId, on: true })+ const add = async (name: string, lead: boolean) => String((await f.execute({ type: 'agent.add', conversationId: app.conversationId, machineId: 'owner-mac',+ harnessId: randomUUID(), name, configuration: config, lead })).result.agentId)+ const pm = await add('Lead', true)+ const worker = await add('Builder', false)+ const task = String((await f.execute({ type: 'conversation.create', projectId: app.projectId, title: 'Copy', brief: '', checks: [] })).result.conversationId)+ await f.execute({ type: 'conversation.agent', conversationId: task, agentId: worker, present: true, lead: false })+ const ask = async (age: number, extra: Record<string, unknown>) => {+ const asked = await new SuperTabStore(db, () => NOW - age).execute(owner, f.tab, { operationId: randomUUID(), command: { type: 'decision.ask', conversationId: task,+ personId: peer.sub, questions: [{ question: `Ship how ${randomUUID()}?`, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release', ...extra }] } as Command }, worker)+ const id = String((asked.result.decisionIds as string[])[0])+ await db.superTabDecision.update({ where: { id }, data: { createdAt: new Date(NOW - age) } })+ return id+ }+ const told = async (id: string, agentId: string) => (await f.store.messages(owner, f.tab, task, {}, agentId)).messages+ .filter(m => (m.source as { decisionId?: string } | null)?.decisionId === id && m.recipientIds.includes(agentId))+ return { ...f, pm, worker, task, ask, told }+ }++ it('notifies the default Buddy only once when decision.ask repeats an open question', async () => {+ const f = await direct()+ const chat = String((await f.execute({ type: 'buddy.chat' }, peer)).result.conversationId)+ const command: Command = { type: 'decision.ask', conversationId: f.task, personId: peer.sub,+ questions: [{ question: 'Ship this copy?', options: ['Yes', 'No'], recommended: 0, unblocks: 'Release', defaultAt: at(HOUR) }] }+ const first = await f.execute(command, owner, f.worker)+ const repeated = await f.execute(command, owner, f.worker)+ expect(repeated.result.decisionIds).toEqual(first.result.decisionIds)+ const lines = (await f.store.messages(peer, f.tab, chat, {})).messages.filter(m => (m.source as { kind?: string })?.kind === 'decision-asked')+ expect(lines).toHaveLength(1)+ expect(lines[0]!.source).toMatchObject({ decisionId: (first.result.decisionIds as string[])[0] })+ })++ it.each([false, true])('keeps a changed agreement requirement distinct (original mustAgree: %s)', async firstMustAgree => {+ const f = await direct()+ const question = { question: 'Authorize the release?', options: ['Yes', 'No'], recommended: 0, unblocks: 'Release', defaultAt: at(HOUR) }+ const ask = async (mustAgree: boolean) => (await f.execute({ type: 'decision.ask', conversationId: f.task, personId: peer.sub,+ questions: [{ ...question, ...(mustAgree ? { mustAgree: true as const } : {}) }] }, owner, f.worker)).result.decisionIds as string[]+ const first = await ask(firstMustAgree)+ const changed = await ask(!firstMustAgree)+ expect(changed).not.toEqual(first)+ expect((await f.row(changed[0]!)).mustAgree === true).toBe(!firstMustAgree)+ })++ it('never tells the person the PM can take over a required agreement', async () => {+ const f = await direct()+ const id = await f.ask(HOUR, { defaultAt: at(0), mustAgree: true })+ const row = (await f.store.decisions(peer, f.tab, 'open')).decisions.find(d => d.id === id)!+ expect(row.pmTakesOver).toBe(false)+ })++ it('applies the recommendation at its time, and the asking agent hears it', async () => {+ const f = await direct()+ const id = await f.ask(HOUR, { defaultAt: at(0) })+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 1, skipped: 0, failed: 0 })+ expect(await f.row(id)).toMatchObject({ choice: 0, delegated: true, defaulted: true })+ expect(await f.told(id, f.worker)).toHaveLength(1)+ })++ it('waits for a person who must agree: the PM is told once, no later pass or the 24-hour sweep answers, and the person still can', async () => {+ const f = await direct()+ const id = await f.ask(HOUR, { defaultAt: at(0), mustAgree: true })+ expect(await f.row(id)).toMatchObject({ mustAgree: true })+ // Not answered: the sweep skips it, once.+ expect(await f.store.leaveOverdueDecisions(NOW)).toEqual({ answered: 0, skipped: 1, failed: 0 })+ expect(await f.row(id)).toMatchObject({ answeredAt: null, choice: null, defaulted: null })+ const pmTold = await f.told(id, f.pm)+ expect(pmTold).toHaveLength(1)+ expect(pmTold[0]).toMatchObject({ source: { kind: 'decision-must-agree' } })+ expect(pmTold[0]!.text).not.toContain('To everyone')+ expect(await f.store.leaveOverdueDecisions(NOW + 1)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ expect(await new SuperTabStore(db, () => NOW + 2 * DAY).leaveOverdueDecisions(NOW + 2 * DAY)).toEqual({ answered: 0, skipped: 0, failed: 0 })+ expect(await f.told(id, f.pm)).toHaveLength(1)+ expect((await f.store.decisions(peer, f.tab, 'open')).decisions.map(d => d.id)).toContain(id)+ await f.execute({ type: 'decision.answer', decisionId: id, choice: 1 }, peer)+ expect(await f.row(id)).toMatchObject({ choice: 1, delegated: null })+ })+})diff --git a/backend/integration/superTabNoticeDigest.test.ts b/backend/integration/superTabNoticeDigest.test.tsindex 8b27976a1..84da280b8 100644--- a/backend/integration/superTabNoticeDigest.test.ts+++ b/backend/integration/superTabNoticeDigest.test.ts@@ -886,35 +886,33 @@ describe('the PM\'s inbox at its turn\'s end', () => {const listed = async (f: Awaited<ReturnType<typeof swarm>>, turn?: 'idle' | 'busy') =>(await f.timed.deliveries(host, f.tab, f.lead, turn) as Array<{ messageId: string }>).map(d => d.messageId)- it('waits while the PM works, then goes in one inbox when its turn ends, under New from people', async () => {+ it('delivers people and thread follow-ups while the PM works, keeping agent notices batched', async () => {const f = await swarm({ capable: true })await f.report()+ const notice = await f.write({ kind: 'work-stalled' }, f.lead)const message = await ask(f, 'Is the parser release out yet?')- expect((await deliveryOf(message, f.lead)).status).toBe('gathered')- expect(await listed(f, 'busy')).not.toContain(message)+ const followup = String((await f.execute({ type: 'message.send', conversationId: 'lead', text: 'And the next build?', replyTo: message, recipientIds: [] })).result.messageId)+ expect((await deliveryOf(message, f.lead)).status).toBe('queued')+ expect(await listed(f, 'busy')).toEqual(expect.arrayContaining([message, followup]))+ expect((await deliveryOf(notice, f.lead)).status).toBe('gathered')expect(await inboxes(f.tab)).toEqual([])- f.clock.now += MIN- expect(await listed(f, 'idle')).not.toContain(message)- const [inbox] = await inboxes(f.tab)- expect(inbox).toContain('New from people (1)')- expect(inbox).toContain('Is the parser release out yet?')- expect((await deliveryOf(message, f.lead)).status).toBe('digested')- // Its next idle read writes no second inbox.- await listed(f, 'idle')- expect(await inboxes(f.tab)).toHaveLength(1)+ // Delivery is not an answer: the later notice inbox lists these again as owed.+ f.clock.now += 16 * MIN+ await f.report()+ await listed(f, 'busy')+ expect((await inboxes(f.tab)).join('\n')).toContain(`message ${message} in lead`)+ expect((await inboxes(f.tab)).join('\n')).toContain(`message ${followup} in lead`)})- it('goes after 15 minutes of one long turn', async () => {+ it('releases people gathered by the previous server on the first busy poll without releasing notices', async () => {const f = await swarm({ capable: true })await f.report()const message = await ask(f, 'Still there?')- f.clock.now += 14 * MIN- await listed(f, 'busy')+ await db.superTabDelivery.update({ where: { id: stableId(message, f.lead) }, data: { status: 'gathered', inboxSection: 'people' } })+ const notice = await f.write({ kind: 'work-stalled' }, f.lead)+ expect(await listed(f, 'busy')).toContain(message)+ expect((await deliveryOf(notice, f.lead)).status).toBe('gathered')expect(await inboxes(f.tab)).toEqual([])- f.clock.now += 2 * MIN- await listed(f, 'busy')- expect((await inboxes(f.tab)).join('\n')).toContain('Still there?')- expect((await deliveryOf(message, f.lead)).status).toBe('digested')})it('goes at once in the same read when the read sends no turn: an older host is unchanged', async () => {@@ -947,9 +945,9 @@ describe('the PM\'s inbox at its turn\'s end', () => {await listed(f, 'idle')expect(await inboxes(f.tab)).toHaveLength(1)// A person's message at idle goes in the next read, with no wait.- await ask(f, 'One more thing.')- await listed(f, 'idle')- expect((await inboxes(f.tab)).at(-1)).toContain('One more thing.')+ const message = await ask(f, 'One more thing.')+ expect(await listed(f, 'idle')).toContain(message)+ expect(await inboxes(f.tab)).toHaveLength(1)})it('lists a crew need under Crew needs, with its options', async () => {@@ -964,3 +962,44 @@ describe('the PM\'s inbox at its turn\'s end', () => {expect(inbox).toContain('Ship on Friday or Monday? Options: Friday / Monday (recommended)')})})++// #3609: receipt means the native session accepted input; listing, claiming and uncertain input do not.+describe('PM person receipt eyes', () => {+ it('adds eyes only on confirmed receipt, once, without answering or hiding the owed ask', async () => {+ const f = await swarm({ capable: true })+ await f.report()+ const message = String((await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Is it out?', replyTo: null, recipientIds: [] })).result.messageId)+ const id = stableId(message, f.lead)+ const eyes = () => db.superTabReaction.findMany({ where: { tabId: f.tab, messageId: message, emoji: 'eyes' } })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'claim', claimId: 'receipt' })+ expect(await eyes()).toEqual([])+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'receipt', receipt: 'unknown', uncertain: true })+ expect(await eyes()).toEqual([])+ const before = await f.timed.messages(owner, f.tab, 'lead', {})+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'receipt', receipt: 'native input', uncertain: false })+ expect(await eyes()).toEqual([expect.objectContaining({ actorKind: 'agent', actorId: f.lead })])+ const after = await f.timed.messages(owner, f.tab, 'lead', {})+ expect(after.reactionSeq).toBe(before.reactionSeq + 1)+ expect(after.messages.find(m => m.id === message)?.reactions).toContainEqual({ emoji: 'eyes', count: 1, by: [{ kind: 'agent', id: f.lead }] })+ await f.timed.delivery(host, f.tab, f.lead, id, { type: 'ack', claimId: 'receipt', receipt: 'native input', uncertain: false })+ expect(await eyes()).toHaveLength(1)+ expect((await f.timed.messages(owner, f.tab, 'lead', {})).reactionSeq).toBe(after.reactionSeq)+ expect((await deliveryOf(message, f.lead)).status).toBe('delivered')+ expect((await deliveryOf(message, f.lead)).answeredAt).toBeNull()+ const state = await f.timed.read(owner, f.tab)+ expect(state.state.conversations.find(c => c.id === 'lead')?.owed?.map(a => a.id)).toContain(message)+ })++ it('does not add eyes for worker receipts or agent-authored input to the PM', async () => {+ const f = await swarm({ capable: true })+ await f.report()+ const person = String((await f.execute({ type: 'message.send', conversationId: f.group, text: 'Check this.', replyTo: null, recipientIds: [f.worker] })).result.messageId)+ const notice = await f.write({ kind: 'prompt' }, f.lead)+ for (const [message, agent] of [[person, f.worker], [notice, f.lead]]) {+ const id = stableId(message!, agent!)+ await f.timed.delivery(host, f.tab, agent!, id, { type: 'claim', claimId: 'ordinary' })+ await f.timed.delivery(host, f.tab, agent!, id, { type: 'ack', claimId: 'ordinary', receipt: 'native input', uncertain: false })+ expect(await db.superTabReaction.findMany({ where: { tabId: f.tab, messageId: message } })).toEqual([])+ }+ })+})diff --git a/backend/integration/superTabScorecard.test.ts b/backend/integration/superTabScorecard.test.tsindex b9a4bab2b..9cf1805c7 100644--- a/backend/integration/superTabScorecard.test.ts+++ b/backend/integration/superTabScorecard.test.ts@@ -108,6 +108,7 @@ describe('the nightly scorecard', () => {expect(row).toMatchObject({ tabId: f.tab, projectId: 'lead', on: '2026-11-05', timeZone: 'Asia/Ho_Chi_Minh' })expect(row!.figures as unknown as ScorecardFigures).toMatchObject({asksShipped: 1, askToShipMedianMinutes: 180,+ pmAnswer: { count: 1, medianSeconds: 600, slowestSeconds: 600 },unansweredAsks: 1, oldestUnansweredAskMinutes: 17 * 60,// 02:00-03:00 the task waited for its agent; from 06:00 the second one waits to midnight.idleMinutes: 60 + 18 * 60,diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex fa385a34f..4b93d51ff 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -26,7 +26,7 @@ import { SEED_RULES } from '../src/superTabs/policy.js'import { stableId, type Agent, type SuperTabState } from '../src/superTabs/model.js'import { agentDisplayName } from '../src/superTabs/agentNames.js'import { roleVersion } from '../src/superTabs/projects.js'-import { ensureTerminalExpiry, TERMINAL_EXPIRY_MS } from '../src/superTabs/terminal.js'+import { ensureTerminalExpiry, TERMINAL_EXPIRY_MS, TERMINAL_RECHECK_MS } from '../src/superTabs/terminal.js'import { ensureMentionExpiry, MENTION_EXPIRY_MS, swarmsWithTags } from '../src/superTabs/mentions.js'import * as parts from '../src/superTabs/parts/index.js'import { swarmTransaction } from '../src/superTabs/cache.js'@@ -2066,6 +2066,30 @@ describe('Super Tabs on a real Mongo replica set', () => {.rejects.toMatchObject({ code: 'INVALID_ANSWER' })})+ it('a PM reaction settles the joke and question in durable owed state without an extra reply', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const sent = async (text: string) => String((await run(tab, { type: 'message.send', conversationId: 'lead', text,+ replyTo: null, recipientIds: [lead] }, peer)).result.messageId)+ const joke = await sent('The PM has more tabs than my browser 😂')+ const question = await sent('Are we collecting tabs now?')+ const react = (messageId: string, emoji: string, on = true, as = lead) => run(tab,+ { type: 'message.react', conversationId: 'lead', messageId, emoji, on } as Command, host, as)+ const owed = async () => (await store.read(owner, tab)).state.conversations.find(c => c.id === 'lead')!.owed?.map(a => a.id) ?? []+ expect(await owed()).toEqual([joke, question])+ await run(tab, { type: 'message.react', conversationId: 'lead', messageId: joke, emoji: 'laugh', on: true }, peer)+ await react(joke, 'laugh', false)+ expect(await owed()).toEqual([joke, question])+ await react(joke, 'laugh')+ expect(await owed()).toEqual([question])+ await react(question, 'eyes')+ await react(question, 'eyes')+ const restarted = new SuperTabStore(db)+ const chat = (await restarted.read(owner, tab)).state.conversations.find(c => c.id === 'lead')!+ expect(chat.owed ?? []).toEqual([])+ expect(chat.pulse!.asks.count).toBe(0)+ })+// Task #3391: acknowledging is a reaction, not a post, so a reaction settles the recipient's delivery as an answer does.it('closes the reacting agent\'s own deliveries of a message as answered, and nobody else\'s', async () => {const { tab, lead } = await fixture()@@ -3972,6 +3996,35 @@ describe('the Lead reads and types in an agent terminal', () => {return { at, loads: () => load.mock.calls.length, listeners: (requestId: string) => notices.listenerCount(requestId) }}+ /** The wait's re-checks (store.ts terminalResult, every TERMINAL_RECHECK_MS), held while a test sets up its answer, then run+ * for their whole period: an answer that comes while none has fired was woken by its notice, however slow the runner (task+ * #4308: a 100 ms wall-clock bound failed at 154 ms on a busy CI runner). `asleep` settles once the wait sleeps on one. */+ function heldRechecks() {+ const realSet = globalThis.setTimeout, realClear = globalThis.clearTimeout+ const held = new Map<object, { run: () => void; timer?: ReturnType<typeof realSet> }>()+ let released = false, fired = 0, sleeping = () => {}+ const asleep = new Promise<void>(resolve => { sleeping = resolve })+ const start = (handle: object, entry: { run: () => void; timer?: ReturnType<typeof realSet> }) => {+ entry.timer = realSet(() => { held.delete(handle); fired++; entry.run() }, TERMINAL_RECHECK_MS)+ }+ const set = vi.spyOn(globalThis, 'setTimeout').mockImplementation(((run: (...args: unknown[]) => void, ms?: number, ...args: unknown[]) => {+ if (ms !== TERMINAL_RECHECK_MS) return realSet(run, ms, ...args)+ const handle = {}, entry = { run: () => run(...args) }+ held.set(handle, entry)+ if (released) start(handle, entry)+ sleeping()+ return handle+ }) as typeof setTimeout)+ const clear = vi.spyOn(globalThis, 'clearTimeout').mockImplementation(((handle?: object) => {+ const entry = handle && held.get(handle)+ if (!entry) return realClear(handle as ReturnType<typeof realSet>)+ held.delete(handle)+ if (entry.timer) realClear(entry.timer)+ }) as typeof clearTimeout)+ onTestFinished(() => { set.mockRestore(); clear.mockRestore() })+ return { asleep, release: () => { released = true; for (const [handle, entry] of held) start(handle, entry) }, fired: () => fired }+ }+it('waits for an answer without loading the Swarm again and again', async () => {const { tab, lead, worker, claim } = await terminalFixture()const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as string@@ -3987,13 +4040,14 @@ describe('the Lead reads and types in an agent terminal', () => {const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as stringexpect(await claim()).toHaveLength(1)const { at, loads } = watched()- const waiting = at.terminalResult(host, tab, requestId, lead, 20_000).then(answer => ({ answer, at: Date.now() }))- await new Promise(resolve => setTimeout(resolve, 300))+ const rechecks = heldRechecks()+ const waiting = at.terminalResult(host, tab, requestId, lead, 20_000)+ await rechecks.asleepawait at.execute(host, tab, { operationId: randomUUID(), command: { type: 'agent.screenResult', requestId, ok: true, text: 'screen' } }, worker)- const answeredAt = Date.now()- const { answer, at: returnedAt } = await waiting- expect(answer).toEqual({ requestId, ok: true, text: 'screen' })- expect(returnedAt - answeredAt).toBeLessThan(100)+ rechecks.release()+ expect(await waiting).toEqual({ requestId, ok: true, text: 'screen' })+ // Woken by the commit's notice: no re-check ran, so the answer did not wait for one.+ expect(rechecks.fired()).toBe(0)expect(loads()).toBeLessThanOrEqual(4)})@@ -4035,12 +4089,14 @@ describe('the Lead reads and types in an agent terminal', () => {const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as stringexpect(await claim()).toHaveLength(1)const { at, loads } = watched({ heard: false })+ const rechecks = heldRechecks()const waiting = at.terminalResult(host, tab, requestId, lead, 20_000)- await new Promise(resolve => setTimeout(resolve, 300))+ await rechecks.asleepawait run(tab, { type: 'agent.screenResult', requestId, ok: true, text: 'screen' }, host, worker)- const answeredAt = Date.now()+ rechecks.release()expect(await waiting).toEqual({ requestId, ok: true, text: 'screen' })- expect(Date.now() - answeredAt).toBeLessThan(6_000)+ // The one re-check after the answer found it.+ expect(rechecks.fired()).toBe(1)expect(loads()).toBeLessThanOrEqual(3)})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex ff6d7977d..ad21b3abd 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1118,6 +1118,8 @@ model SuperTabMessage {/// Files posted with the message (superTabs/attachments.ts); the bytes live in the attachments bucket.attachments Json?replyTo String?+ /// Explicit answer below a message in main chat; kept with the message, without opening a thread (#3609).+ answers String?recipientIds String[]/// People a Lead tagged (superTabs/mentions.ts); absent on older rows.mentions String[]@@ -1369,6 +1371,9 @@ model SuperTabDecision {defaultAt DateTime?/// The server applied the recommendation at defaultAt; never a person’s choice or a legacy overdue answer.defaulted Boolean?+ /// A rule says the person must agree (task #3826): no default applies. At defaultAt the PM is told once and defaultAt is+ /// cleared, and the 24-hour sweep never takes it, so it waits for the person. Absent on every other decision.+ mustAgree Boolean?unblocks StringcreatedAt DateTimeansweredAt DateTime?diff --git a/backend/src/superTabs/agentNew.test.ts b/backend/src/superTabs/agentNew.test.tsindex 2a7ac1d15..128ef33e4 100644--- a/backend/src/superTabs/agentNew.test.ts+++ b/backend/src/superTabs/agentNew.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'-import type { ContributedMachine } from './machines.js'+import { AGENT_MEMORY_BYTES, type ContributedMachine } from './machines.js'import { createSuperTab, SuperTabError, type Actor, type SuperTabState } from './model.js'import { agentKind } from './agentKind.js'import { hostTab } from './read/hostRows.js'@@ -71,6 +71,12 @@ describe('+ New agent, Regular', () => {expect((f.state.projects ?? []).filter(p => p.id !== 'lead')).toHaveLength(0)})+ it('asks an agent\'s memory, not a Buddy\'s smaller one: it takes tasks (#3738)', () => {+ const f = swarm()+ const made = f.add({ kind: 'regular', name: 'Ada' })+ expect(f.state.starts!.find(s => s.id === made.result.startId)!.request.requirements.memoryBytes).toBe(AGENT_MEMORY_BYTES)+ })+it('once started, is a Regular agent in its own chat', () => {const f = swarm()const made = f.add({ kind: 'regular', name: 'Ada' })diff --git a/backend/src/superTabs/asksThroughBuddy.test.ts b/backend/src/superTabs/asksThroughBuddy.test.tsnew file mode 100644index 000000000..4deb0ea4e--- /dev/null+++ b/backend/src/superTabs/asksThroughBuddy.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest'+import { openSwarmBuddyChat, swarmBuddyChatId } from './buddies.js'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { crewNeedOf } from './crewNeeds.js'+import { createSuperTab, type Actor, type Agent, type MessageDraft } from './model.js'++// Task #3826 (Phase 2 of the Buddy board spec, "When an agent needs a person"): in a switched project an agent asks the person+// directly, never through the PM: the question reaches their default Buddy and their Needs you list (their open decisions),+// always with a default and a time. A project not switched keeps "people talk only to the PM" (crewNeeds.test.ts).++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }+const asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'owner' })+const NOW = 1_000_000+const defaultAt = new Date(NOW + 60 * 60_000).toISOString()+const choices = { options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' }++function fixture(switched: boolean) {+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let next = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { operationId: `op${next++}`, now: NOW,+ contribution: { machineOwnerId: 'owner', contributorId: actor.kind === 'person' ? actor.userId : 'owner' }, ...context })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ const app = run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }+ if (switched) run({ type: 'project.boardMode', projectId: app.projectId, on: true })+ const add = (harnessId: string, lead: boolean) => run({ type: 'agent.add', conversationId: app.conversationId, harnessId, machineId: 'machine',+ name: harnessId, lead, configuration }).result.agentId as string+ const pm = add('pm', true)+ const worker = add('worker', false)+ const group = run({ type: 'conversation.create', projectId: app.projectId, title: 'Copy', brief: '', checks: [] }).result.conversationId as string+ run({ type: 'conversation.agent', conversationId: group, agentId: worker, present: true, lead: false })+ const assignmentId = run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string+ // Peer's one Buddy, in their main Buddy chat: their default (buddies.ts defaultBuddy).+ const member = state.people.find(p => p.id === 'peer')!+ const buddy = { id: 'peer-buddy', machineId: 'machine', harnessId: 'peer-buddy-harness', machineOwnerId: 'peer', contributorId: 'peer',+ membershipGeneration: member.generation, name: 'Peer Buddy', configuration, buddyOf: { personId: 'peer', generation: member.generation }, buddyScope: 'swarm' } as Agent+ state.agents.push(buddy)+ openSwarmBuddyChat(state, member).agentIds.push(buddy.id)+ return { run, app, pm, worker, group, assignmentId, buddyChat: swarmBuddyChatId(member), get state() { return state } }+}++const needs = (effects: { messages: MessageDraft[] }) => effects.messages.filter(m => crewNeedOf(m.source))+const statusRow = (effects: { messages: MessageDraft[] }) => effects.messages.find(m => (m.source as { status?: string } | null)?.status === 'needs_human')!++describe('in a switched project, an agent’s ask reaches the person through their Buddy', () => {+ it('opens the person’s decision for a needs_human, writes the question to their default Buddy, and sends nothing to the PM', () => {+ const f = fixture(true)+ const sent = f.run({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'needs_human',+ result: 'Ship to everyone, or behind a flag?', ask: { personId: 'peer', ...choices, defaultAt } }, asAgent(f.worker))+ expect(sent.decisions).toEqual([expect.objectContaining({ personId: 'peer', question: 'Ship to everyone, or behind a flag?', defaultAt, recommended: 0 })])+ expect(needs(sent)).toEqual([])+ expect(sent.result.routedToPm).toBeUndefined()+ // The PM sees the task waiting on peer, and is not told the question.+ expect(statusRow(sent).recipients).not.toContain(f.pm)+ expect(f.state.conversations.find(c => c.id === f.group)!.assignment!.askedOf).toBe('peer')+ const line = sent.messages.filter(m => m.conversationId === f.buddyChat)+ expect(line).toEqual([expect.objectContaining({ recipients: ['peer-buddy'], buddyProject: f.app.projectId,+ source: { kind: 'decision-asked', decisionId: sent.decisions![0]!.id, projectId: f.app.projectId } })])+ expect(line[0]!.author).toMatchObject({ kind: 'agent', id: f.worker })+ expect(line[0]!.text).toContain('Ship to everyone, or behind a flag?')+ expect(line[0]!.text).toContain('Behind a flag (recommended)')+ expect(line[0]!.text).toContain(defaultAt)+ expect(sent.messages.filter(m => m.recipients.includes(f.pm))).toEqual([])+ })++ it('opens the person’s decisions for a decision.ask, one Buddy line each, and no crew need', () => {+ const f = fixture(true)+ const questions = [{ question: 'Ship how?', ...choices, defaultAt }, { question: 'Which copy?', options: ['Short', 'Long'], recommended: 1, unblocks: 'Copy', defaultAt }]+ const asked = f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer', questions }, asAgent(f.worker))+ expect(asked.decisions?.map(d => d.question)).toEqual(['Ship how?', 'Which copy?'])+ expect(asked.result.decisionIds).toHaveLength(2)+ expect(needs(asked)).toEqual([])+ expect(asked.result.routedToPm).toBeUndefined()+ expect(asked.messages.filter(m => m.conversationId === f.buddyChat).map(m => (m.source as { decisionId: string }).decisionId)).toEqual(asked.result.decisionIds)+ })++ it('tells the person that a required agreement never applies a default', () => {+ const f = fixture(true)+ const asked = f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer',+ questions: [{ question: 'Authorize the release?', ...choices, defaultAt, mustAgree: true }] }, asAgent(f.worker))+ const line = asked.messages.find(m => m.conversationId === f.buddyChat)!+ expect(line.text).toContain('No default applies')+ expect(line.text).toContain(defaultAt)+ expect(line.text).not.toContain('if not answered: Behind a flag')+ })++ it('refuses an ask with no default time, saying what to add', () => {+ const f = fixture(true)+ expect(() => f.run({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'needs_human',+ result: 'Ship how?', ask: { personId: 'peer', ...choices } }, asAgent(f.worker))).toThrow(/defaultAt/)+ expect(() => f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer', questions: [{ question: 'Ship how?', ...choices }] },+ asAgent(f.worker))).toThrow(/defaultAt/)+ })++ it('keeps the person’s rights: one who cannot read the task is not asked, and only the person asked answers', () => {+ const f = fixture(true)+ // A private project peer is no member of: its worker reads the task, peer does not.+ const project = f.state.projects!.find(p => p.id === f.app.projectId)!+ project.visibility = 'private'+ expect(() => f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer', questions: [{ question: 'Ship how?', ...choices, defaultAt }] },+ asAgent(f.worker))).toThrow(/^peer cannot read this conversation\.$/)+ project.visibility = 'public'+ const asked = f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer', questions: [{ question: 'Ship how?', ...choices, defaultAt }] }, asAgent(f.worker))+ const draft = asked.decisions![0]!+ const decision = { ...draft, answeredAt: null, defaultAt: Date.parse(defaultAt), createdAt: NOW }+ const answer = (actor: Actor) => f.run({ type: 'decision.answer', decisionId: draft.id, choice: 0 }, actor, { decision })+ expect(() => answer(owner)).toThrow('unavailable')+ expect(answer(peer).decisionAnswer).toEqual({ id: draft.id, choice: 0, note: null })+ })+})++describe('in a project not switched, an agent’s ask still goes to the PM', () => {+ it('opens no decision and writes nothing to the person’s Buddy', () => {+ const f = fixture(false)+ const sent = f.run({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'needs_human',+ result: 'Ship how?', ask: { personId: 'peer', ...choices, defaultAt } }, asAgent(f.worker))+ expect(sent.decisions ?? []).toEqual([])+ expect(statusRow(sent).recipients).toEqual([f.pm])+ expect(crewNeedOf(statusRow(sent).source)).toMatchObject({ agentId: f.worker, personIds: ['peer'], defaultAt })+ const asked = f.run({ type: 'decision.ask', conversationId: f.group, personId: 'peer', questions: [{ question: 'Ship how?', ...choices }] }, asAgent(f.worker))+ expect(asked.decisions ?? []).toEqual([])+ expect(needs(asked)).toHaveLength(1)+ expect([...sent.messages, ...asked.messages].filter(m => m.conversationId === f.buddyChat)).toEqual([])+ })+})diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 232cfe02f..dde11628d 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -4,7 +4,7 @@ import { applyCommand, commandSchema, type Command, type CommandContext } from 'import { createSuperTab, stableId, visibleState, type Actor, type Conversation } from './model.js'import { canReadGroup, canWatchAgent, isConfidential, readsRecordsIn, wordsOf } from './projects.js'import { CLOSED_CHAT_ANSWERED_NOTICE } from './decisions.js'-import { buddyChatId, defaultBuddy, defaultBuddyChat, shownBefore, swarmBuddyChatId } from './buddies.js'+import { BUDDY_REQUIREMENTS, buddyChatId, defaultBuddy, defaultBuddyChat, shownBefore, swarmBuddyChatId } from './buddies.js'import { isRoleName } from './agentNames.js'import { buddiesTold } from './buddyNews.js'import { sweepLiveness } from './liveness.js'@@ -399,7 +399,28 @@ describe('adding a Buddy', () => {const f = fresh()const added = addBuddy(f, peer, f.app.projectId, 'peer-mac')const start = f.state.starts!.find(s => s.id === added.result.startId)!- expect(start.request.requirements).toEqual({ memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false })+ expect(start.request.requirements).toEqual({ memoryBytes: BUDDY_REQUIREMENTS.memoryBytes, diskBytes: 1024 ** 3, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false })+ })++ // Task #3738 (tuan.dev, 11-06): a Windows PC with 16 GB and under 2 GB free could not add a Buddy. The requirement is the measured peak+ // with a margin (buddies.ts BUDDY_PEAK_BYTES), checked here and again by the host from the same start request.+ it('is admitted on a machine with 1.5 GB free, which the old 2 GB refused, and refused below its need with the amounts (#3738)', () => {+ const GIB = 1024 ** 3+ const free = (f: ReturnType<typeof fresh>, bytes: number) => {+ const pool = f.state.machines!.find(m => m.machineId === 'peer-mac')!+ // Its owner leaves room to memory (Agents: by memory), so the free memory decides, not a count.+ pool.agents = 'memory'+ const resources = pool.observation!.resources+ resources.memoryTotalBytes = 16 * GIB+ resources.memoryUsedBytes = 16 * GIB - bytes+ }+ const roomy = fresh()+ free(roomy, 1.5 * GIB)+ expect(() => addBuddy(roomy, peer, roomy.app.projectId, 'peer-mac')).not.toThrow()+ const short = fresh()+ free(short, 1 * GIB)+ expect(() => addBuddy(short, peer, short.app.projectId, 'peer-mac')).toThrow(+ 'peer\'s Mac is out of free memory: 1 GB free, and a Buddy needs 1.25 GB. Try again when an agent there finishes, or pick another machine.')})it('makes the started agent a Buddy in its owner\'s chat, and says it is ready there', () => {@@ -592,6 +613,7 @@ describe('a Buddy\'s proposal to the PM', () => {source: { kind: 'buddy-proposal', personId: 'peer', buddyId: 'buddy', ownerMessageId: 'ask',goal: 'Sync edits made offline', scope: 'Desktop drafts only; no phone yet', priority: 'high' } })expect(posted.some(m => m.author.kind === 'agent' && m.conversationId === f.app.conversationId)).toBe(false)+ expect(f.state.conversations.find(c => c.id === f.app.conversationId)!.owed ?? []).toContainEqual(expect.objectContaining({ id: home[0]!.id, personId: 'peer' }))})it('takes words up to a chat message\'s length, never cut at 80', () => {diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.tsindex 033049c6d..7349e8a4b 100644--- a/backend/src/superTabs/buddies.ts+++ b/backend/src/superTabs/buddies.ts@@ -266,10 +266,20 @@ export function chosenBuddyName(state: SuperTabState, chat: Conversation, owner:return { name: chat.title, notice: `${was} is taken now; your Buddy starts as ${chat.title}. Rename it from the ⋮ menu.` }}-/** What a Buddy asks of its machine: it reads and talks, so the usual agent's share with git to read the project. CPU use is one- * momentary sample, so it is not capped, as a routed Builder's start (Diego, 10-30). */-export const BUDDY_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 100,- tools: ['git'], devices: [], quotaRequired: false }+/** A Buddy's measured memory (task #3738, 11-06). A Buddy is one Claude Code session that reads and talks. Measured on a Mac (macOS+ * 26.5.1, arm64): the resident memory of the 38 live Claude Code sessions there, from 195 MB to 1,510 MB, median 580 MB and 90th+ * percentile 796 MB. The peak a new Buddy needs is that of an ordinary session: 800 MiB. The few sessions near 1.5 GB are+ * long-running builders, which a Buddy is not, and a Buddy already running is never refused for what it grows to. Windows: not+ * measured here (no Windows machine in this task); the figure below stands until a measurement on one says otherwise. */+export const BUDDY_PEAK_BYTES = 800 * 1024 ** 2+/** The margin above that peak a machine must have free before it takes a Buddy, so one never pushes it into swap: 1.6 times. */+export const BUDDY_MEMORY_MARGIN = 1.6++/** What a Buddy asks of its machine: it reads and talks, so its measured peak with a margin (BUDDY_PEAK_BYTES), and git to read the+ * project. CPU use is one momentary sample, so it is not capped, as a routed Builder's start (Diego, 10-30). Checked when it is added+ * (admitByRoom) and again by its host at launch, which both read this start request's requirements. */+export const BUDDY_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: Math.round(BUDDY_PEAK_BYTES * BUDDY_MEMORY_MARGIN), diskBytes: 1024 ** 3,+ maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false }/** The line a Buddy's chat shows once its session joined. */export const buddyReady = (name: string): string => `${name} is ready. Tell it what you have in mind.`diff --git a/backend/src/superTabs/buddyMachines.test.ts b/backend/src/superTabs/buddyMachines.test.tsindex c3e443727..b67864a8f 100644--- a/backend/src/superTabs/buddyMachines.test.ts+++ b/backend/src/superTabs/buddyMachines.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'import { createSuperTab, visibleState, type Actor } from './model.js'import { servedLocalModels, type ContributedMachine } from './machines.js'-import { isBuddyChat, swarmBuddyChatId } from './buddies.js'+import { BUDDY_PEAK_BYTES, BUDDY_REQUIREMENTS, isBuddyChat, swarmBuddyChatId } from './buddies.js'import { LEAD_CAPABILITY } from './leadStart.js'import { hostTab } from './read/hostRows.js'import { leaderboard } from './leaderboard/stats.js'@@ -434,3 +434,15 @@ describe('a Buddy-only machine after its reviews', () => {})})})++// Task #3738 (tuan.dev, 11-06): some people run Windows PCs with 16 GB and often under 2 GB free, and could not add a Buddy. A Buddy is+// one Claude session that reads and talks: what it asks of its machine comes from a measured peak, with a margin, not a round 2 GB.+describe('the memory a Buddy asks of its machine (#3738)', () => {+ const GIB = 1024 ** 3+ it('comes from a measured peak with a margin above it, and is under the 2 GiB a Buddy asked before', () => {+ expect(BUDDY_REQUIREMENTS.memoryBytes).toBeGreaterThanOrEqual(BUDDY_PEAK_BYTES * 1.5)+ expect(BUDDY_REQUIREMENTS.memoryBytes).toBeLessThan(2 * GIB)+ // Swarm agents' requirements stay as they were: this is a Buddy's alone.+ expect(BUDDY_REQUIREMENTS.diskBytes).toBe(GIB)+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex a3a74a24e..e476b0fe4 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -8,7 +8,7 @@ import { crewMoveFailed, takeOverCrewMember, wakeCrewMember } from './crewKeep.jimport { moveTimingRow, startWake } from './crewTimes.js'import type { PushOrigin } from '../github/pushOrigin.js'import { requireRepositoryReach, unknownPushReason, type RepositoryReach } from './repositoryReach.js'-import { admitByRoom, admitMachineStart, noRepositoryStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamAccountPool, teamPoolsOf, teamWorkCheck, TEAM_ACCOUNTS_GONE, NOT_YOUR_COMPUTER, type ContributedMachine } from './machines.js'+import { admitByRoom, admitMachineStart, AGENT_MEMORY_BYTES, noRepositoryStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamAccountPool, teamPoolsOf, teamWorkCheck, TEAM_ACCOUNTS_GONE, NOT_YOUR_COMPUTER, type ContributedMachine } from './machines.js'import { movableEntry } from './computerMoves.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'import { addedAgentName, renameAgentTo } from './agentRename.js'@@ -41,9 +41,9 @@ import { isReview, machineRuleRefusal } from './machineRules.js'import { accessRefusal, changeAccess, expireAccess, taskAccess } from './machineAccess.js'import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { agentsNamedIn, checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, type MentionTarget } from './mentions.js'-import { CREW_NEED_KIND, crewNeedPlace, crewNeedText, routedLine, routesToPm, type CrewNeed } from './crewNeeds.js'+import { CREW_NEED_KIND, crewNeedPlace, crewNeedText, projectPm, routedLine, routesToPm, type CrewNeed } from './crewNeeds.js'import { checkReason, heldReason, missingReason } from './heldReason.js'-import { answerDecision, askDecisions, checkDecisionDeadline, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'+import { answerDecision, askDecisions, askedThroughBuddy, mustAgreePassed, asksDirectly, checkDirectAsk, checkDecisionDeadline, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { leadOf, TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest, workedAgain } from './terminal.js'import { BACK_WITH_YOU, pickUp, reopenHanded } from './handed.js'import { changesRequested, engineerAnswered, leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, revisionReady, toldEngineer, waitingForReview } from './liveness.js'@@ -1566,7 +1566,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}// Sessions have no count of their own (Scholes, 11-02): idle ones close themselves. The one limit is the machine's, which// its owner set to protect it (Lead, 11-02), said in words a person can act on. A Buddy-only machine has none (below).- if (!pool.buddyOnly) admitByRoom(state, pool, machineSlots(state, pool), BUDDY_REQUIREMENTS.memoryBytes)+ if (!pool.buddyOnly) admitByRoom(state, pool, machineSlots(state, pool), BUDDY_REQUIREMENTS.memoryBytes, 'a Buddy')const contributor = person(state, main.contributorId)// In the one Buddy chat a session works in one project its person reads, or, with none named, as the main Buddy does// (spec: The model). A project's own chat has its project.@@ -3000,9 +3000,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const group = open(state, command.conversationId)const drafts = askDecisions(state, group, command.personId, command.questions,{ now: context.now, operationId, askerAgentId: checkAsker(state, actor, group), assignmentId: null })- // People talk only to the PM (anh Dee, 11-05; crewNeeds.ts): another agent's questions are the PM's crew needs, one- // each, checked as a decision would be and opened for nobody.- const pmInstead = routesToPm(state, actor, group)+ // In a switched project the person is asked directly, through their default Buddy (task #3826). Elsewhere people talk only+ // to the PM (anh Dee, 11-05; crewNeeds.ts): another agent's questions are the PM's crew needs, one each, checked as a+ // decision would be and opened for nobody.+ const direct = asksDirectly(state, group)+ if (direct) checkDirectAsk(command.questions)+ const pmInstead = direct ? null : routesToPm(state, actor, group)if (pmInstead) {command.questions.forEach((q, i) => crewNeed(group, pmInstead, { personIds: [command.personId], conversationId: group.id,question: q.question, options: q.options, recommended: q.recommended, ...q.defaultAt ? { defaultAt: q.defaultAt } : {} }, q.question, stableId(operationId, 'crew-need', String(i))))@@ -3010,10 +3013,20 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,break}effects.decisions = drafts+ if (direct) effects.messages.push(...askedThroughBuddy(state, group, drafts, sender))result.decisionIds = effects.decisions.map(d => d.id)break}case 'decision.answer': {+ // The sweep at the time of a decision its person must agree to: no default applies, the PM is told once (task #3826).+ if (context.defaulted && context.decision?.mustAgree) {+ const passed = mustAgreePassed(state, actor, context.decision, context.now)+ effects.decisionKeptWaiting = context.decision.id+ if (passed.recipients.length) message(passed.noticeIn, passed.text, passed.recipients, null, passed.source)+ result.decisionId = context.decision.id+ result.keptWaiting = true+ break+ }const { answer, noticeIn, notice, recipients, source, line } = answerDecision(state, actor, context.decision,{ choice: command.choice, note: command.note ?? null, delegate: command.delegate === true, overdue: context.overdue === true, defaulted: context.defaulted === true, now: context.now })effects.decisionAnswer = answer@@ -3519,6 +3532,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,{ kind: 'buddy-proposal', personId: owner.id, buddyId: self.id, ownerMessageId: command.ownerMessageId,goal: command.goal, scope: command.scope, priority: command.priority }, attachments)effects.messages.at(-1)!.author = { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation }+ const relayed = effects.messages.at(-1)!+ owe(state, home, { ...relayed, thread: relayed.thread ?? null }, context.now)// Its own id: this command's id is the proposal's, and a second row with it rolls the command back. Marked with its project,// so it goes from view as a PM's line does when its person loses that project (buddySessions.ts lostProjectRow).if (isSwarmBuddy(self)) effects.messages.push({ id: stableId('proposal-sent', operationId), conversationId: chat.id, author: sender,@@ -3753,7 +3768,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!pool.observation?.capabilities?.includes(REGULAR_AGENT_CAPABILITY)) fail('HOST_OUTDATED', `Update Harness on ${pool.name ?? 'your computer'} to start this agent there.`, 409)const chatId = openAgentChat(me, name)const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,- ...(command.model ? { model: command.model } : {}), name, cwd: buddyHomeFolder(pool, me), worktree: false, requirements: BUDDY_REQUIREMENTS, regular: true }+ ...(command.model ? { model: command.model } : {}), name, cwd: buddyHomeFolder(pool, me), worktree: false,+ // A Buddy's smaller memory is for a session that only reads and talks (#3738); a Regular agent takes tasks.+ requirements: { ...BUDDY_REQUIREMENTS, memoryBytes: AGENT_MEMORY_BYTES }, regular: true }const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!state.starts ??= []if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')@@ -4313,7 +4330,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)}result.changed = react(group, command.messageId, command.on, context.reaction)- if (actor.kind === 'agent') settleReaction(state, group, actor.agentId, command.messageId, command.emoji, command.on)+ if (actor.kind === 'agent') settleReaction(state, group, actor.agentId, command.messageId, command.on)// A reaction is how an agent acknowledges (ACK_ONLY refuses the post), so it settles the agent's delivery of that message.if (actor.kind === 'agent' && command.on) effects.settles = { messageId: command.messageId, agentId: actor.agentId }break@@ -4496,6 +4513,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,message(group.id, text, recipients, command.replyTo, command.agentOnly ? { ...AGENT_ONLY, ...command.notice ? { notice: command.notice } : {} } : undefined, attachments, tagged,tagged.length ? command.mentionsIfNoWorker : undefined)if (!command.agentOnly) effects.messages.at(-1)!.post = true+ if (command.answers) effects.messages.at(-1)!.answers = command.answers// Whom a stuck line in a task tags, with its requester (stuck.ts, task #3915).if (actor.kind === 'person' && !command.agentOnly && !group.kind && !group.audience && !isProjectChat(state, group)) noteWriter(group, actor.userId)// After the post is marked: the crew need is the server's row for the PM, never a post of its own.@@ -4782,7 +4800,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,let asked: string | undefined// People talk only to the PM (anh Dee, 11-05; crewNeeds.ts): an agent's needs_human, whoever's assignment it is, when that// agent is not the PM, is the PM's crew need, and its question opens no decision for the person it names (review of #3223).- const pmInstead = command.status === 'needs_human' ? routesToPm(state, actor, group) : null+ // In a switched project an ask goes to the person directly, through their default Buddy and their Needs you list, and the+ // PM sees only the task waiting on them (task #3826).+ const direct = !!command.ask && asksDirectly(state, group)+ if (direct) checkDirectAsk([command.ask!])+ const pmInstead = command.status === 'needs_human' && !direct ? routesToPm(state, actor, group) : nullif (command.ask) {if (command.status !== 'needs_human' || !command.result || actor.kind !== 'agent') {fail('INVALID_DECISION', 'An agent asks a person for a decision only when its work needs a human, with the question as its result.', 400)@@ -4799,6 +4821,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (context.openDecisions == null) {effects.decisions = draftsasked = context.repeatedDecision ?? drafts[0]!.id+ // A repeat of a question still open was already brought to the person.+ if (direct && !context.repeatedDecision) effects.messages.push(...askedThroughBuddy(state, group, drafts, sender))}else effects.result.notAsked = `Not asked ${agentWrittenNameOf(state, person(state, personId).id)}: ${context.openDecisions} decisions you asked them are still open, and at most ${MAX_OPEN_DECISIONS} can be. Wait for answers before asking more.`}@@ -4845,7 +4869,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Its own Ready wakes nobody (Ken, 2026-11-02: every hand-over reached the PM): it names whom it hands to.: own ? (lead && ['needs_human', 'blocked', 'done'].includes(command.status) ? [lead] : []): [...command.status === 'stopped' ? [] : [assignment.agentId], ...lead ? [lead] : []]- const recipients = [...new Set(told)].filter(id => actor.kind !== 'agent' || id !== actor.agentId)+ // A direct ask is the person's to answer: the PM only sees the task waiting on them (askedOf), never the question.+ const pm = direct ? projectPm(state, group) : null+ const recipients = [...new Set(told)].filter(id => (actor.kind !== 'agent' || id !== actor.agentId) && !(direct && (id === pm || id === group.leadId)))const askedName = command.ask ? agentWrittenNameOf(state, person(state, command.ask.personId).id) : ''const asked = !command.ask ? '' : pmInstead ? `\n\nFor the PM to ask ${askedName}.`: effects.result.notAsked ? `\n\n${effects.result.notAsked}` : `\n\nAsked ${askedName}.`diff --git a/backend/src/superTabs/crewKeep.apply.test.ts b/backend/src/superTabs/crewKeep.apply.test.tsindex bc0dc0256..3f77ba090 100644--- a/backend/src/superTabs/crewKeep.apply.test.ts+++ b/backend/src/superTabs/crewKeep.apply.test.ts@@ -168,3 +168,27 @@ describe('a take-over marks nothing Team-written (security review of #3229, Curlexpect(after.teamWritten).toBeFalsy()})})++describe('a member that keeps stopping is moved and its task goes back at once (#3662)', () => {+ it('hands its task on as soon as the move is decided, not after its start runs, and says why', () => {+ const f = fixture()+ const task = working(f)+ f.state.agents.find(a => a.id === f.ada.id)!.stops = [NOW - 50 * 60_000, NOW - 30 * 60_000, NOW - 5 * 60_000]+ const drafts = applyCrewKeep(f.state, NOW, everywhere)+ const ada = f.state.agents.find(a => a.id === f.ada.id)!+ expect(ada.movedTo).toMatchObject({ machineId: 'mini', reason: 'unstable' })+ const now = f.state.conversations.find(c => c.id === task.id)!+ expect(now.assignment).toMatchObject({ status: 'lost', lost: { reason: 'crew-unstable', at: NOW } })+ expect(activeWork(now)).toBe(false)+ expect(drafts.map(d => d.text).join(' ')).toContain('stopped 3 times in the last hour')+ })++ it('moves a member below its quota floor without handing its task on: it is still working', () => {+ const f = fixture([machine('mac', { usedPercent: 90 }), machine('mini')])+ const task = working(f)+ applyCrewKeep(f.state, NOW, everywhere)+ expect(f.state.agents.find(a => a.id === f.ada.id)!.movedTo).toMatchObject({ machineId: 'mini', reason: 'quota-low' })+ expect(f.state.conversations.find(c => c.id === task.id)!.assignment!.status).toBe('working')+ })+})+diff --git a/backend/src/superTabs/crewKeep.test.ts b/backend/src/superTabs/crewKeep.test.tsindex 63815ac22..6d7f3070e 100644--- a/backend/src/superTabs/crewKeep.test.ts+++ b/backend/src/superTabs/crewKeep.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { applyCommand } from './commands.js'import { crewKeep, crewNeedsMachine, type CrewDeps } from './crewKeep.js'+import { recordAgentPresence } from './machines.js'import { config, fixture, GB, machine, NOW, person } from './crewKeep.test-support.js'import * as crewRules from './crewRules.js'import type { MachineRule } from './policy.js'@@ -229,3 +230,65 @@ describe('crewKeep: machine rules apply to moves, read from the project rules reexpect(kinds(f.state)).toEqual([])})})++// Task #3662 (anh Dee, 11-06): Wren stopped three times in an hour on an account with about 10% weekly quota left, and Aspen on one+// at about 12%; the keeper reopened Wren each time and its task waited 5 minutes per stop. A member on an account below the routing+// quota floor moves to the best fallback instead of reopening in place, and one that keeps stopping is moved too.+describe('crewKeep: low quota and a member that keeps stopping (#3662)', () => {+ const moveOf = (state: SuperTabState, deps = everywhere) => crewKeep(state, NOW, deps).find(a => a.kind === 'move')+ const stuckOf = (state: SuperTabState) => crewKeep(state, NOW, everywhere).find(a => a.kind === 'stuck')++ it('moves a member off an account that runs the PM when its weekly quota is below 20%, not above it', () => {+ // The PM runs on 'mac', Ada with it: 10% left is under the 20% an account running a PM keeps.+ expect(moveOf(fixture([machine('mac', { usedPercent: 90 }), machine('mini')]).state)).toMatchObject({ toMachineId: 'mini', reason: 'quota-low' })+ expect(moveOf(fixture([machine('mac', { usedPercent: 70 }), machine('mini')]).state)).toBeUndefined()+ })++ it('moves a member off any other account below 5%, and keeps it above', () => {+ const onMini = (used: number) => {+ const f = fixture([machine('mac'), machine('mini', { usedPercent: used })])+ f.state.agents.find(a => a.id === f.ada.id)!.machineId = 'mini'+ return f.state+ }+ expect(moveOf(onMini(96))).toMatchObject({ toMachineId: 'mac', reason: 'quota-low' })+ expect(moveOf(onMini(90))).toBeUndefined()+ })++ it('never picks a fallback that is itself below its floor', () => {+ const f = fixture([machine('mac', { usedPercent: 90 }), machine('mini', { signedIn: false })])+ f.state.agents.find(a => a.id === f.ada.id)!.machineId = 'mini'+ // Ada's own machine is signed out; the only other one runs the PM with 10% left, under its 20%.+ expect(moveOf(f.state)).toBeUndefined()+ expect(stuckOf(f.state)).toMatchObject({ reason: 'signed-out' })+ })++ it('says nothing of a quota it cannot read', () => {+ expect(moveOf(fixture([machine('mac', { usedPercent: 99, known: false }), machine('mini')]).state)).toBeUndefined()+ })++ it('moves a member that stopped three times in the last hour, not two, and counts only the last hour', () => {+ const stopped = (times: number[]) => {+ const f = fixture()+ f.state.agents.find(a => a.id === f.ada.id)!.stops = times+ return f.state+ }+ expect(moveOf(stopped([NOW - 50 * 60_000, NOW - 30 * 60_000, NOW - 5 * 60_000]))).toMatchObject({ toMachineId: 'mini', reason: 'unstable' })+ expect(moveOf(stopped([NOW - 30 * 60_000, NOW - 5 * 60_000]))).toBeUndefined()+ expect(moveOf(stopped([NOW - 61 * 60_000, NOW - 30 * 60_000, NOW - 5 * 60_000]))).toBeUndefined()+ })++ it('records a stop when a reading first shows the session gone, once however long it stays down', () => {+ const f = fixture()+ recordAgentPresence(f.state, 'mac', [], NOW)+ recordAgentPresence(f.state, 'mac', [], NOW + 30_000)+ const ada = () => f.state.agents.find(a => a.id === f.ada.id)!+ expect(ada().stops).toEqual([NOW])+ recordAgentPresence(f.state, 'mac', [ada().harnessId], NOW + 60_000)+ recordAgentPresence(f.state, 'mac', [], NOW + 90_000)+ expect(ada().stops).toEqual([NOW, NOW + 90_000])+ // Only the last hour is kept, and at most a few.+ recordAgentPresence(f.state, 'mac', [ada().harnessId], NOW + 2 * 3_600_000)+ recordAgentPresence(f.state, 'mac', [], NOW + 2 * 3_600_000 + 1_000)+ expect(ada().stops).toEqual([NOW + 2 * 3_600_000 + 1_000])+ })+})diff --git a/backend/src/superTabs/crewKeep.ts b/backend/src/superTabs/crewKeep.tsindex d96533926..81b3db5f1 100644--- a/backend/src/superTabs/crewKeep.ts+++ b/backend/src/superTabs/crewKeep.ts@@ -16,7 +16,7 @@ import { barredFromTeamWritten, teamWrittenTask } from './teamWritten.js'import { placeAfter, queueSiblings } from './taskQueue.js'import { quotaOf, resetMs } from './reviewSeats.js'import { groupsOf, idleSince } from './tidy.js'-import { DISK_FLOOR_BYTES, FOLDER_ASLEEP_MS, HELD_TASK_MS, MOVE_LOW_DISK_BYTES, MOVE_OFFLINE_MS, MOVE_QUOTA_OUT_MS, MOVE_REFUSED_WAIT_MS, SLEEP_IDLE_MS } from './crewRules.js'+import { DISK_FLOOR_BYTES, FOLDER_ASLEEP_MS, HELD_TASK_MS, MOVE_LOW_DISK_BYTES, MOVE_OFFLINE_MS, MOVE_QUOTA_OUT_MS, MOVE_REFUSED_WAIT_MS, QUOTA_FLOOR_PERCENT, QUOTA_FLOOR_PM_PERCENT, SLEEP_IDLE_MS, UNSTABLE_STOPS, UNSTABLE_WINDOW_MS } from './crewRules.js'export type CrewAction =| { kind: 'sleep'; agentId: string }@@ -78,9 +78,28 @@ export function crewTrouble(state: SuperTabState, pool: ContributedMachine | nul})) return 'quota'const disk = freeDisk(pool)if (typeof disk === 'number' && disk < MOVE_LOW_DISK_BYTES) return 'disk'+ // Below the routing's quota floor (task #3662): a member there stops again and again as the weekly quota runs out, so it moves+ // to a better account rather than reopening in place. An unknown reading is never trouble.+ const weekly = quota?.known ? quota.windows.find(w => w.name === 'weekly') : undefined+ // Used up (100%) is the 'quota' rule's above: it waits when the window resets within the hour.+ if (weekly && weekly.usedPercent < 100 && 100 - weekly.usedPercent < (runsPm(state, pool, engine) ? QUOTA_FLOOR_PM_PERCENT : QUOTA_FLOOR_PERCENT)) return 'quota-low'return null}+/** Whether a project's coordinator runs on [pool]'s account for [engine]: its weekly quota is the PM's, so a crew member leaves it+ * sooner. An account is a machine (a Team account's machine counts with the Mac that hosts it). */+function runsPm(state: SuperTabState, pool: ContributedMachine, engine: string): boolean {+ return state.conversations.some(c => {+ const lead = c.leadId ? state.agents.find(a => a.id === c.leadId) : undefined+ if (!lead || lead.configuration.engine !== engine) return false+ const home = state.machines?.find(m => m.machineId === lead.machineId)+ return lead.machineId === pool.machineId || (!!pool.hostMachineId && pool.hostMachineId === lead.machineId) || (!!home?.hostMachineId && home.hostMachineId === pool.machineId)+ })+}++/** Whether [agent] stopped [UNSTABLE_STOPS] times within the last [UNSTABLE_WINDOW_MS]. */+const unstable = (agent: Agent, now: number): boolean => (agent.stops ?? []).filter(at => now - at < UNSTABLE_WINDOW_MS).length >= UNSTABLE_STOPS+/** The fallback machines for [agent], best first, in the route's order: the same account kind as the machine it leaves, then* the account whose weekly quota resets soonest, then the most left, then the fewest agents working, then by name. Only* machines with no trouble that admit its start. */@@ -128,7 +147,7 @@ export function crewKeep(state: SuperTabState, now: number, deps: CrewDeps): Creconst actions: CrewAction[] = []const members = state.agents.filter(a => isCrew(a) && !isBuddy(a) && !isLead(state, a) && !a.movedTo)for (const agent of members) {- const trouble = crewTrouble(state, standingPool(state, agent.machineId), agent.configuration.engine, now)+ const trouble = crewTrouble(state, standingPool(state, agent.machineId), agent.configuration.engine, now) ?? (unstable(agent, now) ? 'unstable' : null)// An asleep member, or an awake one with no work on a machine gone offline (a laptop closed for the night), stays where it// is: it holds nothing to move, and a wake or new work moves it then (review of #3229).const stays = !!agent.asleep || (trouble === 'offline' && !heldTasks(state, agent, now).length)@@ -169,6 +188,8 @@ export function troubleText(state: SuperTabState, agent: Agent, reason: CrewTroureturn reason === 'offline' ? `${from} has been offline over 5 minutes`: reason === 'signed-out' ? `${engine} is signed out on ${from}`: reason === 'quota' ? `${from} is out of ${engine} quota for over an hour`+ : reason === 'quota-low' ? `${engine} on ${from} is nearly out of weekly quota`+ : reason === 'unstable' ? `${nameOf(agent)} stopped ${UNSTABLE_STOPS} times in the last hour on ${from}`: `${from} is low on disk`}const nameOf = (agent: Agent) => agent.displayName ?? agent.name@@ -238,7 +259,16 @@ export function applyCrewKeep(state: SuperTabState, now: number, deps: CrewDeps)request: { ...request, handoffNote: handoffNote(state, agent, action.reason, pool, now) }, harnessId: null, dispatched: false, error: null, requestedAt: now }state.starts.push(start)// At the head of the list now, before the old session's loss of it (offline, or its host closing it) can come first.- for (const group of heldTasks(state, agent, now)) toHead(state, group)+ for (const group of heldTasks(state, agent, now)) {+ // A member that keeps stopping hands its task on now, back to its area for whoever is free, rather than waiting 5 minutes for+ // each reopen and then for its move (task #3662).+ if (action.reason === 'unstable' && activeWork(group)) {+ group.assignment!.status = 'lost'+ group.assignment!.lost = { reason: 'crew-unstable', at: now }+ group.lostAttempt = { id: group.assignment!.id, agentId: agent.id, machineId: agent.machineId, engine: agent.configuration.engine }+ }+ toHead(state, group)+ }agent.movedTo = { machineId: pool.machineId, startId: id, reason: action.reason, at: now }delete agent.crewStuckdrafts.push(...notice(state, agent, stableId('crew-move', agent.id, id),diff --git a/backend/src/superTabs/crewNeeds.ts b/backend/src/superTabs/crewNeeds.tsindex aed365181..bf8a2e89a 100644--- a/backend/src/superTabs/crewNeeds.ts+++ b/backend/src/superTabs/crewNeeds.ts@@ -3,6 +3,8 @@* the PM gets a crew need, and the agent's command result says so. This routes; it never refuses. The PM tags anyone. Any* other agent may still tag the person it is answering (the author of the message it answers or replies to). A project with* no PM in its chat routes nothing, so its tags reach people as before.+ * In a switched project (boardRights.ts) an agent's ask of a person is not routed: it goes to the person directly, through+ * their default Buddy (decisions.ts asksDirectly, task #3826).** A crew need is either its own row (source kind `crew-need`: a tag, a decision ask, a line to a person) or the needs_human* status row the agent already writes to the PM (`source.crewNeed`). `crewNeedOf` reads both; the PM's inbox (#3403) listsdiff --git a/backend/src/superTabs/crewRules.ts b/backend/src/superTabs/crewRules.tsindex c1b5e8f20..5dc9f9a7f 100644--- a/backend/src/superTabs/crewRules.ts+++ b/backend/src/superTabs/crewRules.ts@@ -21,3 +21,12 @@ export const MOVE_REFUSED_WAIT_MS = HOUR/** How long after losing its task to its machine a crew member still counts as holding it, so it moves with it. */export const HELD_TASK_MS = HOUR++/** The weekly quota an account keeps for a crew member (the routing's order and quota): below it the member moves to a fallback+ * instead of reopening in place (task #3662). 5% for the big work a crew member does; 20% when the account runs a PM, whose work+ * must never wait on a crew member's. */+export const QUOTA_FLOOR_PERCENT = 5+export const QUOTA_FLOOR_PM_PERCENT = 20+/** A crew member whose session stopped this many times within the window is moved, not reopened. */+export const UNSTABLE_STOPS = 3+export const UNSTABLE_WINDOW_MS = HOURdiff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex dbe321ac4..d6dd0cf50 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -3,14 +3,15 @@* with one tap, and the answer reaches the asking agent and the Lead in the conversation it came from. Decisions live in* SuperTabDecision, never in the tab state, as mentions do. A decision is not a private channel: the PM's private lines go* to the person's Buddy chat (buddies.ts). Called inside SuperTabStore's transactions. */-import { defaultBuddyChat, isBuddy, isSwarmBuddy, openBuddyChat } from './buddies.js'+import { defaultBuddy, defaultBuddyChat, isBuddy, isSwarmBuddy, openBuddyChat } from './buddies.js'+import { switched } from './boardRights.js'import { usernameOf } from './usernames.js'import { agentWrittenNameOf } from './personNames.js'import { createHash } from 'node:crypto'import type { Prisma } from '@prisma/client'import { z } from 'zod'import { agentDisplayName } from './agentNames.js'-import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Author, type Conversation, type SuperTabState } from './model.js'+import { AGENT_ONLY, fail, isLeads, person, stableId, type Actor, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, canReadGroup, groupProject, isClosedPmChat, ledProject, projectAgent, projectOf, projectsOf, readsRecordsIn } from './projects.js'import { LEDGER_WEEKS } from './leaderboard/record.js'import { coordinatorNameOf } from './instructions.js'@@ -27,7 +28,9 @@ const line = (max: number) => z.string().trim().min(1).max(max)/** What a question offers besides itself: 2–5 distinct options, the index of the recommended one, and what an answer unblocks. */export const decisionChoices = z.object({ options: z.array(line(200)).min(2).max(5).refine(o => new Set(o).size === o.length, 'Give distinct options.'),recommended: z.number().int().min(0), unblocks: line(300),- defaultAt: z.string().datetime({ offset: true }).transform(value => new Date(value).toISOString()).optional() }).strict()+ defaultAt: z.string().datetime({ offset: true }).transform(value => new Date(value).toISOString()).optional(),+ /** A rule says the person must agree (task #3826): at defaultAt the PM is told instead of the default applying. */+ mustAgree: z.literal(true).optional() }).strict()export const decisionQuestion = decisionChoices.extend({ question: line(1000) }).strict()type Question = z.infer<typeof decisionQuestion>@@ -61,6 +64,7 @@ export interface DecisionTarget {kind?: string | null/** Closed unanswered once its work was over (withdrawIn). */withdrawn?: boolean+ mustAgree?: boolean}/** `delegated`: the person asked left it to the PM, who took the recommended option. *//** `choice` null with a `note`: the person typed their own answer instead of choosing an option (task #2996). */@@ -84,6 +88,36 @@ export function askDecisions(state: SuperTabState, group: Conversation, personIdconversationId: group.id, projectId, personId, askerAgentId: from.askerAgentId, assignmentId: from.assignmentId, ...from.kind ? { kind: from.kind } : {} }))}+/** Whether an agent's ask in [group] goes to the person directly, never through the PM: in a switched project (boardRights.ts;+ * task #3826, spec "When an agent needs a person"). Elsewhere people talk only to the PM (crewNeeds.ts). */+export const asksDirectly = (state: SuperTabState, group: Conversation): boolean => switched(groupProject(state, group))++/** A direct ask always says when its recommendation applies: the person may be away, and the work must not wait without end. */+export function checkDirectAsk(questions: ReadonlyArray<{ defaultAt?: string }>): void {+ if (questions.some(q => !q.defaultAt)) {+ fail('INVALID_DECISION', 'In this project you ask the person directly, so each question needs defaultAt: the time its recommended option applies if they have not answered (at least 15 minutes ahead).', 400)+ }+}++/** Each asked decision's line in its person's default Buddy chat, to their default Buddy, which brings it to them: the Buddy+ * cannot answer it (answerable), the person answers in their Needs you list. Marked with its project, so it hides once they+ * lose it (buddies.ts hiddenProjectRow). Written as [author], the agent that asked. */+export function askedThroughBuddy(state: SuperTabState, group: Conversation, drafts: readonly DecisionDraft[], author: Author): MessageDraft[] {+ return drafts.map(d => {+ const to = person(state, d.personId)+ const buddy = defaultBuddy(state, to.id)+ const options = d.options.map((o, i) => i === d.recommended ? `${o} (recommended)` : o).join(' / ')+ const task = group.number ? ` on task #${group.number}` : ''+ const text = `${author.displayName ?? author.name} asks ${usernameOf(state, to.id)}${task}: ${d.question}\n\nOptions: ${options}\n`+ + `Unblocks: ${d.unblocks}\n` + (d.mustAgree+ ? `No default applies: your agreement is required. At ${d.defaultAt}, the PM is told if you have not answered.`+ : `At ${d.defaultAt}, if not answered: ${d.options[d.recommended]!}.`)+ return { id: stableId(d.id, 'buddy'), conversationId: defaultBuddyChat(state, to).id, author, text, replyTo: null,+ recipients: buddy ? [buddy.id] : [], source: { kind: DECISION_ASKED_KIND, decisionId: d.id, projectId: d.projectId }, buddyProject: d.projectId }+ })+}+export const DECISION_ASKED_KIND = 'decision-asked'+/** Any agent of the project asks with `decision.ask`, in its own project's conversations (project instructions, phase 4); a* worker may also ask through needs_human. */export function checkAsker(state: SuperTabState, actor: Actor, group: Conversation): string {@@ -172,6 +206,23 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Decreturn { answer, noticeIn: noticeIn.id, notice, recipients, source: { ...AGENT_ONLY, decisionId: asked.id }, line }}+export const MUST_AGREE_KIND = 'decision-must-agree'+/** What the PM is told when a decision its person must agree to reaches its time unanswered: none of the question, which the+ * PM reads in its decisions; the sweep never applies the default (task #3826, spec "When an agent needs a person"). */+export function mustAgreePassed(state: SuperTabState, actor: Actor, decision: DecisionTarget | undefined, now: number) {+ const group = answerable(state, actor, decision)+ const asked = decision!+ if (asked.withdrawn || workOver(state, group)) fail('DECISION_ANSWERED', NO_LONGER_WAITS)+ if (asked.answeredAt !== null) fail('DECISION_ANSWERED', 'This decision is already answered.')+ if (!asked.mustAgree || asked.defaultAt == null || asked.defaultAt > now) fail('INVALID_DECISION', 'This decision has not reached its default time.', 400)+ const project = groupProject(state, group)+ const lead = state.conversations.find(c => c.id === project.leadConversationId)?.leadId+ const noticeIn = isClosedPmChat(group) ? state.conversations.find(c => c.id === project.leadConversationId)! : group+ const text = `A decision ${usernameOf(state, asked.personId)} must agree to reached its default time unanswered, so no default applied: `+ + 'it waits for them. Read it with: harness super-tab decisions'+ return { noticeIn: noticeIn.id, text, recipients: lead && noticeIn.agentIds.includes(lead) ? [lead] : [], source: { kind: MUST_AGREE_KIND, decisionId: asked.id } }+}+/** The Lead's one line saying what it chose, in the person's own Buddy chat of that project: only they and their Buddy read* it, and they were asked the question. Opened for the line when they have none (buddies.ts openBuddyChat), so it never* drops: Buddies replaced Chat with PM (Ken, 10-29). */@@ -227,10 +278,10 @@ export function workEnded(before: SuperTabState, after: SuperTabState): string[]return after.conversations.filter(c => workOver(after, c) && !(was.has(c.id) && workOver(before, was.get(c.id)!))).map(c => c.id)}-/** What makes an ask a repeat: the same asker, task, person, conversation, question, options, recommendation and what it- * unblocks. Another asker, another task or other options with the same text is a decision of its own (review of #1753). */-const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'> & { defaultAt?: string | Date | null }) =>- JSON.stringify([d.askerAgentId, d.assignmentId ?? null, d.personId, d.conversationId, d.question, d.options, d.recommended, d.unblocks, d.defaultAt ? new Date(d.defaultAt).toISOString() : null])+/** What makes an ask a repeat: the same asker, task, person, conversation, question, options, recommendation, agreement requirement+ * and what it unblocks. Another asker, another task or other options with the same text is a decision of its own (review of #1753). */+const repeatKey = (d: Pick<DecisionDraft, 'askerAgentId' | 'assignmentId' | 'personId' | 'conversationId' | 'question' | 'options' | 'recommended' | 'unblocks'> & { defaultAt?: string | Date | null; mustAgree?: boolean | null }) =>+ JSON.stringify([d.askerAgentId, d.assignmentId ?? null, d.personId, d.conversationId, d.question, d.options, d.recommended, d.unblocks, d.defaultAt ? new Date(d.defaultAt).toISOString() : null, d.mustAgree === true])/** Writes the questions asked and returns the decision each one is: an open decision that this ask exactly repeats is that* decision again, not a second one. New ones beyond MAX_OPEN_DECISIONS from this asker to this person are refused, and@@ -290,9 +341,16 @@ export async function expireReflections(tx: Tx, tabId: string, projectId: stringexport async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {const row = await tx.superTabDecision.findFirst({ where: { id, tabId },select: { id: true, personId: true, conversationId: true, projectId: true, askerAgentId: true, question: true, options: true, recommended: true,- answeredAt: true, defaultAt: true, createdAt: true, assignmentId: true, kind: true, withdrawn: true } })+ answeredAt: true, defaultAt: true, createdAt: true, assignmentId: true, kind: true, withdrawn: true, mustAgree: true } })return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, defaultAt: row.defaultAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null,- withdrawn: row.withdrawn === true } : undefined+ withdrawn: row.withdrawn === true, mustAgree: row.mustAgree === true } : undefined+}++/** A must-agree decision past its time keeps waiting for its person: its time is cleared, so the due range never reads it again+ * and the PM is told once. Conflicts with a concurrent answer, as recordAnswer does. */+export async function keepWaiting(tx: Tx, tabId: string, id: string): Promise<void> {+ const kept = await tx.superTabDecision.updateMany({ where: { id, tabId, mustAgree: true, defaultAt: { not: null }, ...waiting }, data: { defaultAt: null } })+ if (!kept.count) fail('DECISION_ANSWERED', 'This decision is already answered.')}/** Conflicts with a concurrent answer of the same decision: only the first one counts. */@@ -415,8 +473,8 @@ export async function listDecisions(tx: Tx, tabId: string, state: SuperTabState,question: row.question, options: row.options, recommended: row.recommended, unblocks: row.unblocks,createdAt: row.createdAt, answeredAt: row.answeredAt ?? null, choice: row.choice ?? null, note: row.note ?? null,delegated: row.delegated === true, overdue: row.overdue === true, defaultAt: row.defaultAt ?? null, defaulted: row.defaulted === true,- // What the 24-hour sweep can take: the sweep skips a reflection and a recommended option that is not one of the options.- pmTakesOver: row.kind !== REFLECTION_DECISION && row.recommended >= 0 && row.recommended < row.options.length,+ // What the 24-hour sweep can take: the sweep skips required agreement, reflections and an invalid recommended option.+ pmTakesOver: row.mustAgree !== true && row.kind !== REFLECTION_DECISION && row.recommended >= 0 && row.recommended < row.options.length,// A typed answer (no option) reads as its words.answer: row.choice == null ? (row.answeredAt ? row.note ?? null : null): row.options[row.choice] === undefined ? null : row.defaulted ? `Default applied: ${row.options[row.choice]!}` : answerText(row.options[row.choice]!, row.delegated === true) }diff --git a/backend/src/superTabs/inbox.test.ts b/backend/src/superTabs/inbox.test.tsindex 837595da9..34ef71ea4 100644--- a/backend/src/superTabs/inbox.test.ts+++ b/backend/src/superTabs/inbox.test.ts@@ -115,7 +115,7 @@ describe('the sections of the PM\'s inbox', () => {expect(personLine(f.state, { conversationId: 'lead', messageId: 'p1' }, 'y'.repeat(2000), 'owner').length).toBeLessThanOrEqual(1000)})- it('gathers a person\'s message or a crew need for a PM whose host sends its turn, and nothing else', () => {+ it('batches crew needs but delivers people immediately even to a turn-aware PM', () => {const { f } = setup()const pm = f.state.agents.find(a => a.id === f.lead)!, dev = f.state.agents.find(a => a.id === f.dev)!const person = { author: { kind: 'person', id: 'owner' } as Author, source: undefined }@@ -124,7 +124,7 @@ describe('the sections of the PM\'s inbox', () => {// An older host, which reports no such capability: everything goes at once, as before.expect(gathersForInbox(f.state, pm, person)).toBe(false)f.state.machines = [{ machineId: pm.machineId, observation: { capabilities: [INBOX_CAPABILITY] } } as never]- expect(gathersForInbox(f.state, pm, person)).toBe(true)+ expect(gathersForInbox(f.state, pm, person)).toBe(false)expect(gathersForInbox(f.state, pm, need)).toBe(true)expect(gathersForInbox(f.state, pm, post)).toBe(false)// Never for an agent that is not the PM.diff --git a/backend/src/superTabs/inbox.ts b/backend/src/superTabs/inbox.tsindex c16b42999..edf1df428 100644--- a/backend/src/superTabs/inbox.ts+++ b/backend/src/superTabs/inbox.ts@@ -33,10 +33,10 @@ export function inboxSection(message: { author: Pick<Author, 'kind'>; source?: uexport const turnInboxHost = (state: SuperTabState, agent: Agent): boolean => !!ledProject(state, agent.id)&& !!state.machines?.find(m => m.machineId === agent.machineId)?.observation?.capabilities?.includes(INBOX_CAPABILITY)-/** Whether [message] to [recipient] waits for its inbox: a person's message or a crew need to a project's PM whose host sends- * its turn (INBOX_CAPABILITY). Results and notices are gathered as noticeDigest.ts says, whatever the host. */+/** Only crew needs wait for a turn-aware PM's inbox (#3609). People waited 2–15 minutes behind this gate;+ * their original messages now go straight to the session, while noticeDigest.ts still batches agents' notices. */export const gathersForInbox = (state: SuperTabState, recipient: Agent, message: { author: Pick<Author, 'kind'>; source?: unknown }): boolean =>- inboxSection(message) !== 'results' && turnInboxHost(state, recipient)+ inboxSection(message) === 'crew' && turnInboxHost(state, recipient)/** Whether the PM's gathered rows, oldest first, go out now. A read that sends no turn (an older host) keeps the notice* digest's own clock. One that does: when the oldest has waited TURN_END_WAIT_MS, whatever the turn; at idle, at once for adiff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 6c3ece716..b06612ffb 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -603,7 +603,11 @@ export function recordAgentPresence(state: SuperTabState, machineId: string, runif (running.includes(target.harnessId)) {delete target.downSincedelete target.downNamed- } else target.downSince = downSince(state, target, now) ?? new Date(now).toISOString()+ } else {+ // A stop is counted once, when a reading first shows the session gone; the last hour's, at most five (task #3662).+ if (!target.downSince) target.stops = [...(target.stops ?? []).filter(at => now - at < 3_600_000), now].slice(-5)+ target.downSince = downSince(state, target, now) ?? new Date(now).toISOString()+ }}}@@ -872,7 +876,7 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque}// A Buddy-only machine is recorded with its Buddy's start, before its host ever read the Swarm: the start waits for it.if (machineOffline(pool, now) && !(pool.buddyOnly && !pool.observation)) fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')- if (!start) admitByRoom(state, pool, slots(pool), request.requirements.memoryBytes)+ if (!start) admitByRoom(state, pool, slots(pool), request.requirements.memoryBytes, request.buddyOf ? 'a Buddy' : 'an agent')const machineReason = !start ? machineSuspensionReason(pool, now) : nullif (machineReason) fail('MACHINE_UNAVAILABLE', machineReason)// A new start only: a grid model runs without the engine's subscription, and one already asked for is settled by its host.@@ -943,9 +947,9 @@ export function availableSlots(state: SuperTabState, pool: ContributedMachine, ureturn free === null ? 0 : Math.min(ceiling, Math.floor(free / AGENT_MEMORY_BYTES))}-const gib = (bytes: number) => `${Math.round(bytes / 1024 ** 3 * 10) / 10} GB`+const gib = (bytes: number) => `${Math.round(bytes / 1024 ** 3 * 100) / 100} GB`/** A new start's room on [pool], said in words its owner can act on: its own count, or its free memory. */-export function admitByRoom(state: SuperTabState, pool: ContributedMachine, used: number, memoryBytes: number) {+export function admitByRoom(state: SuperTabState, pool: ContributedMachine, used: number, memoryBytes: number, who = 'an agent') {const limit = agentLimit(pool)if (limit !== null) {if (used >= limit) fail('MACHINE_FULL', `${pool.name} is set to run at most ${limit} agent${limit === 1 ? '' : 's'} and runs ${used}. Its owner can change that in its settings, or try again when one finishes.`)@@ -954,7 +958,7 @@ export function admitByRoom(state: SuperTabState, pool: ContributedMachine, usedif (used >= MACHINE_AGENTS_CEILING) fail('MACHINE_FULL', `${pool.name} already runs ${used} agents, the most any machine runs.`)const free = startableMemoryBytes(state, pool)if (free !== null && free < memoryBytes) {- fail('MACHINE_FULL', `${pool.name} is out of free memory: ${gib(free)} free, and an agent needs ${gib(memoryBytes)}. Try again when an agent there finishes, or pick another machine.`,+ fail('MACHINE_FULL', `${pool.name} is out of free memory: ${gib(free)} free, and ${who} needs ${gib(memoryBytes)}. Try again when an agent there finishes, or pick another machine.`,409, { reason: 'memory' })}}diff --git a/backend/src/superTabs/mergeTrain/plan.test.ts b/backend/src/superTabs/mergeTrain/plan.test.tsindex 58817ce50..284c8e4c6 100644--- a/backend/src/superTabs/mergeTrain/plan.test.ts+++ b/backend/src/superTabs/mergeTrain/plan.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import type { Check, Conversation } from '../model.js'-import { componentOf, eligible, headReads, laneOf, splitRed, type TrainCandidate, type TrainTask } from './plan.js'+import { componentOf, eligible, headReads, laneOf, skipReason, splitRed, type TrainCandidate, type TrainTask } from './plan.js'import { requiredReads, SEED_RULES } from '../policy.js'const URL = 'https://github.com/acme/app/pull/7'@@ -30,7 +30,7 @@ describe('headReads', () => {})it('refuses a pass at an older head with another patch', () => {const t = task({ steps: [step([check([{ passed: true, head: OLD, patch: 'p0' }])])] })- expect(headReads(t, URL, HEAD, 'main')).toBe(null)+ expect(headReads(t, URL, HEAD, 'main')).toEqual(expect.any(String))})it('keeps a pass at an older head whose patch is the same (a plain rebase)', () => {const t = task({ steps: [step([check([{ passed: true, head: OLD, patch: 'p1' }])])] })@@ -38,26 +38,26 @@ describe('headReads', () => {})it('never counts a pass with no head, though old clients still count it', () => {const t = task({ steps: [step([check([{ passed: true }])])] })- expect(headReads(t, URL, HEAD, 'main')).toBe(null)+ expect(headReads(t, URL, HEAD, 'main')).toEqual(expect.any(String))})it('never counts a stale pass, or one on another pull request', () => {- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, stale: { head: OLD } }])])] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, pullRequest: 'https://github.com/acme/app/pull/8' }])])] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, stale: { head: OLD } }])])] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, pullRequest: 'https://github.com/acme/app/pull/8' }])])] }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('refuses when the watch has not seen this head yet', () => {- expect(headReads(task({ pullRequestHeads: { [URL]: { head: OLD, patch: 'p1', at: 1, base: 'main' } } }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ pullRequestHeads: undefined }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ pullRequestHeads: { [URL]: { head: OLD, patch: 'p1', at: 1, base: 'main' } } }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ pullRequestHeads: undefined }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('refuses a failure at the head next to a pass', () => {const t = task({ steps: [step([check([{ passed: true, head: HEAD }, { passed: false, head: HEAD }])])] })- expect(headReads(t, URL, HEAD, 'main')).toBe(null)+ expect(headReads(t, URL, HEAD, 'main')).toEqual(expect.any(String))})it('needs a review step, every open step done, and the task checks too', () => {- expect(headReads(task({ steps: [] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test' })] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ steps: [...task().steps, step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test', assignment: { status: 'working' } as Conversation['assignment'] })] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ steps: [...task().steps, step([], { step: 'Test', title: 'Test' })] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ checks: [check([{ passed: true, head: OLD, patch: 'p0' }])] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test' })] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ steps: [...task().steps, step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test', assignment: { status: 'working' } as Conversation['assignment'] })] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ steps: [...task().steps, step([], { step: 'Test', title: 'Test' })] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ checks: [check([{ passed: true, head: OLD, patch: 'p0' }])] }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('counts each reviewer once, over every review step passed at the head', () => {const two = step([check([{ passed: true, head: HEAD }])], { step: 'Security review 2', title: 'Security review 2' })@@ -69,16 +69,16 @@ describe('headReads', () => {it('never counts the task\'s own builders as reads: its assignee or an earlier attempt\'s agent', () => {// The review step is passed by agent:r0 (the step helper's checker): as the builder, its pass counts for nothing, so the// step has no pass at all and the pull request may not merge, however many other steps passed.- expect(headReads(task({ builders: ['agent:r0'] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ builders: ['agent:r0'] }), URL, HEAD, 'main')).toEqual(expect.any(String))const two = step([check([{ passed: true, head: HEAD }])], { step: 'Security review 2', title: 'Security review 2' })two.checks[0]!.verdicts![0]!.by = 'agent:other'- expect(headReads(task({ steps: [...task().steps, two], builders: ['agent:r0'] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [...task().steps, two], builders: ['agent:r0'] }), URL, HEAD, 'main')).toEqual(expect.any(String))expect(headReads(task({ steps: [...task().steps, two], builders: ['agent:someone-else'] }), URL, HEAD, 'main')).toBe(2)})it('never counts a builder\'s pass of a test step, but keeps the builder\'s own task checks', () => {const tested = step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test' })tested.checks[0]!.verdicts![0]!.by = 'agent:builder'- expect(headReads(task({ steps: [...task().steps, tested], builders: ['agent:builder'] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [...task().steps, tested], builders: ['agent:builder'] }), URL, HEAD, 'main')).toEqual(expect.any(String))const own = task({ builders: ['agent:r0'] })own.steps[0]!.checks[0]!.verdicts![0]!.by = 'agent:reviewer'expect(headReads(own, URL, HEAD, 'main')).toBe(1)@@ -96,30 +96,58 @@ describe('headReads at the base it read (task #3493)', () => {it('never counts the same patch on a new base: a patch id names its base', () => {const t = task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p-main', at: 2, base: 'main' } },steps: [step([check([{ passed: true, head: OLD, patch: 'p-release', base: 'release' }])])] })- expect(headReads(t, URL, HEAD, 'main')).toBe(null)+ expect(headReads(t, URL, HEAD, 'main')).toEqual(expect.any(String))})it('never counts a verdict once the pull request was retargeted: the live base differs from the watched one', () => {// Ledger's case on #3218: passed at this head against another branch, retargeted to main before the watch's next pass.const t = task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p-release', at: 1, base: 'release' } },checks: [check([{ passed: true, head: HEAD, base: 'release' }])], steps: [step([check([{ passed: true, head: HEAD, base: 'release' }])])] })- expect(headReads(t, URL, HEAD, 'main')).toBe(null)+ expect(headReads(t, URL, HEAD, 'main')).toEqual(expect.any(String))})it('never counts a verdict naming no base, or another base, at the same head', () => {- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, base: undefined }])])] }), URL, HEAD, 'main')).toBe(null)- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, base: 'release' }])])] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, base: undefined }])])] }), URL, HEAD, 'main')).toEqual(expect.any(String))+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, base: 'release' }])])] }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('never counts a verdict naming no pull request, which the shared check reads against the latest watched head', () => {- expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, pullRequest: undefined }])])] }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ steps: [step([check([{ passed: true, head: HEAD, pullRequest: undefined }])])] }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('reads nothing from a head recorded before bases', () => {- expect(headReads(task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p1', at: 1 } } }), URL, HEAD, 'main')).toBe(null)+ expect(headReads(task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p1', at: 1 } } }), URL, HEAD, 'main')).toEqual(expect.any(String))})it('reads nothing when a base holds a control or format character, however it reads on screen', () => {const hidden = 'main\u200b'const t = task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p1', at: 1, base: hidden } },checks: [check([{ passed: true, head: HEAD, base: hidden }])], steps: [step([check([{ passed: true, head: HEAD, base: hidden }])])] })- expect(headReads(t, URL, HEAD, hidden)).toBe(null)- expect(headReads(task(), URL, HEAD, 'main\u202e')).toBe(null)+ expect(headReads(t, URL, HEAD, hidden)).toEqual(expect.any(String))+ expect(headReads(task(), URL, HEAD, 'main\u202e')).toEqual(expect.any(String))+ })+})++describe('headReads names the rule it fails (task #3902)', () => {+ const why = (t: TrainTask) => headReads(t, URL, HEAD, 'main')+ it('names a task check nobody passed: #3367 and #3370, whose steps all passed', () => {+ const unpassed: Check = { id: 'c0', description: 'A widget test per first-join path that fails without the fix', independent: false, evidence: null, passedBy: null }+ expect(why(task({ checks: [unpassed] }))).toBe('the task\'s check "A widget test per first-join path that fails without the fix": nobody has passed it yet')+ })+ it('names the step and what is wrong with it', () => {+ expect(why(task({ steps: [step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test', assignment: { status: 'working' } as Conversation['assignment'] })] })))+ .toBe('the Test step is not done')+ expect(why(task({ steps: [step([])] }))).toBe('the Review step has no checks')+ expect(why(task({ steps: [step([check([{ passed: true, head: OLD, patch: 'p0' }])])] })))+ .toBe('the Review step: no verdict was read at this head on this base: it moved since, or the verdict is marked stale')+ expect(why(task({ steps: [step([check([{ passed: true, head: HEAD }, { passed: false, head: HEAD }])])] }))).toBe('the Review step: a failed verdict counts at this head')+ expect(why(task({ builders: ['agent:r0'] }))).toContain('only the task\'s own builders passed it')+ expect(why(task({ steps: [step([check([{ passed: true, head: HEAD }])], { step: 'Test', title: 'Test' })] }))).toBe('no Review step has passed')+ })+ it('names the watch when it has not read this head or base', () => {+ expect(why(task({ pullRequestHeads: { [URL]: { head: OLD, patch: 'p1', at: 1, base: 'main' } } }))).toBe('the pull request watch has not read its head on GitHub yet')+ expect(why(task({ pullRequestHeads: undefined }))).toBe('the pull request watch has not read this pull request yet')+ expect(why(task({ pullRequestHeads: { [URL]: { head: HEAD, patch: 'p1', at: 1, base: 'release' } } }))).toBe('its base branch is not the one the pull request watch recorded')+ })+ it('counts a verdict at the current head by an agent that has since left the project: the train reads no roster', () => {+ const t = task()+ t.steps[0]!.checks[0]!.verdicts![0]!.by = 'agent:rowtest-who-left'+ expect(why(t)).toBe(1)})})@@ -142,7 +170,7 @@ describe('eligible', () => {expect(eligible(candidate(over), 1, 1)).toEqual({ ok: false, why })})it('refuses one whose verdicts are not at its head', () => {- expect(eligible(candidate(), null, 1)).toEqual({ ok: false, why: 'verdict' })+ expect(eligible(candidate(), 'nobody has passed it', 1)).toEqual({ ok: false, why: 'verdict' })})it('refuses one with fewer passed reads at its head than the review table asks', () => {expect(eligible(candidate(), 1, 2)).toEqual({ ok: false, why: 'reads' })@@ -185,3 +213,19 @@ describe('the rules record\'s seed for the train', () => {expect(SEED_RULES.mergeTrain).toEqual({ enabled: false, everyMinutes: 10 })})})++describe('skipReason (task #3902)', () => {+ it('names the rule in plain words, with a key that changes only when the reason does', () => {+ expect(skipReason('draft', candidate({ draft: true }), '')).toEqual({ key: 'draft', text: 'it is still a draft' })+ expect(skipReason('hold', candidate({ labels: ['hold'] }), '')?.text).toBe('it has the hold label')+ expect(skipReason('base', candidate({ base: 'release' }), '')?.text).toBe('it targets release, and the train merges only into main')+ expect(skipReason('ci', candidate({ ciRequired: 'pending' }), '')).toEqual({ key: 'ci:pending', text: 'ci/required is pending at its head' })+ expect(skipReason('ci', candidate({ ciRequired: null }), '')?.text).toBe('ci/required is not reported at its head')+ expect(skipReason('mergeable', candidate({ mergeable: null }), '')?.text).toContain('worked out')+ expect(skipReason('verdict', candidate(), 'the Test step is not done')).toEqual({ key: 'verdict:the Test step is not done',+ text: 'the train does not count its reviews and tests: the Test step is not done' })+ })+ it('stays silent where the Engineer already hears the reason as its own line, and for a closed pull request', () => {+ for (const why of ['closed', 'conflict', 'reads'] as const) expect(skipReason(why, candidate(), '')).toBeNull()+ })+})diff --git a/backend/src/superTabs/mergeTrain/plan.ts b/backend/src/superTabs/mergeTrain/plan.tsindex 02ad82488..b32196892 100644--- a/backend/src/superTabs/mergeTrain/plan.ts+++ b/backend/src/superTabs/mergeTrain/plan.ts@@ -30,6 +30,8 @@ export interface TrainTask {/** Each linked pull request's head and patch id as the PR watch last read them (task #3394). */pullRequestHeads?: Record<string, PullRequestHead>steps: Array<Pick<Conversation, 'step' | 'title' | 'checks' | 'archived' | 'assignment'>>+ /** Whether its Engineer set it done: only a done task hears why its pull request keeps waiting (skipReason). */+ done?: boolean/** Who built the task, as verdicts name checkers (`agent:ID`): its assignee and every earlier attempt's agent. Their verdicts* on its steps count for nothing: a builder is never its own review or test (review 1 of #3226). */builders?: string[]@@ -48,45 +50,57 @@ const plainBase = (base: string | undefined): base is string => !!base && !HIDDEconst countsFor = (verdict: CheckVerdict, url: string, heads: PullRequestHeads): boolean =>verdict.pullRequest === url && !!verdict.head && verdict.stale === undefined && verdictCounts(verdict, heads)-/** The checkers whose passes count on [check], or null when it has no pass that counts or a failure that does. */-function passers(check: Check, url: string, heads: PullRequestHeads, ignored: ReadonlySet<string> = new Set()): string[] | null {- const counting = (check.verdicts ?? []).filter(v => !ignored.has(v.by) && countsFor(v, url, heads))- if (!counting.length || counting.some(v => !v.passed)) return null- return counting.map(v => v.by)+/** The checkers whose passes count on [check], or in plain words why none does: a failure that counts, only the builders'+ * passes (ignored), no verdict at this head and base, or no verdict at all. A verdict by an agent that has since left the+ * project counts like any other: the train reads no roster. */+function passers(check: Check, url: string, heads: PullRequestHeads, ignored: ReadonlySet<string> = new Set()): string[] | string {+ const verdicts = check.verdicts ?? []+ const counting = verdicts.filter(v => countsFor(v, url, heads)), others = counting.filter(v => !ignored.has(v.by))+ if (others.some(v => !v.passed)) return 'a failed verdict counts at this head'+ if (others.length) return others.map(v => v.by)+ if (counting.length) return 'only the task\'s own builders passed it, and a builder is never its own review or test'+ return verdicts.length ? 'no verdict was read at this head on this base: it moved since, or the verdict is marked stale' : 'nobody has passed it yet'}/*** How many independent reads [task]'s pull request [url] has at [head], the head GitHub shows now: the reviewers whose review- * steps passed there, each once. Null when it may not merge whatever the count: the PR watch has not seen this head yet, no+ * steps passed there, each once. Otherwise, in plain words, the rule it fails: the PR watch has not seen this head yet, no* review step passed, or the task's own checks or another step (a test) did not pass at this head. A cancelled step does not* count either way; any other step must be done.*/-export function headReads(task: TrainTask, url: string, head: string, base: string): number | null {+export function headReads(task: TrainTask, url: string, head: string, base: string): number | string {const heads = task.pullRequestHeads, now = heads?.[url]// GitHub's live head and base must be the ones the watch read (task #3493, Ledger's case on #3218): a pull request retargeted// since then carries verdicts read against another branch, which the shared check still counts until the watch reads it.- if (!heads || !now || now.head.toLowerCase() !== head.toLowerCase() || !plainBase(now.base) || !plainBase(base) || now.base !== base) return null- if (!task.checks.every(check => passers(check, url, heads))) return null+ if (!heads || !now) return 'the pull request watch has not read this pull request yet'+ if (now.head.toLowerCase() !== head.toLowerCase()) return 'the pull request watch has not read its head on GitHub yet'+ if (!plainBase(now.base) || !plainBase(base) || now.base !== base) return 'its base branch is not the one the pull request watch recorded'+ for (const check of task.checks) {+ const found = passers(check, url, heads)+ if (typeof found === 'string') return `the task's check "${check.description.slice(0, 60)}": ${found}`+ }const readers = new Set<string>(), builders = new Set(task.builders ?? [])let reviewed = falsefor (const step of task.steps) {- const status = step.assignment?.status+ const status = step.assignment?.status, name = step.step ?? step.titleif (status === 'cancelled') continue- if (status !== 'done' || !step.checks.length) return null+ if (status !== 'done') return `the ${name} step is not done`+ if (!step.checks.length) return `the ${name} step has no checks`const found = step.checks.map(check => passers(check, url, heads, builders))- if (found.some(list => !list)) return null- if (REVIEW_STEP.test(step.step ?? step.title)) {+ const refused = found.find((list): list is string => typeof list === 'string')+ if (refused) return `the ${name} step: ${refused}`+ if (REVIEW_STEP.test(name)) {reviewed = true- for (const list of found) for (const by of list!) readers.add(by)+ for (const list of found) for (const by of list as string[]) readers.add(by)}}- return reviewed ? readers.size : null+ return reviewed ? readers.size : 'no Review step has passed'}export type Ineligible = 'closed' | 'draft' | 'base' | 'hold' | 'ci' | 'mergeable' | 'conflict' | 'verdict' | 'reads'/** Whether [candidate] may join a batch, given its [reads] at its head (headReads) and the reads its files need. */-export function eligible(candidate: TrainCandidate, reads: number | null, required: number): { ok: true } | { ok: false; why: Ineligible } {+export function eligible(candidate: TrainCandidate, reads: number | string, required: number): { ok: true } | { ok: false; why: Ineligible } {const no = (why: Ineligible) => ({ ok: false as const, why })if (candidate.state !== 'open') return no('closed')if (candidate.draft) return no('draft')@@ -95,11 +109,26 @@ export function eligible(candidate: TrainCandidate, reads: number | null, requirif (candidate.ciRequired !== 'success') return no('ci')if (candidate.mergeable === null) return no('mergeable')if (candidate.mergeable === false) return no('conflict')- if (reads === null) return no('verdict')+ if (typeof reads === 'string') return no('verdict')if (reads < required) return no('reads')return { ok: true }}+/** Why the train passes over [candidate] in plain words, with a key that changes only when the reason does; null when the+ * Engineer already hears it as its own line (a conflict, too few reads) or there is nothing to say (closed). [verdict] is the+ * rule headReads named. */+export function skipReason(why: Ineligible, candidate: TrainCandidate, verdict: string): { key: string; text: string } | null {+ switch (why) {+ case 'closed': case 'conflict': case 'reads': return null+ case 'draft': return { key: why, text: 'it is still a draft' }+ case 'base': return { key: why, text: `it targets ${candidate.base}, and the train merges only into main` }+ case 'hold': return { key: why, text: 'it has the hold label' }+ case 'ci': return { key: `${why}:${candidate.ciRequired}`, text: `ci/required is ${candidate.ciRequired ?? 'not reported'} at its head` }+ case 'mergeable': return { key: why, text: 'GitHub has not yet worked out whether it merges cleanly' }+ case 'verdict': return { key: `${why}:${verdict}`, text: `the train does not count its reviews and tests: ${verdict}` }+ }+}+/** `fast` when every file only documents or scripts (FAST_LANE): such a pull request merges on its own green CI. */export function laneOf(files: readonly string[]): 'fast' | 'code' {return files.length && files.every(file => FAST_LANE.some(lane => lane.test(file))) ? 'fast' : 'code'diff --git a/backend/src/superTabs/mergeTrain/train.test.ts b/backend/src/superTabs/mergeTrain/train.test.tsindex 584905f2c..345c37011 100644--- a/backend/src/superTabs/mergeTrain/train.test.ts+++ b/backend/src/superTabs/mergeTrain/train.test.ts@@ -317,6 +317,20 @@ describe('the merge train finishes batches', () => {expect(swarm.told).toHaveLength(1)})+ it('names the pull request a member left waiting after main moved shares a file with', async () => {+ const { repo, swarm, pass } = setup()+ const a = repo.addPull(7, ['backend/src/a.ts'])+ swarm.approve(a)+ await pass()+ const first = repo.batches()[0]!+ // Main moves, and an older pull request changing the same file is ready now: it goes first.+ repo.state.main = 'd'.repeat(40)+ swarm.approve(repo.addPull(5, ['backend/src/a.ts']))+ await pass()+ expect(swarm.told.map(t => t.key)).toEqual([`train-moved:${first.number}:${a.head}`])+ expect(swarm.told[0]!.text).toContain('changes a file that #5 also changes')+ })+it('says nothing on a member merged by hand meanwhile, often why main moved', async () => {const { repo, swarm, pass } = setup()const a = repo.addPull(7, ['backend/src/a.ts']), b = repo.addPull(8, ['cli/src/b.ts'])@@ -506,3 +520,80 @@ describe('the merge train finishes batches', () => {expect(repo.batches()).toHaveLength(1)})})++describe('the merge train says why it passes over a done task\'s pull request (task #3902)', () => {+ const doneTask = (swarm: ReturnType<typeof fakeSwarm>, pull: FakePull) => { swarm.approve(pull); swarm.tasks.get(`task-${pull.number}`)!.task.done = true }+ const unpassedCheck: Check = { id: 'c0', description: 'A widget test per first-join path', independent: false, evidence: null, passedBy: null }++ it('writes the rule once after two passes in a row, as for #3367: the steps passed but the task\'s own check never did', async () => {+ const { repo, swarm, pass } = setup()+ const a = repo.addPull(7, ['desktop/lib/a.dart'])+ doneTask(swarm, a)+ swarm.tasks.get('task-7')!.task.checks = [unpassedCheck]+ await pass()+ expect(swarm.told).toEqual([])+ await pass()+ expect(swarm.told).toEqual([expect.objectContaining({ taskId: 'task-7', key: expect.stringContaining('train-skip:'), text: expect.stringContaining('for 2 passes in a row') })])+ expect(swarm.told[0]!.text).toContain('the task\'s check "A widget test per first-join path": nobody has passed it yet')+ await pass(); await pass()+ expect(swarm.told).toHaveLength(1)+ expect(repo.batches()).toEqual([])+ })++ it('writes again only when the reason changes', async () => {+ const { repo, swarm, pass } = setup()+ const a = repo.addPull(7, ['desktop/lib/a.dart'])+ doneTask(swarm, a)+ swarm.tasks.get('task-7')!.task.checks = [unpassedCheck]+ await pass(); await pass()+ a.labels = ['hold']+ await pass()+ expect(swarm.told).toHaveLength(1)+ await pass()+ expect(swarm.told).toHaveLength(2)+ expect(swarm.told[1]!.text).toContain('it has the hold label')+ })++ it('counts passes in a row: a pass that read it eligible starts the count again', async () => {+ const { repo, swarm, pass } = setup()+ const a = repo.addPull(7, ['desktop/lib/a.dart'], { draft: true })+ doneTask(swarm, a)+ await pass()+ a.draft = false+ await pass()+ a.draft = true+ await pass()+ expect(swarm.told).toEqual([])+ })++ it('tells nothing for a task that is not done, a conflict or too few reads (their own lines), or an eligible pull request', async () => {+ const { repo, swarm, pass } = setup()+ const working = repo.addPull(7, ['desktop/lib/a.dart'], { draft: true })+ swarm.approve(working)+ const conflicting = repo.addPull(8, ['cli/src/b.ts'], { mergeable: false })+ doneTask(swarm, conflicting)+ const ready = repo.addPull(9, ['backend/src/c.ts'])+ doneTask(swarm, ready)+ for (let i = 0; i < 4; i++) await pass()+ expect(swarm.told.map(t => t.key)).toEqual([`train-conflict:${conflicting.head}`])+ })++ it('says a ready pull request waits for the next batch when it shares a file with one in the batch, pass after pass', async () => {+ const { repo, swarm, pass } = setup()+ const a = repo.addPull(7, ['backend/src/a.ts']), b = repo.addPull(8, ['backend/src/a.ts'])+ doneTask(swarm, a); doneTask(swarm, b)+ await pass()+ repo.state.main = 'f'.repeat(40)+ await pass()+ expect(swarm.told).toEqual([expect.objectContaining({ taskId: 'task-8', key: `train-skip:files:7:${b.head}` })])+ expect(swarm.told[0]!.text).toContain('changes a file that #7 also changes')+ })++ it('still batches a verdict at the current head by an agent that has since left the project', async () => {+ const { repo, swarm, pass } = setup()+ doneTask(swarm, repo.addPull(7, ['backend/src/a.ts']))+ swarm.approve(repo.state.pulls.get(7)!, ['agent:rowtest-who-left'])+ await pass()+ expect(repo.batches()).toHaveLength(1)+ })+})diff --git a/backend/src/superTabs/mergeTrain/train.ts b/backend/src/superTabs/mergeTrain/train.tsindex 1731971a2..c90313be5 100644--- a/backend/src/superTabs/mergeTrain/train.ts+++ b/backend/src/superTabs/mergeTrain/train.ts@@ -14,7 +14,7 @@*/import { TrainReadError, type TrainGitHub, type TrainPull } from '../../github/train.js'import { NOT_MERGEABLE_BY_TOKEN, TRAIN_BRANCH_PREFIX, TRAIN_CI_TIMEOUT_MS, TRAIN_MAX_BATCH } from './config.js'-import { eligible, headReads, laneOf, splitRed, type Ineligible, type TrainTask } from './plan.js'+import { eligible, headReads, laneOf, skipReason, splitRed, type Ineligible, type TrainTask } from './plan.js'import { requiredReads, type ProjectRules } from '../policy.js'/** A task's linked pull request, as the Swarm holds it: what headReads reads. */@@ -33,10 +33,15 @@ export interface TrainSwarm {interface Member { number: number; url: string; head: string; title: string; files: string[]; taskId: string }interface Batch { number: number; url: string; branch: string; tip: string; base: string; startedAt: number; members: Member[] }-/** What a worker remembers between passes, per project: its open batches, the heads that failed alone, and the parts of red- * batches still to run. Lost on a restart, which only closes and rebuilds what was open. */-export interface TrainMemory { batches: Map<number, Batch>; failed: Set<string>; splits: string[][] }-export const newTrainMemory = (): TrainMemory => ({ batches: new Map(), failed: new Set(), splits: [] })+/** What a worker remembers between passes, per project: its open batches, the heads that failed alone, the parts of red+ * batches still to run, and for each done task's pull request the reason it was passed over, how many passes in a row, and+ * whether its Engineer heard it. Lost on a restart, which only closes and rebuilds what was open (and counts the passes again;+ * a line already written is not written twice, whatever the memory). */+export interface TrainMemory { batches: Map<number, Batch>; failed: Set<string>; splits: string[][]; skips: Map<string, Skip> }+interface Skip { key: string; passes: number; told: boolean }+export const newTrainMemory = (): TrainMemory => ({ batches: new Map(), failed: new Set(), splits: [], skips: new Map() })+/** A done task's pull request is told why it is passed over after this many passes in a row. */+const SKIPS_BEFORE_TELLING = 2/** The project's rules record as this pass read it: its switch, the review table its reads come from (policy.ts), and the* minutes between passes, which the line to a waiting pull request names. */@@ -49,15 +54,8 @@ const batchLabel = (at: number) => { const d = new Date(at), two = (n: number) =return `${two(d.getUTCMonth() + 1)}-${two(d.getUTCDate())} train-${two(d.getUTCHours())}${two(d.getUTCMinutes())}` }const PULL = /\/pull\/([1-9][0-9]*)$/-/** Why a pull request the train read waits, in plain words, for the line to a member of a batch main moved under. */-const WAITS: Record<Ineligible, string> = {- closed: 'it is closed', draft: 'it is a draft', base: 'it no longer merges into main', hold: 'it has a hold label',- ci: 'ci/required is not green at its head', mergeable: 'GitHub has not worked out yet whether it merges cleanly',- conflict: 'it conflicts with main', verdict: 'a review or test does not count at its head, or a step is still open',- reads: 'it needs more passed reviews at its head',-}--interface Read { member: Member; verdict: { ok: true } | { ok: false; why: Ineligible }; reads: number | null; required: number; lane: 'fast' | 'code' }+interface Reason { key: string; text: string }+interface Read { member: Member; verdict: { ok: true } | { ok: false; why: Ineligible }; reads: number | string; required: number; lane: 'fast' | 'code'; skip: Reason | null }export async function trainPass(input: { projectId: string; github: TrainGitHub; swarm: TrainSwarm; memory: TrainMemory; now: number; rules: TrainRules }): Promise<TrainPassLine> {const { projectId, github, swarm, memory, now, rules } = input@@ -89,9 +87,11 @@ export async function trainPass(input: { projectId: string; github: TrainGitHub;const files = await github.files(number), ciRequired = await github.ciRequired(pull.head)const reads = headReads(linked.task, linked.url, pull.head, pull.base), required = requiredReads(rules.rules, files)const lane = laneOf(files), mergeable = building && lane === 'code' && pull.mergeable === null ? true : pull.mergeable- const verdict = eligible({ url: linked.url, number, head: pull.head, state: pull.state, draft: pull.draft, base: pull.base, mergeable,- labels: pull.labels, files, ciRequired }, reads, required)- return { member: { number, url: linked.url, head: pull.head, title: pull.title, files, taskId: linked.taskId }, verdict, reads, required, lane }+ const candidate = { url: linked.url, number, head: pull.head, state: pull.state, draft: pull.draft, base: pull.base, mergeable,+ labels: pull.labels, files, ciRequired }+ const verdict = eligible(candidate, reads, required)+ return { member: { number, url: linked.url, head: pull.head, title: pull.title, files, taskId: linked.taskId }, verdict, reads, required, lane,+ skip: verdict.ok ? null : skipReason(verdict.why, candidate, typeof reads === 'string' ? reads : '') }}const closeBatch = async (number: number, branch: string, why: string) => {@@ -192,21 +192,22 @@ export async function trainPass(input: { projectId: string; github: TrainGitHub;if (memory.batches.size) return line// Nothing open: read every candidate, merge the fast lane, and build the next batches.- // Why each pull request read waits: null where it had its own line this pass (a conflict, its reads, a workflow change), or- // where it went into a batch or main.- const reads: Read[] = [], waits = new Map<string, string | null>()+ // Why each pull request read waits, for the line to a member of a batch main moved under (#4379): null where it had its own+ // line this pass (a conflict, its reads, a workflow change), or where it went into a batch or main.+ const reads: Read[] = [], skipped: Array<{ member: Member; skip: Reason }> = [], waits = new Map<string, string | null>()for (const linked of taskOf.values()) {try {const found = await read(linked, true)if (!found || memory.failed.has(`${found.member.url}@${found.member.head}`)) continueline.candidates++const { member, verdict } = found+ if (found.skip) skipped.push({ member, skip: found.skip })waits.set(member.url, verdict.ok ? 'it did not fit the new batch (another pull request in it changes the same files, or it was full)'- : verdict.why === 'conflict' || verdict.why === 'reads' ? null : WAITS[verdict.why])+ : found.skip?.text ?? null)if (!verdict.ok && verdict.why === 'conflict') await tellConflict(swarm, member)else if (!verdict.ok && verdict.why === 'reads') {await swarm.tell(member.taskId, member.url, `train-reads:${member.head}`,- `Your pull request #${member.number} needs ${found.required} passed reviews at its head (${member.head.slice(0, 7)}) before the merge train takes it; it has ${found.reads}. ${member.url}`)+ `Your pull request #${member.number} needs ${found.required} passed reviews at its head (${member.head.slice(0, 7)}) before the merge train takes it; it has ${found.reads as number}. ${member.url}`)} else if (verdict.ok && member.files.some(file => NOT_MERGEABLE_BY_TOKEN.test(file))) {await swarm.tell(member.taskId, member.url, `train-workflows:${member.head}`,`Your pull request #${member.number} changes CI workflows, which the merge train cannot merge: merge it by hand. ${member.url}`)@@ -236,7 +237,15 @@ export async function trainPass(input: { projectId: string; github: TrainGitHub;}const code = reads.filter(r => r.lane === 'code').map(r => r.member)const groups = (memory.splits.length ? memory.splits.map(urls => code.filter(m => urls.includes(m.url))) : [code])- .map(disjoint).filter(group => group.length)+ .map(group => {+ const kept = disjoint(group)+ for (const member of group) if (!kept.includes(member)) {+ const skip = leftOut(member, kept)+ skipped.push({ member, skip })+ waits.set(member.url, skip.text)+ }+ return kept+ }).filter(group => group.length)memory.splits = []for (const [index, group] of groups.entries()) {const branch = `${prefix}${now}-${index}`@@ -270,10 +279,38 @@ export async function trainPass(input: { projectId: string; github: TrainGitHub;await github.deleteBranch(branch).catch(() => {})}}+ await tellSkips(swarm, memory, skipped, taskOf)await tellMoved(swarm, moved, waits, rules.everyMinutes)return line}+/** Why [member], ready, is not in the batch of [kept]: it shares a file with one that is, or the batch is full. */+function leftOut(member: Member, kept: readonly Member[]): Reason {+ const sharing = kept.find(other => other.files.some(file => member.files.includes(file)))+ return sharing ? { key: `files:${sharing.number}`, text: `it is ready, but changes a file that #${sharing.number} also changes, so it waits for the next batch` }+ : { key: 'full', text: `it is ready, but the batch is full (${TRAIN_MAX_BATCH} pull requests), so it waits for the next batch` }+}++/**+ * Tells the Engineer of a done task why its pull request was passed over (task #3902): once the same reason held for+ * [SKIPS_BEFORE_TELLING] passes in a row, and again only when the reason changes. A pass that did not read a pull request, or+ * found it eligible and batched, ends its count. The line is written once per reason and head whatever the memory (trainTell).+ */+async function tellSkips(swarm: TrainSwarm, memory: TrainMemory, skipped: ReadonlyArray<{ member: Member; skip: Reason }>, taskOf: ReadonlyMap<string, TrainTaskPull>) {+ const next = new Map<string, Skip>()+ for (const { member, skip } of skipped) {+ if (!taskOf.get(member.url)?.task.done) continue+ const before = memory.skips.get(member.url), same = before?.key === skip.key+ const entry: Skip = { key: skip.key, passes: same ? before.passes + 1 : 1, told: same && before.told }+ next.set(member.url, entry)+ if (entry.passes < SKIPS_BEFORE_TELLING || entry.told) continue+ await swarm.tell(member.taskId, member.url, `train-skip:${skip.key}:${member.head}`,+ `The merge train has passed over your pull request #${member.number} for ${entry.passes} passes in a row: ${skip.text}. ${member.url}`)+ entry.told = true+ }+ memory.skips = next+}+/** Tells each member of a batch closed because main moved (task #4379) that the train read again and that went into no new* batch why it waits and when the next batch starts: once per closed batch and head. One merged by hand meanwhile, or one* told by its own line this pass, hears nothing more. */diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 68e50ea4a..b87aca6fe 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -45,7 +45,7 @@ export interface AgentConfiguration {engineVersion: string | null}/** Why a crew member must leave its machine (crewKeep.ts). */-export type CrewTrouble = 'offline' | 'signed-out' | 'quota' | 'disk'+export type CrewTrouble = 'offline' | 'signed-out' | 'quota' | 'disk' | 'quota-low' | 'unstable'export interface Agent {id: string@@ -130,6 +130,9 @@ export interface Agent {* work.assign clears it and the host reopens it in place. `folderDropped` once a cleanup rule removed its folder, so a* wake starts it fresh. Set only by the server. */asleep?: { since: number; folderDropped?: boolean }+ /** When a reading first showed its session gone, in the last hour, at most five (machines.ts recordAgentPresence): a crew member+ * that stops three times in an hour is moved, not reopened in place (crewKeep.ts, task #3662). */+ stops?: number[]/** A crew member being moved off a failing machine (crewKeep.ts): its start on [machineId] takes over under the same name;* until then nothing is assigned to it and its old host closes the session. Set only by the server. */movedTo?: { machineId: string; startId: string; reason: CrewTrouble; at: number }@@ -787,6 +790,8 @@ export interface MessageDraft {author: Authortext: stringreplyTo: string | null+ /** Explicit answer in main chat, without a thread. */+ answers?: stringrecipients: string[]/** Buddies this row is news for (buddyNews.ts): a delivery each, never listed among its recipients. */buddyRecipients?: string[]@@ -858,6 +863,10 @@ export const NOTICE_READERS = {// 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',+ // An agent's question to a person in a switched project, in their default Buddy chat (decisions.ts askedThroughBuddy, #3826).+ 'decision-asked': 'people',+ // A decision its person must agree to reached its time unanswered, told to the PM alone (decisions.ts mustAgreePassed).+ 'decision-must-agree': 'recipients',// 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',// "<machine> left the Swarm: ..." in every project chat, no longer written (anh Dee, 11-04, #2742): the rows stored before are@@ -959,6 +968,8 @@ export interface CommandEffects {/** Decisions asked, and a decision answered, written outside the tab state by the store (decisions.ts). */decisions?: import('./decisions.js').DecisionDraft[]decisionAnswer?: import('./decisions.js').DecisionAnswer+ /** A must-agree decision past its time, kept waiting for its person (decisions.ts keepWaiting). */+ decisionKeptWaiting?: string/** Deliveries of messages already stored: a Buddy thread session's first messages, sent while it started (buddySessions.ts). *//** `lead`: a project's Lead hearing its person's messages sent while the chat had none (leadStart.ts leadArrived). */lateDeliveries?: Array<{ messageId: string; conversationId: string; agentId: string; author: { kind: 'person'; id: string; generation: string }; lead?: true }>diff --git a/backend/src/superTabs/overdueDecisions.ts b/backend/src/superTabs/overdueDecisions.tsindex 4e519843b..a9a883872 100644--- a/backend/src/superTabs/overdueDecisions.ts+++ b/backend/src/superTabs/overdueDecisions.ts@@ -12,11 +12,12 @@ const at = (ms: number) => ({ $date: new Date(ms).toISOString() })* The still-waiting decisions asked in `(now - 8 days, now - 24h]`, oldest first, at most `limit` a pass. One `aggregateRaw` on the* `decision_waiting_created` index, never a Prisma `in` (backend/AGENTS.md). `answeredAt: null` matches a missing field too, as intended.* No cursor is kept: a row that fails or exceeds the cap is read again by every later pass until it is 8 days old, and a person- * answering removes it from the index range. Routing proposals (`kind`) and withdrawn decisions are never the PM's to take.+ * answering removes it from the index range. Routing proposals (`kind`), withdrawn decisions and those the person must agree to+ * (`mustAgree`, task #3826) are never the PM's to take.*/export async function overdueDecisions(db: PrismaClient, now: number, limit = OVERDUE_PER_PASS): Promise<Array<{ tabId: string; id: string; personId: string }>> {const rows = await db.superTabDecision.aggregateRaw({ pipeline: [- { $match: { answeredAt: null, defaultAt: null, createdAt: { $gt: at(now - OVERDUE_REACH_MS), $lte: at(now - OVERDUE_DECISION_MS) }, withdrawn: { $ne: true }, kind: { $ne: REFLECTION_DECISION } } },+ { $match: { answeredAt: null, defaultAt: null, createdAt: { $gt: at(now - OVERDUE_REACH_MS), $lte: at(now - OVERDUE_DECISION_MS) }, withdrawn: { $ne: true }, kind: { $ne: REFLECTION_DECISION }, mustAgree: { $ne: true } } },{ $sort: { createdAt: 1 } }, { $limit: limit }, { $project: { _id: 1, tabId: 1, personId: 1 } }] }) as unknown as Array<Record<string, unknown>>return rows.map(row => ({ tabId: String(row.tabId), id: String(row._id), personId: String(row.personId) }))}diff --git a/backend/src/superTabs/pulse.test.ts b/backend/src/superTabs/pulse.test.tsindex d032dcf22..e6629be76 100644--- a/backend/src/superTabs/pulse.test.ts+++ b/backend/src/superTabs/pulse.test.ts@@ -10,6 +10,7 @@ import { sweepForLead } from './liveness.js'import { projectsOf } from './projects.js'import { recordPulse, storedPulse } from './pulse.js'import { owner, stepsFixture } from './steps.test-support.js'+import { owedLines } from './inbox.js'const MINUTE = 60_000/** What a task an agent opens must say (commands.ts): at least one check, with a priority and who asked. */@@ -28,7 +29,7 @@ function setup() {return effects.result.messageId as string}const owed = (on = 'lead') => (f.group(on).owed ?? []).map(ask => ask.id)- const react = (by: string, on: string, messageId: string, emoji: string) => f.run({ type: 'message.react', conversationId: on, messageId, emoji, on: true } as Command,+ const react = (by: string, on: string, messageId: string, emoji: string, add = true) => f.run({ type: 'message.react', conversationId: on, messageId, emoji, on: add } as Command,f.as(by), { reaction: { messageId, reacted: false } })const request = (id: string) => ({ id, conversationId: 'lead', replyTo: null, source: null, author: person })const taskFrom = (ask: string) => f.run({ type: 'conversation.create', title: 'From the ask', brief: 'Do it.', checks: DONE_WHEN, priority: 'P2', requestMessageId: ask } as Command,@@ -79,18 +80,25 @@ describe('what the PM owes', () => {expect(owed()).toEqual([first])})- it('is settled by the PM\'s verdict reaction, never by eyes', () => {+ it.each(['thumbs_up', 'tada', 'heart', 'laugh', 'eyes', 'check', 'rocket'])('is settled by the PM’s %s reaction without needing words', emoji => {const { f, post, owed, react } = setup()- const ask = post(null, 'lead', 'Please merge #12.')- react(f.lead, 'lead', ask, 'eyes')- expect(owed()).toEqual([ask])- react(f.lead, 'lead', ask, 'check')+ const ask = post(null, 'lead', 'The PM has more tabs than my browser 😂')+ react(f.lead, 'lead', ask, emoji)expect(owed()).toEqual([])- for (const emoji of ['thumbs_up', 'rocket', 'tada']) {- const next = post(null, 'lead', `Another ${emoji}.`)- react(f.lead, 'lead', next, emoji)- expect(owed()).toEqual([])- }+ const project = projectsOf(f.state)[0]!+ // Main's inbox also lists unread process notes (#3298): only the owed-ask lines matter here.+ expect(owedLines(f.state, project, f.now).join('\n')).not.toMatch(/Owed asks/)+ expect(storedPulse(f.state, project)!.asks.count).toBe(0)+ })++ it('lets the PM decide a question needs only a reaction, without settling its thread siblings', () => {+ const { f, post, owed, react } = setup()+ const ask = post(null, 'lead', 'Are we collecting tabs now?')+ const sibling = post(null, 'lead', 'And a second message.', { reply: ask })+ react(f.lead, 'lead', ask, 'eyes', false)+ expect(owed()).toEqual([ask, sibling])+ react(f.lead, 'lead', ask, 'eyes')+ expect(owed()).toEqual([sibling])})it('is settled by a task the PM opens from it', () => {@@ -244,11 +252,11 @@ describe('the pulse', () => {it('says when each red rule turns red, by the limits it sends', () => {const { f, post } = setup()- expect(pulseOf(f).limits).toEqual({ askMinutes: 15, idleMinutes: 10, lostMinutes: 10 })+ expect(pulseOf(f).limits).toEqual({ askMinutes: 5, idleMinutes: 10, lostMinutes: 10 })expect(pulseOf(f).redAt).toEqual({ asks: null, idle: null, lost: null, held: null })post(null, 'lead', 'An ask.')const askedAt = f.now- expect(pulseOf(f).redAt.asks).toBe(askedAt + 15 * MINUTE)+ expect(pulseOf(f).redAt.asks).toBe(askedAt + 5 * MINUTE)status(f, f.task, f.dev, 'blocked', null)expect(pulseOf(f).redAt.held).toBe(0)})diff --git a/backend/src/superTabs/pulse.ts b/backend/src/superTabs/pulse.tsindex 1ab1a0aa6..2c1e33fb7 100644--- a/backend/src/superTabs/pulse.ts+++ b/backend/src/superTabs/pulse.ts@@ -4,7 +4,7 @@* unanswered for 3-10 h: nothing tracked what the PM owed, and the idle checks ran only on the PM's poll.** An owed ask is a person's message that reached the PM, kept on its conversation (`Conversation.owed`) until the PM answers- * it in its place (a reply in its thread, or an answer right below it), gives it a verdict reaction, or opens a task from it.+ * it in its place (a reply in its thread, or an answer right below it), explicitly reacts, or opens a task from it.* Nothing here refuses anything: a settle that finds nothing does nothing.*/import { isBuddy, isBuddyChat } from './buddies.js'@@ -21,8 +21,6 @@ export interface OwedAsk { id: string; personId: string; at: number; thread: str/** At most this many asks are kept per conversation, the newest: a growth bound, far above what a PM leaves unanswered. */export const MAX_OWED = 50-/** The reactions that answer an ask (reactions.ts): a verdict. Eyes says the PM saw it, and it still owes the answer. */-export const VERDICT_REACTIONS: ReadonlySet<string> = new Set(['check', 'thumbs_up', 'rocket', 'tada'])/** The project [group] belongs to, or none for a conversation outside every project (the removed Leads chat, a person's one* Buddy chat). Never throws: the pulse is never a reason for a command to fail. */@@ -42,7 +40,7 @@ const counted = (group: Conversation): boolean => !group.audience && !group.kind/** Records [message] as owed when a person wrote it and it reached [group]'s PM. */export function owe(state: SuperTabState, group: Conversation, message: { id: string; author: Author; recipients: readonly string[]; thread: string | null; source?: unknown }, now: number): void {- if (message.author.kind !== 'person' || message.source || !counted(group)) return+ if (message.author.kind !== 'person' || (message.source && (message.source as { kind?: string }).kind !== 'buddy-proposal') || !counted(group)) returnconst project = projectOfGroup(state, group)const pm = project && pmOf(state, project)// A project switched to the Board way of working owes its PM no chat messages (boardRights.ts, task #3819).@@ -71,9 +69,9 @@ export function settleReply(state: SuperTabState, group: Conversation, agentId:settle(group, ask => ask.id === place.answers || (!!place.thread && ask.thread === place.thread))}-/** The PM's verdict reaction on [messageId] settles it. */-export function settleReaction(state: SuperTabState, group: Conversation, agentId: string, messageId: string, emoji: string, on: boolean): void {- if (!on || !VERDICT_REACTIONS.has(emoji) || !group.owed || !byPm(state, group, agentId)) return+/** The PM's explicit reaction on [messageId] settles it. Automatic receipt eyes never call this command path (#3663). */+export function settleReaction(state: SuperTabState, group: Conversation, agentId: string, messageId: string, on: boolean): void {+ if (!on || !group.owed || !byPm(state, group, agentId)) returnsettle(group, ask => ask.id === messageId)}@@ -92,7 +90,7 @@ export function settleRequest(state: SuperTabState, project: SwarmProject, agent/** When each rule turns the strip red (anh Dee's brief), sent with the pulse so no app holds a threshold. */export interface PulseLimits { askMinutes: number; idleMinutes: number; lostMinutes: number }-export const PULSE_LIMITS: PulseLimits = { askMinutes: 15, idleMinutes: 10, lostMinutes: 10 }+export const PULSE_LIMITS: PulseLimits = { askMinutes: 5, idleMinutes: 10, lostMinutes: 10 }/** A project's pulse. `redAt`: when each rule turns red (0: already, by its nature), null while it cannot. */export interface Pulse {diff --git a/backend/src/superTabs/scorecard/figures.test.ts b/backend/src/superTabs/scorecard/figures.test.tsindex d2b5b638f..4a7a9e7f3 100644--- a/backend/src/superTabs/scorecard/figures.test.ts+++ b/backend/src/superTabs/scorecard/figures.test.ts@@ -225,3 +225,50 @@ describe('crew wake and move times (#3462)', () => {expect(figures.crewWake).toEqual({ count: 0, medianSeconds: null, slowestSeconds: null })})})+++describe('PM first-answer time (#3609)', () => {+ it('times each main ask, thread follow-up and Buddy relay to its first PM answer in place', () => {+ const main = person('chat', at(1), { id: 'main', recipientIds: ['pm'] })+ const follow = person('chat', at(2), { id: 'follow', thread: 'root', recipientIds: ['pm'] })+ const relay = person('chat', at(3), { id: 'relay', source: { kind: 'buddy-proposal' }, recipientIds: ['pm'] })+ const messages = [main, follow, relay,+ row({ conversationId: 'chat', createdAt: at(1) + 10_000, answers: 'main' }),+ row({ conversationId: 'chat', createdAt: at(1) + 90_000, answers: 'main' }),+ row({ conversationId: 'chat', createdAt: at(2) + 30_000, thread: 'root' }),+ row({ conversationId: 'chat', createdAt: at(3) + 50_000, answers: 'relay' })]+ expect(scorecardDay(input({ messages: [...messages, ...messages] })).pmAnswer).toEqual({ count: 3, medianSeconds: 30, slowestSeconds: 50 })+ })++ it('ignores other agents, wrong places, earlier thread answers, cards, and reaction/delivery timestamps', () => {+ const ask = person('chat', at(1), { id: 'ask', thread: 'root', recipientIds: ['pm'] })+ const unseen = person('task', at(1), { id: 'unseen', recipientIds: ['worker'] })+ const messages = [ask, unseen,+ row({ conversationId: 'chat', createdAt: at(0), thread: 'root' }),+ row({ conversationId: 'chat', createdAt: at(2), answers: 'ask', author: { kind: 'agent', id: 'worker' } }),+ row({ conversationId: 'other', createdAt: at(3), answers: 'ask', thread: 'root' }),+ row({ conversationId: 'chat', createdAt: at(4), source: { kind: 'task-line' }, answers: 'ask' }),+ row({ conversationId: 'task', createdAt: at(4), answers: 'unseen' })]+ expect(scorecardDay(input({ messages, answeredDeliveries: [{ messageId: 'ask', answeredAt: at(2) }] })).pmAnswer)+ .toEqual({ count: 0, medianSeconds: null, slowestSeconds: null })+ })++ it('counts first answers completed today across midnight, never a second answer today or one after the day', () => {+ const messages = [+ person('chat', START - 20_000, { id: 'overnight', recipientIds: ['pm'] }),+ row({ conversationId: 'chat', createdAt: START + 10_000, answers: 'overnight' }),+ person('chat', START - 60_000, { id: 'yesterday', recipientIds: ['pm'] }),+ row({ conversationId: 'chat', createdAt: START - 30_000, answers: 'yesterday' }),+ row({ conversationId: 'chat', createdAt: START + 20_000, answers: 'yesterday' }),+ person('chat', END - 20_000, { id: 'tomorrow', recipientIds: ['pm'] }),+ row({ conversationId: 'chat', createdAt: END, answers: 'tomorrow' })]+ expect(scorecardDay(input({ messages })).pmAnswer).toEqual({ count: 1, medianSeconds: 30, slowestSeconds: 30 })+ })+})+++it('orders a same-millisecond PM answer after its ask by stored sequence', () => {+ const ask = person('chat', at(1), { id: 'instant', recipientIds: ['pm'], sequence: 10 })+ const answer = row({ conversationId: 'chat', createdAt: at(1), answers: 'instant', sequence: 11 })+ expect(scorecardDay(input({ messages: [answer, ask] })).pmAnswer).toEqual({ count: 1, medianSeconds: 0, slowestSeconds: 0 })+})diff --git a/backend/src/superTabs/scorecard/figures.ts b/backend/src/superTabs/scorecard/figures.tsindex 04a1a3f41..35808b9b2 100644--- a/backend/src/superTabs/scorecard/figures.ts+++ b/backend/src/superTabs/scorecard/figures.ts@@ -17,8 +17,13 @@ export interface ScorecardMessage {source: Record<string, unknown> | nulltext: stringreplyTo: string | null+ /** Durable main-chat answer link; absent on older messages. */+ answers?: string | null+ recipientIds?: string[]+ private?: booleanthread: string | nullcreatedAt: number+ sequence?: number/** People the post tagged. */mentions?: string[]}@@ -71,7 +76,9 @@ export interface ScorecardFigures {typedIntoPm: numberackPosts: numberagentPosts: number- /** The day's crew wakes and moves, from start to running again (crewTimes.ts, task #3462). Absent on days stored before. */+ /** First PM replies completed in this day, in seconds; absent on older scorecards. */+ pmAnswer?: CrewTimes+ /** The day's crew wakes and moves; absent on older scorecards. */crewWake?: CrewTimescrewMove?: CrewTimes}@@ -131,7 +138,7 @@ export function scorecardDay(input: ScorecardInput): ScorecardFigures {const { start, end } = inputconst limits = input.limits ?? { ...SCORECARD_LIMITS }const inDay = (t: number) => t >= start && t < end- const messages = [...new Map(input.messages.map(m => [m.id, m])).values()].sort((a, b) => a.createdAt - b.createdAt)+ const messages = [...new Map(input.messages.map(m => [m.id, m])).values()].sort((a, b) => a.createdAt - b.createdAt || (a.sequence ?? 0) - (b.sequence ?? 0))const byId = new Map(messages.map(m => [m.id, m]))const pm = new Set(input.pmAgentIds)const dayRows = messages.filter(m => inDay(m.createdAt))@@ -168,9 +175,41 @@ export function scorecardDay(input: ScorecardInput): ScorecardFigures {ackPosts: ownPosts.filter(m => isAcknowledgement(m.text)).length,agentPosts: ownPosts.length,...crewTimesOf(dayRows, input.chatId),+ pmAnswer: pmAnswerTimes(input, messages),}}+/** Consume rows in time order, removing a pending ask on its first PM reply. Reactions and task creation+ * never count as replies. Per-thread sets avoid comparing every ask with every message in a busy week. */+function pmAnswerTimes(input: ScorecardInput, messages: ScorecardMessage[]): CrewTimes {+ const pm = new Set(input.pmAgentIds), pending = new Map<string, ScorecardMessage>()+ const threads = new Map<string, Set<string>>(), times: number[] = []+ const key = (m: ScorecardMessage) => JSON.stringify([m.conversationId, m.thread ?? m.id])+ const settle = (id: string, reply: ScorecardMessage) => {+ const ask = pending.get(id)+ if (!ask || ask.conversationId !== reply.conversationId) return+ pending.delete(id)+ threads.get(key(ask))?.delete(id)+ if (reply.createdAt >= input.start && reply.createdAt < input.end) times.push((reply.createdAt - ask.createdAt) / 1000)+ }+ for (const message of messages) {+ if (message.createdAt >= input.end || message.private) continue+ if (isAsk(message) && message.recipientIds?.some(id => pm.has(id))) {+ pending.set(message.id, message)+ const thread = key(message)+ if (!threads.has(thread)) threads.set(thread, new Set())+ threads.get(thread)!.add(message.id)+ } else if (message.author.kind === 'agent' && pm.has(message.author.id) && !message.source) {+ const direct = message.answers ?? message.replyTo+ if (direct) settle(direct, message)+ if (message.thread && message.thread !== message.id) {+ for (const id of threads.get(key(message)) ?? []) settle(id, message)+ }+ }+ }+ return { count: times.length, medianSeconds: median(times), slowestSeconds: times.length ? Math.max(...times) : null }+}+/** The day's crew wakes and moves (crewTimes.ts): the server's timing rows in the project chat, never a person's row or one in* another conversation. The chat is read back further than the day, so the rows are the day's already (dayRows). */function crewTimesOf(dayRows: ScorecardMessage[], chatId: string): { crewWake: CrewTimes; crewMove: CrewTimes } {diff --git a/backend/src/superTabs/scorecard/records.ts b/backend/src/superTabs/scorecard/records.tsindex 7923eec47..d5c92b6a8 100644--- a/backend/src/superTabs/scorecard/records.ts+++ b/backend/src/superTabs/scorecard/records.ts@@ -24,7 +24,7 @@ const DAY_ROW_CAP = 10_000const GROUP_FIELDS = { _id: 0, key: 1, 'data.id': 1, 'data.kind': 1, 'data.number': 1, 'data.reviewOf': 1, 'data.leadId': 1, 'data.ledger.askedAt': 1,'data.ledger.shippedAt': 1, 'data.ledger.fixedAfterMergeAt': 1, 'data.ledger.runs.at': 1, 'data.ledger.proposal.messageId': 1,- 'data.cards.line.messageId': 1 }+ 'data.cards.line.messageId': 1, 'data.audience': 1 }export interface ScorecardRecords { input: ScorecardInput; capped: number }@@ -44,8 +44,8 @@ async function projectGroups(tx: Transaction, tabId: string, projectId: string,const asMessage = (row: SuperTabMessage): ScorecardMessage => {const author = row.author as { kind?: string; id?: string } | nullreturn { id: row.id, conversationId: row.conversationId, author: { kind: author?.kind === 'person' ? 'person' : 'agent', id: String(author?.id ?? '') },- source: (row.source ?? null) as Record<string, unknown> | null, text: row.text, replyTo: row.replyTo ?? null, thread: row.thread ?? null,- createdAt: row.createdAt.getTime(), mentions: row.mentions ?? [] }+ source: (row.source ?? null) as Record<string, unknown> | null, text: row.text, replyTo: row.replyTo ?? null, answers: row.answers ?? null, recipientIds: row.recipientIds, thread: row.thread ?? null,+ createdAt: row.createdAt.getTime(), sequence: row.sequence, mentions: row.mentions ?? [] }}/** A row that says a task's phase (figures.ts): a status, a loss or a resume. */@@ -88,10 +88,10 @@ export async function scorecardRecords(tx: Transaction, at: { tabId: string; proconst isChat = group.id === chatId// A Buddy chat is a person's own, not the project's work.if (group.kind && !isChat) continue- const from = isChat ? end - SCORECARD_LIMITS.askLookbackDays * DAY : start+ const from = end - SCORECARD_LIMITS.askLookbackDays * DAYconst read = await groupRows(tx, tabId, group.id, from, !isChat, isChat ? CHAT_ROW_CAP : GROUP_ROW_CAP)if (read.capped) capped++- messages.push(...read.rows)+ messages.push(...read.rows.map(row => ({ ...row, ...group.audience ? { private: true } : {} })))}// The rows people replied to in the day, wherever they are: whether a PM wrote them. Matched by id alone (pageReads.ts).const have = new Set(messages.map(m => m.id))diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex f4deebf17..92e0540e2 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -131,7 +131,7 @@ import { closeAssignment, closeUnassignedStart, LIST_SIZE, newestConversations,import { answeredAgents, dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByAnswer, resolveByReply, resolveTags, resolveWhenWorked, writeMentions } from './mentions.js'import { stuckAlerts } from './stuck.js'import { OVERDUE_PER_PASS, overdueDecisions, dueDefaultDecisions } from './overdueDecisions.js'-import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'+import { answerable, askDecisions, DECISION_ASKED_KIND, keepWaiting, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'import { recordMessageRead, type MessageReadKey } from './messageReadStats.js'import { recordMessageReach } from './messageReachStats.js'@@ -1653,9 +1653,11 @@ export class SuperTabStore {const person = await this.db.user.findUnique({ where: { id: row.personId }, select: { email: true } })if (!autonomousEnv || !person) { await withdrawDefault(row); result.skipped++; continue }const user: AuthUser = { sub: row.personId, email: person.email, autonomousEnv, role: 'user' }- await this.executeOnce(user, row.tabId, { operationId: `${row.defaulted ? 'default' : 'overdue'}-decision-${row.id}`, command: { type: 'decision.answer', decisionId: row.id, delegate: true } },+ const done = await this.executeOnce(user, row.tabId, { operationId: `${row.defaulted ? 'default' : 'overdue'}-decision-${row.id}`, command: { type: 'decision.answer', decisionId: row.id, delegate: true } },undefined, undefined, false, row.defaulted ? { defaulted: true } : { overdue: true })- result.answered+++ // One its person must agree to waits for them: not answered, so skipped.+ if (done.result.keptWaiting) result.skipped+++ else result.answered++} catch (error) {const code = error instanceof SuperTabError ? error.code : 'unknown'// Answered meanwhile, a recommendation out of range, or the person or Swarm gone: nothing for the sweep to do.@@ -2216,6 +2218,14 @@ export class SuperTabStore {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)+ // Resolve repeats before numbering or writing Buddy notices: a repeated ask is the existing decision, already told.+ const decisionIds = effects.decisions ? await writeDecisions(tx, tabId, effects.decisions, context.now) : []+ const newDecisions = effects.decisions?.filter((draft, i) => decisionIds[i] === draft.id) ?? []+ if (effects.decisions) {+ if (command.type === 'decision.ask') effects.result.decisionIds = decisionIds+ const fresh = new Set(newDecisions.map(d => d.id))+ effects.messages = effects.messages.filter(m => m.source?.kind !== DECISION_ASKED_KIND || fresh.has(String(m.source.decisionId)))+ }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.const shown = effects.messages.filter(message => !agentOnly(message.source, message.recipients))@@ -2476,14 +2486,10 @@ export class SuperTabStore {if (taken.count !== 1) fail('AVATAR_UNAVAILABLE', 'Upload this picture again before using it.', 400)}if (effects.closedProposal) await closeProposal(tx, tabId, effects.closedProposal, actor.kind === 'person' ? actor.userId : actor.agentId, new Date(context.now))- if (effects.decisions) {- const ids = await writeDecisions(tx, tabId, effects.decisions, context.now)- if (command.type === 'decision.ask') effects.result.decisionIds = ids- // A decision new in this write reaches its person's phones (task #3248); one asked again is the open one, told already.- const asked = effects.decisions.filter((draft, i) => ids[i] === draft.id)- this.tellPhones(tx, tabId, effects.state, { replies: [], tags: [], decisions: asked }, [])- }+ // A new decision reaches its person's phones (task #3248); a repeat was already brought to them.+ if (newDecisions.length) this.tellPhones(tx, tabId, effects.state, { replies: [], tags: [], decisions: newDecisions }, [])if (effects.decisionAnswer) await recordAnswer(tx, tabId, effects.decisionAnswer, context.now)+ if (effects.decisionKeptWaiting) await keepWaiting(tx, tabId, effects.decisionKeptWaiting)// Work this command ended (done, cancelled, archived) closes the decisions still waiting there (Dee, 10-31). After this// command's own answer and asks, so an answer in the same write counts and a reopened task's new ask is a new decision.const over = workEnded(original, effects.state)@@ -3675,7 +3681,7 @@ export class SuperTabStore {if (!kept.has(message.id)) rows.push({ id: message.id, tabId, conversationId: message.conversationId,sequence: sequences.get(message.id)!, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),...(message.attachments ? { attachments: json(message.attachments) } : {}),- text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [],+ text: message.text, replyTo: message.replyTo, ...message.answers ? { answers: message.answers } : {}, recipientIds: message.recipients, mentions: message.mentions ?? [],// A top-level message is its own thread's root; only a row written before threads has none (its replies stay inline).thread: message.thread ?? message.id, ...(message.alsoInChat ? { alsoInChat: true } : {}),...(message.buddySession ? { buddySession: true } : {}), ...(message.buddyProject ? { buddyProject: message.buddyProject } : {}) })@@ -4755,7 +4761,8 @@ export class SuperTabStore {const last = await this.polls.get(key).catch(error => { pollMemoryFailed(error); return undefined })// A PM whose inbox is due gets it now, not at the next full poll (#3545): only its host sends `turn`, and only a read// 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)+ const gathered = turn !== undefined ? await agentGatheredDeliveries(this.db, tabId, agentId, NOTICE_DIGEST_MAX) : []+ const releasing = gathered.some(d => d.inboxSection === 'people') || inboxDue(gathered, this.now(), turn)if (!releasing && last !== undefined && this.now() - last.at < SWEEP_EVERY_MS) {const open = await openDeliveries(this.db, tabId, agentId, last.open?.prioritized)if (!open.length) return []@@ -4818,10 +4825,10 @@ export class SuperTabStore {let gathered = led ? await agentGatheredDeliveries(tx, tabId, agentId, NOTICE_DIGEST_MAX) : []// A read that sends no turn, from a PM whose machine says its host does (#3545): the people's messages and crew needs it// gathered go now, in this read, as they would to an older host; the notices keep their digest.- if (turn === undefined && gathered.length && turnInboxHost(loaded.state, agent(loaded.state, agentId))) {+ if (gathered.some(d => d.inboxSection === 'people') || turn === undefined && gathered.length && turnInboxHost(loaded.state, agent(loaded.state, agentId))) {const requeued = new Set<string>()// By the section recorded when each was gathered: no message is read for it.- for (const delivery of gathered.filter(d => d.inboxSection)) {+ for (const delivery of gathered.filter(d => d.inboxSection === 'people' || turn === undefined && d.inboxSection)) {if ((await tx.superTabDelivery.updateMany({ where: { id: delivery.id, tabId, status: 'gathered' }, data: { status: 'queued' } })).count) requeued.add(delivery.id)}gathered = gathered.filter(d => !requeued.has(d.id))@@ -5139,6 +5146,21 @@ export class SuperTabStore {// A Buddy reads no machine names, in what it is handed too (security review 2 of #2178). News from outside its chat// (buddyNews.ts) is marked, so its host words it as news to note, never a message to answer there.const target = agent(state, agentId), group = conversation(state, delivery.conversationId)+ // #3609: only a confirmed native receipt means the PM has received a person's words. Keep the eyes+ // and receipt in one transaction, using the same identity as a manual reaction; eyes never answers the ask.+ if (action.type === 'ack' && !action.uncertain && !delivery.deliveredAt && row && !row.deletedAt+ && delivery.authorKind === 'person' && ledProject(state, agentId)) {+ const actor: Actor = { kind: 'agent', agentId, machineOwnerId: target.machineOwnerId }+ const command: ReactCommand = { type: 'message.react', conversationId: group.id, messageId: row.id, emoji: 'eyes', on: true }+ if (!await tx.superTabReaction.findUnique({ where: { id: reactionId(tabId, actor, command) } })) {+ // Delivery authority uses light groups. Read the complete one before updating, so no task fields are lost.+ const stored = await tx.swarmGroup.findUniqueOrThrow({ where: { id: partId(tabId, group.id) } })+ const data = stored.data as unknown as Conversation+ await this.writeReaction(tx, tabId, actor, command, this.now())+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: group.id, seen: stored.version,+ data: { ...data, reactionSeq: (data.reactionSeq ?? 0) + 1 } }, stamp)+ }+ }// An agent reads people by name, never email (task #2954).const named = row && namesPerson(row) ? rowForAgent(state, lazyUsernames(state), row) : rowconst shown = named && isBuddy(target) ? rowForBuddy(named) : named@@ -5683,7 +5705,8 @@ export class SuperTabStore {...earlier.filter(a => a.conversationId === group.id).map(a => a.agentId)].filter((id): id is string => typeof id === 'string' && !!id))].map(id => `agent:${id}`)entry.pulls.push({ taskId: group.id, url: own, task: { checks: group.checks,- pullRequestHeads: (group as { pullRequestHeads?: TrainTask['pullRequestHeads'] }).pullRequestHeads, steps, builders } })+ pullRequestHeads: (group as { pullRequestHeads?: TrainTask['pullRequestHeads'] }).pullRequestHeads, steps, builders,+ done: group.assignment?.status === 'done' } })}}projects.push(...found.values())diff --git a/desktop/lib/super_tabs/scorecard.dart b/desktop/lib/super_tabs/scorecard.dartindex 68b59a331..21a1ec9b6 100644--- a/desktop/lib/super_tabs/scorecard.dart+++ b/desktop/lib/super_tabs/scorecard.dart@@ -83,6 +83,20 @@ final scorecardRows = <SuperTabScorecardRow>['Ask to ship (median)',(d) => scorecardDuration(d.number('askToShipMedianMinutes')),),+ SuperTabScorecardRow(+ 'pmAnswerMedian',+ 'PM first answer (median)',+ (d) => scorecardSeconds(+ (d.parts('pmAnswer')['medianSeconds'] as num?)?.round(),+ ),+ ),+ SuperTabScorecardRow(+ 'pmAnswerSlowest',+ 'PM first answer (slowest)',+ (d) => scorecardSeconds(+ (d.parts('pmAnswer')['slowestSeconds'] as num?)?.round(),+ ),+ ),SuperTabScorecardRow('oldestUnansweredAskMinutes','Oldest unanswered ask',diff --git a/desktop/test/super_tab_scorecard_test.dart b/desktop/test/super_tab_scorecard_test.dartindex 773d3e1a5..0273b6c90 100644--- a/desktop/test/super_tab_scorecard_test.dart+++ b/desktop/test/super_tab_scorecard_test.dart@@ -70,6 +70,27 @@ void main() {expect(scorecardRows.first.cell(null), '–');});+ test(+ 'PM first answer shows median and slowest, with gaps on older days',+ () {+ String cell(String key, Map<String, dynamic> figures) => scorecardRows+ .firstWhere((r) => r.key == key)+ .cell(SuperTabScorecardDay.fromJson(_day('2026-11-05', figures)));+ final figures = {+ 'pmAnswer': {'count': 3, 'medianSeconds': 30, 'slowestSeconds': 90},+ };+ expect(cell('pmAnswerMedian', figures), '30s');+ expect(cell('pmAnswerSlowest', figures), '1m30');+ expect(cell('pmAnswerMedian', {}), '–');+ expect(+ cell('pmAnswerSlowest', {+ 'pmAnswer': {'count': 0},+ }),+ '–',+ );+ },+ );+// Task #3462: crew wake and move times, as median · slowest.test('crew wake and move times as median and slowest', () {expect(scorecardSeconds(null), '–');@@ -327,6 +348,11 @@ void main() {'ackPosts': f[11],// Crew times start with #3462: older days show "–".if (on == '2026-11-05') ...{+ 'pmAnswer': {+ 'count': 18,+ 'medianSeconds': 30,+ 'slowestSeconds': 90,+ },'crewWake': {'count': 4,'medianSeconds': 14,diff --git a/docs/plans/2026-11-06-asks-through-buddy-plan.md b/docs/plans/2026-11-06-asks-through-buddy-plan.mdnew file mode 100644index 000000000..3dd792b5a--- /dev/null+++ b/docs/plans/2026-11-06-asks-through-buddy-plan.md@@ -0,0 +1,91 @@+# An agent's ask reaches the person through their Buddy: implementation plan++> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,+> the failing test committed before its code. No Execution Handoff.++**Goal:** In a switched project, an agent that needs a person's answer asks them directly: the question reaches their+default Buddy and their Needs you list, with a default and a time, and never goes through the PM; past the time the default+applies, unless the ask says the person must agree (task #3826, requested by Dee through Harness; spec+docs/plans/2026-11-06-buddy-board-final-spec.md, "When an agent needs a person"). Projects not switched are unchanged.++**Depends on:** #3818 (several Buddies: `defaultBuddyChat`) and #3819 (the project switch, `SwarmProject.boardMode`). Code+starts once both are on main; this plan is the draft's first commit.++**Architecture:** Today an agent's ask of a person (a `work.status needs_human` with an `ask`, or a `decision.ask`) goes to+the PM as a crew need (crewNeeds.ts `routesToPm`), "people talk only to the PM". The path that asks the person already+exists beside it: `askDecisions` opens a decision for them (decisions.ts), with an optional `defaultAt` that the sweep+applies when due (store.ts leaveOverdueDecisions, `dueDefaultDecisions`). In a project with `boardMode` (boardRights.ts+`switched`):++1. Both asks take the direct path: no crew need, and a needs_human status row with a direct ask reaches no PM; the task's+ `askedOf` mark (already kept) is what the PM sees.+2. Each question must carry `defaultAt` (refused with what is missing otherwise), and may carry `mustAgree: true`.+3. Each question is posted in the person's default Buddy chat (`defaultBuddyChat`), addressed to their default Buddy+ (`defaultBuddy`), source kind `decision-asked`, marked with its project; the decision is in their Needs you list (the+ person's open decisions). The Buddy cannot answer for them (`answerable` takes the person only): it brings it to them.+4. At `defaultAt` the sweep answers with the recommendation, as today. A `mustAgree` decision is not answered: the PM is+ told once in the decision's conversation (source `decision-must-agree`, its alone), and its `defaultAt` is cleared in+ the same write so the due range never reads it again; the 24-hour legacy sweep skips `mustAgree` rows, so it waits for+ the person until answered or withdrawn with its work.++**Tech Stack:** TypeScript backend, vitest.++## Global Constraints++- Projects without `boardMode` behave exactly as today: crew need to the PM.+- The server enforces it: the person answers their own decision; their Buddy answers within its existing rights.+- Swarm code stays out of cli/src/core.++## Design++- growth: decisions are already capped per person (MAX_OPEN_DECISIONS) and expire as today; one Buddy-chat line per question;+ one optional `mustAgree` field per decision row, deleted with the row.+- concurrency: the ask is the task's own status write; the default applies in the overdue sweep's conditional write, which a+ person's answer in the same second wins, as today.+- read cost: none new; both sweep reads keep their indexes (`decision_waiting_default`, `decision_waiting_created`), with+ `mustAgree` a residual filter on the legacy one only.+- scale: 10x asks is 10x decisions, bounded per person by the cap; the first warning is people's open decisions at the cap.+- compatibility: `mustAgree` extends the ask's contract (optional); an older CLI sends an ask without `defaultAt` and is+ refused in a switched project with what to add; older apps read the decision and the Buddy-chat line as today.+- migration + rollback: none (an optional field); rollback routes asks to the PM again, and a `mustAgree` row with its+ `defaultAt` cleared then falls to the legacy 24-hour sweep.+- audience: the decision is the person's own; the Buddy chat is read by them and their Buddy only.+- identity: the agent asks as itself; the answer is the person's; the Buddy brings the question but cannot answer it for them.+- failure: an ask refused says why; a must-agree decision past its time tells the PM once.+- platforms: backend.++## Review Focus++- A project not switched routes exactly as before.+- No path lets the default apply to a must-agree decision.++## Task 1: in a switched project an ask goes to the person, through their default Buddy++**Files:** backend/src/superTabs/{commands.ts, decisions.ts, model.ts}, backend/src/superTabs/asksThroughBuddy.test.ts++**Interfaces:** `askedThroughBuddy(state, group, drafts, author)`: the Buddy-chat lines for drafts in a switched project+(decisions.ts); `checkSwitchedAsk(question)`: refuses a question with no `defaultAt`.++- [x] Test: in a switched project, an agent's needs_human ask and its decision.ask each open a decision for the person+ with its default and time, post the question in their default Buddy's chat addressed to that Buddy, send nothing to the+ PM, and keep `askedOf`; without `defaultAt` each is refused; in a project not switched both are the PM's crew needs, as+ today.+- [x] Watch it fail; commit. Code; watch it pass; commit.++## Task 2: the default applies at its time, unless the person must agree++**Files:** backend/prisma/schema.prisma, backend/src/superTabs/{decisions.ts, overdueDecisions.ts, commands.ts, store.ts,+model.ts}, backend/integration/overdueDecisions.test.ts++- [x] Test: past its time the default answers a switched project's decision and the agent hears it; a `mustAgree` one+ stays open, the PM is told once, the next pass and the 24-hour sweep take nothing, and the person can still answer.+- [x] Watch it fail; commit. Code; watch it pass; commit.++## Follow-up after merging prerequisites++- [x] Resolve the single imports conflict with main, retaining both task imports.+- [x] Test first: an identical `decision.ask` sends one Buddy notice; a changed `mustAgree` is a distinct decision; required+ agreement never advertises a default or PM takeover. Red: one unit failure and four integration failures.+- [x] Resolve decision deduplication before writing/numbering Buddy notices, using the existing indexed read once; include+ `mustAgree` in repeat identity and describe required agreement truthfully. Green: 623 focused unit tests and 23 decision+ sweep/persistence integration tests; typecheck clean.diff --git a/docs/plans/2026-11-06-pm-person-delivery-plan.md b/docs/plans/2026-11-06-pm-person-delivery-plan.mdnew file mode 100644index 000000000..1510afa02--- /dev/null+++ b/docs/plans/2026-11-06-pm-person-delivery-plan.md@@ -0,0 +1,78 @@+# Prompt PM delivery and answer time implementation plan++> Implement directly, task by task, test first; commit each failing test before its passing code, then obtain independent PR review.++**Goal:** Deliver people's messages immediately to the working PM, acknowledge receipt once, and measure its first answer.++**Architecture:** Stop gathering person-authored messages into the turn inbox; retain batching for agent notices and crew needs. The authorized host acknowledgement adds the PM's existing eyes reaction transactionally. Derive answer-time figures from existing message records and change the existing board pulse threshold to five minutes.++**Tech Stack:** TypeScript, Vitest, Prisma/MongoDB; existing CLI Swarm input delivery (already accepts input while busy).++**Spec:** Harness task #3609, conversation e6e4f5a93f4ecb99f29f8ff9, River's brief of 2026-11-06.++## Global Constraints++- Backend and CLI Swarm implementation, plus the two existing Desktop scorecard rows needed to display the figures; no cli/src/core changes, production writes, sign-outs or system installs.+- PR starts `Requested by dee through Harness.` Tests first; affected tests locally, complete backend/integration checks in PR CI.+- Preserve access checks, message author attribution, cross-account warnings, unanswered tracking and older hosts.+- Temporary files only in mktemp -d folders; stop only processes started for this task, by id.++## Visible behavior++Existing board strip, unchanged layout: `[ PM · 1 ask · oldest 5m (red) | Working 3 | Next 2 ]`.+Message receipt: `Dee: Is the fix out? 👀 River` (only after successful session receipt).+Daily scorecard adds `PM first answer | median 30s | slowest 90s | 2 answered`.++## Design++Reuse message/reaction/scorecard stores and their lifecycle; no new collection or index. One optional message field, `answers`, preserves a main answer link without opening a thread; older clients ignore it and old rows remain valid. Reaction and receipt share the existing transaction; deterministic reaction identity makes retries idempotent. Readers use current project grants and indexed message pages. A PM reply must be in the same conversation and directly answer the message or occur later in its thread; agent notices, reactions, and task cards do not count. Daily figures cover messages answered during the day, with the existing bounded seven-day lookback and reader cap reported as before. Rollback restores batching and the old threshold; old scorecards omit the optional figure. No backfill, new timer, or platform-specific code. At ten times traffic reads stay bounded by existing page caps; watch capped scorecards and delivery latency. Production read-only credentials are unavailable here; loopback integration/profile evidence substitutes and that limitation is reported.++## Review Focus++- Already-gathered person rows must escape a busy inbox without releasing agent notices.+- Thread and Buddy relay messages preserve author/place and remain owed after eyes.+- Uncertain/retried receipts and non-PM deliveries must not create false or duplicate eyes.+- An unrelated agent post, reaction, or later answer must not replace the PM's first answer time.+- Cross-day replies, zero samples, private chats, deleted rows and missing historical context remain bounded and honest.++### Task 1: Immediate person delivery++**Files:** backend/src/superTabs/inbox.ts, inbox.test.ts, store.ts; backend/integration/superTabNoticeDigest.test.ts; pulse.ts if relay tracking needs correction.+**Interfaces:** gathersForInbox(state, recipient, message): boolean keeps only crew batching; deliveries(user, tab, agent, turn) releases legacy people without releasing other gathered rows. Existing owedLines remains the reminder interface.++- [x] Commit tests for busy PM project messages, threads and Buddy relays delivered immediately while notices stay gathered; legacy gathered people released; unanswered asks reappear.+- [x] Run the affected unit/integration cases and observe the behavior fail.+- [x] Implement the minimal classification/requeue changes, preserving all authorization and attribution.+- [x] Run affected inbox/digest/pulse tests, commit code and push.++### Task 2: Receipt eyes++**Files:** backend/src/superTabs/store.ts; backend/integration/superTabNoticeDigest.test.ts (or existing delivery integration fixture).+**Interfaces:** deliver(... ack ...) writes eyes under the receiving PM's identity on first confirmed receipt; existing reaction identity and reactionSeq drive reader refresh.++- [x] Commit tests: claim has no eyes; uncertain ack has no eyes; successful ack adds one, retries keep one and do not settle owed; non-PM/agent messages add none.+- [x] Run and observe failing tests.+- [x] Add the transactional reaction write and existing conversation change notification; test concurrent/manual eyes and revocation through current delivery authorization.+- [x] Run affected receipt/reaction integrations; commit and push.++### Task 3: Answer time and five-minute pulse++**Files:** backend/prisma/schema.prisma (optional message answer link), backend/src/superTabs/{model.ts,commands.ts,store.ts}, backend/src/superTabs/scorecard/{figures.ts,figures.test.ts,records.ts}, scorecard presentation module; backend/src/superTabs/{pulse.ts,pulse.test.ts}; backend/integration/superTabScorecard.test.ts.+**Interfaces:** optional pmAnswer {count, medianSeconds, slowestSeconds} on ScorecardFigures; records includes bounded project message lookback and explicit answer links; PULSE_LIMITS.askMinutes = 5.++- [x] Commit tests for first PM answers to main/thread/relay messages; wrong agent/place, reactions, task cards and duplicate answers excluded; cross-day, zero samples and subminute timings; redAt equals sent+300000ms.+- [x] Run and observe failures.+- [x] Implement pure first-answer matching from stored message links and render daily median/slowest; extend existing indexed reader only as necessary, retaining caps and audience filters.+- [x] Run figures/pulse/job tests and affected scorecard integrations; profile any changed query against its existing index; typecheck.+- [x] Commit and push; add red/green PR comment; mark ready and set task review with exact revision and evidence.+++### Task 4: Show the scorecard figures++**Files:** desktop/lib/super_tabs/scorecard.dart, desktop/test/super_tab_scorecard_test.dart.+**Interfaces:** Read optional pmAnswer parts from the existing scorecard API; no transport changes.++- [x] Commit and observe a failing row test for median 30s, slowest 1m30, and missing old-day figures.+- [x] Add the two rows in the existing table, reusing scorecardSeconds.+- [x] Run affected scorecard widget tests with memory fixtures and capture light/dark screenshots; no real sign-in.+- [x] Commit/push and include the current-head screenshots in review evidence.diff --git a/docs/plans/2026-11-06-pm-reaction-settlement-plan.md b/docs/plans/2026-11-06-pm-reaction-settlement-plan.mdnew file mode 100644index 000000000..f735fc530--- /dev/null+++ b/docs/plans/2026-11-06-pm-reaction-settlement-plan.md@@ -0,0 +1,53 @@+# PM reaction settlement implementation plan++> Implement natively, task by task, with a committed failing test before the fix and one independent review.++**Goal:** A PM's explicit reaction settles a person's message, so a joke needs no reply just to leave the owed list.++**Architecture:** Reuse the existing message.react → settleReaction path and owed-list/pulse persistence. Accept every supported reaction instead of only verdict emoji. Keep the PM identity, on=true and exact-message checks; receipt reactions written internally never call this explicit-command path.++**Tech Stack:** TypeScript, Vitest, existing Prisma/MongoDB transaction; no dependency or schema changes.++**Spec:** Task #3663, conversation ef3328db5c39c5f324771e27. River's 2026-11-06 clarification supersedes the initial question exception: “No phrase check ... Every person's message stays owed until the PM replies or reacts. A PM reaction settles it ... The PM decides what needs words.” Test Leo's one-line joke, plus a question to pin that ruling.++## Global Constraints++- One task/branch/PR; first body line: Requested by dee through Harness.+- Do not infer requests from language or punctuation. An explicit PM reaction or reply settles the message.+- Other agents and people, removing a reaction, and automatic receipt eyes do not settle PM owes.+- No production writes, secrets, sign-outs, system installs or CLI core changes. Temp files only in mktemp -d folders; stop only own processes by id.+- Affected tests locally; full backend and Super Tab integration suites in ready PR CI. Red/green evidence in a PR comment; one review.++## Design++- **Growth/concurrency:** No new state; remove a row from the existing 50-row owed list under the existing transaction/fence.+- **Read cost/scale:** No query/index changes or extra reads. Existing bounded owed scan; no classifier, content read or transcript copy.+- **Compatibility/rollback:** Existing records and clients unchanged. Rollback restores verdict-only settlement; it does not recreate rows already settled.+- **Audience/identity:** Only the actual project's PM's explicit command settles that message; existing reaction/message access checks still apply.+- **Failure/platforms:** Normal validation failures remain visible. Shared backend behavior on every client; no screen/layout changes.++## Review Focus++- Eyes, laugh and heart must clear the joke as verdict reactions already did (unit and real-store tests).+- A question also clears on a PM reaction, per the later PM ruling; no phrase classifier (unit and real-store tests).+- Another person's/agent's reaction and taking a reaction off must leave the PM's owes intact (existing and extended unit tests).+- Reacting to one thread message must not clear its siblings (unit test).+- Automatic receipt eyes must remain a receipt, not an explicit answer; only message.react invokes settleReaction (verify the command boundary and retain receipt tests from #3609).++### Task 1: Settle an explicit PM reaction++**Files:** pulse.ts, commands.ts; pulse.test.ts, integration/superTabs.test.ts.+**Interfaces:** settleReaction(state, group, agentId, messageId, on) removes only that owed message when the actual PM adds a reaction. The emoji is already validated by message.react.++- [x] Commit tests: all seven reactions clear a social message and owedLines/pulse; questions clear too; removing a reaction/other actors do not; thread siblings remain. Add a real-store joke/question case proving persisted owed state (`cb868b10b`).+- [x] Run new tests and observe missing eyes/laugh/heart settlement before implementation: four unit failures and the real-store joke remained owed.+- [x] Remove verdict-only filtering and its unused set/argument; keep actual-PM/on/exact-message checks and automatic receipt path unchanged.+- [x] Run pulse, commands, answers, inbox, reactions and liveness importers: 545 tests pass; four affected real-store reaction/answer/index cases pass; typecheck clean.+- [x] Commit/push the green fix and record red/green evidence in the PR. Full component suites run in ready CI.+- [ ] Independent review confirms the final head.++## Evidence++- `npm --prefix backend test -- src/superTabs/pulse.test.ts src/superTabs/commands.test.ts src/superTabs/answers.test.ts src/superTabs/inbox.test.ts src/superTabs/reactions.test.ts src/superTabs/liveness.test.ts`: 545 passed.+- `npm --prefix backend run test:super-tabs -- integration/superTabs.test.ts -t 'a PM reaction settles|closes the reacting agent|settles a reaction.s deliveries by index|closes an agent.s delivery when it answers'`: four passed. The joke and question leave durable owed state without replies; other actors/removal do not clear them; existing answer/delivery isolation and indexed delivery updates still pass.+- `npm --prefix backend run typecheck`: passed. No query, index, schema, dependency or screen changes; no production reads/writes.