Skip to content

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

The server writes the status card from task state, within each command's read budget (#4419) (#3519)

0xken15b48d99dd009d
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index be69481d4..5a0d21345 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -383,16 +383,15 @@ describe('a Buddy through the store', () => {
expect((await f.store.decisions(peer, f.tab, 'settled')).decisions.map(d => d.question)).toContain(routing[0]!.question)
})
- it('still reads a task archived before the PM reported on it, until it leaves the active set (security review 1 of #2115)', async () => {
+ it('reads a task archived by hand in the dormant view at once, with no report to wait for (security review 1 of #2115, #3593)', async () => {
const f = await swarm()
const { agentId } = await buddy(f)
const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Old task', brief: '', checks: [] })).result.conversationId)
- // A work change the PM has not reported yet (a plain message no longer is one: Dee, 2026-10-31).
await f.execute({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/example/app/pull/7' })
await f.execute({ type: 'conversation.archive', conversationId: group, archived: true } as Command)
- const read = await new SwarmReads(f.store).firstLoad(peer, f.tab, agentId)
- expect(read.groups.find(g => g.key === group)?.data).toMatchObject({ archived: true })
- expect(read.groups.find(g => g.key === group)?.data.dormant).toBeUndefined()
+ const reads = new SwarmReads(f.store)
+ expect((await reads.firstLoad(peer, f.tab, agentId)).groups.some(g => g.key === group)).toBe(false)
+ expect((await reads.dormant(peer, f.tab, { projectId: 'lead' }, agentId)).groups.find(g => g.key === group)?.data).toMatchObject({ archived: true })
})
it('reads a lost task without the machine it ran on, in its messages, its task and its agent (security re-check 2 of #2115)', async () => {
const f = await swarm()
diff --git a/backend/integration/superTabBuddyProbes.test.ts b/backend/integration/superTabBuddyProbes.test.ts
index 17e0e7109..725ee0904 100644
--- a/backend/integration/superTabBuddyProbes.test.ts
+++ b/backend/integration/superTabBuddyProbes.test.ts
@@ -108,18 +108,16 @@ describe('security review 1 of #2115: a Buddy\'s reads, probed by two people', (
await expect(f.store.routeDecision(peer,f.tab,'invented-route-id',agentId)).rejects.toThrow()
})
- it('still hands a Buddy an archived task awaiting the PM\'s report, in the active set its summary shows', async () => {
+ it('hands a Buddy an archived task in the dormant view the moment it is archived, with no report to wait for (#3593)', async () => {
const f=await swarm(), {agentId}=await buddy(f)
- const group=String((await f.execute({type:'conversation.create',projectId:'lead',title:'Archived but unsummarized',brief:'',checks:[]})).result.conversationId)
- // A work change the PM has not reported yet (a plain message no longer is one: Dee, 2026-10-31).
+ const group=String((await f.execute({type:'conversation.create',projectId:'lead',title:'Archived at once',brief:'',checks:[]})).result.conversationId)
await f.execute({type:'conversation.merged',conversationId:group,pullRequestUrl:'https://github.com/example/app/pull/7'})
await f.execute({type:'conversation.archive',conversationId:group,archived:true})
const reads=new SwarmReads(f.store), active=await reads.firstLoad(peer,f.tab,agentId)
- const held=active.groups.find(g=>g.key===group)!
+ expect(active.groups.some(g=>g.key===group)).toBe(false)
+ // It is in the other of the two views, which only the project's readers may page.
+ const held=(await reads.dormant(peer,f.tab,{projectId:'lead'},agentId)).groups.find(g=>g.key===group)!
expect(held.data.archived).toBe(true)
- expect(held.data.dormant).not.toBe(true)
- expect((await reads.dormant(peer,f.tab,{projectId:'lead'},agentId)).groups.map(g=>g.key)).not.toContain(group)
- // So the summary shows it, marked archived (buddyStatus.spec.ts), and it is in one of the two views.
})
it('refuses private chats, other Buddies, Leads and other-project groups even with forged paging inputs',async()=>{
diff --git a/backend/integration/superTabDeletion.test.ts b/backend/integration/superTabDeletion.test.ts
index 8a362b403..8242daa0f 100644
--- a/backend/integration/superTabDeletion.test.ts
+++ b/backend/integration/superTabDeletion.test.ts
@@ -331,7 +331,7 @@ describe('while a Swarm is deleted', () => {
expect(await db.superTabMessage.count({ where: { tabId: tab, text: 'after the delete' } })).toBe(0)
})
- /** A Swarm with an archived group whose reports are all summarized (so it may sleep), a finished start past its keeping,
+ /** A Swarm with a group archived by hand (so it may sleep), a finished start past its keeping,
* a decision still waiting in that finished group, and a group finished weeks ago with a merged pull request; deleted or
* not. Each background job changes the live one, so a check on the deleted one can fail (re-check 2 of #2457). */
async function quietSwarm(w: ReturnType<typeof world>, name: string, deleted: boolean) {
@@ -339,8 +339,11 @@ describe('while a Swarm is deleted', () => {
const group = String((await f.execute({ type: 'conversation.create', title: 'Old work', brief: 'Done long ago.',
checks: [{ description: 'Done', independent: false }] })).result.conversationId)
await f.execute({ type: 'conversation.archive', conversationId: group, archived: true })
- const progress = await db.swarmProgress.findUniqueOrThrow({ where: { id: `${f.tab}:lead` } })
- await db.swarmProgress.update({ where: { id: progress.id }, data: { data: { ...(progress.data as object), summarizedFloor: 1e9 } } })
+ // An archived group sleeps at once now (task #3593); this test is about the sweep, so it is put back awake, as the sweep finds one
+ // archived before the sweep existed.
+ const slept = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: group } } })
+ const { dormant: _dormant, ...awake } = slept.data as unknown as Record<string, unknown>
+ await db.swarmGroup.update({ where: { id: slept.id }, data: { dormant: false, data: awake as object } })
const prGroup = String((await f.execute({ type: 'conversation.create', title: 'Merged work', brief: 'Merged.',
checks: [{ description: 'Done', independent: false }] })).result.conversationId)
await db.superTabThreadBackfill.deleteMany({ where: { id: f.tab } })
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 6a29dcd90..30ed68e1e 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -920,11 +920,12 @@ describe('a machine\'s report', () => {
// A report never reads its projects' report progress (projectUpdates.ts): only commands and native events note reports.
describe('machine reports and report progress', () => {
- it('reads no report progress and leaves its part as it was, also when the report loses a task', async () => {
+ it('reads no report progress and writes none, also when the report loses a task', async () => {
const f = await swarm()
await f.execute({ type: 'message.send', conversationId: f.group, text: 'Parser done', replyTo: null, recipientIds: [] })
+ // Nothing marks a work group for a report any more (task #3593), so no report progress exists to read or write.
const before = await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } })
- expect(before).not.toBeNull()
+ expect(before).toBeNull()
const { reads } = await profiledReads(db, /\.SwarmProgress$/, async () => {
// The tab's first report, so it runs the liveness sweep too.
await f.observe('test-host', [f.harness.worker])
@@ -934,10 +935,7 @@ describe('machine reports and report progress', () => {
})
expect(reads).toBe(0)
expect((await f.assignment()).status).toBe('lost')
- const after = await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } })
- expect(after!.version).toBe(before!.version)
- expect(after!.data).toEqual(before!.data)
- expect(after!.changedAt).toEqual(before!.changedAt)
+ expect(await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } })).toBeNull()
})
})
@@ -1439,61 +1437,11 @@ describe('the delivery poll of an agent with nothing waiting', () => {
expect(counted.ops).toContain('SwarmGroup.aggregateRaw')
})
- it('still runs the Lead\'s time checks: the five-minute update request arrives once 30 seconds have passed', async () => {
+ it('sends the Lead no update request for work changes: its inbox stays empty five minutes on (#3593)', async () => {
const f = await swarm()
await f.leadInbox()
f.clock.now += 5 * MINUTE
- const told = await f.leadInbox()
- expect(told.map(m => (m.source as { kind?: string }).kind)).toEqual(['update-request'])
- // It is the Lead's to act on, with a command to run: the Lead reads it in its chat, and the people there do not.
- const read = async (asAgentId?: string) => (await f.timed.messages(asAgentId ? host : owner, f.tab, told[0]!.conversationId, {}, asAgentId)).messages.map(m => m.id)
- expect(await read(f.lead)).toContain(told[0]!.id)
- expect(await read()).not.toContain(told[0]!.id)
- })
-
- // Prod, 2026-10-28: a Lead's host received an update request on 26 Oct and the Lead never answered it. Every later poll
- // took it as still pending, so the project was never asked again, its reports were never summarized, and 372 archived
- // conversations could not go quiet for two days.
- it('asks again once an update request the Lead\'s host received goes unanswered for two hours, and not before', async () => {
- const f = await swarm()
- await f.leadInbox()
- f.clock.now += 5 * MINUTE
- const requests = async () => {
- const rows = await f.timed.deliveries(host, f.tab, f.lead)
- const messages = await db.superTabMessage.findMany({ where: { id: { in: rows.map(r => r.messageId) } } })
- return rows.filter(r => (messages.find(m => m.id === r.messageId)!.source as { kind?: string }).kind === 'update-request')
- }
- const [first] = await requests()
- expect(first).toBeDefined()
- // Typed into the Lead's terminal, never answered.
- await f.timed.delivery(host, f.tab, f.lead, first!.id, { type: 'claim', claimId: 'claim' })
- await f.timed.delivery(host, f.tab, f.lead, first!.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })
- // New work changes keep coming (an ordinary progress note would wake nobody: Dee, 2026-10-31).
- f.clock.now += MINUTE
- await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'review', result: 'Halfway' }, host, f.worker)
- f.clock.now += 59 * MINUTE
- expect(await requests()).toEqual([])
- f.clock.now += 61 * MINUTE
- const again = await requests()
- expect(again).toHaveLength(1)
- expect(again[0]!.messageId).not.toBe(first!.messageId)
- })
-
- it('keeps holding later update requests while the first never reached the Lead\'s host, however long', async () => {
- const f = await swarm()
- await f.leadInbox()
- f.clock.now += 5 * MINUTE
- const kinds = async () => {
- const rows = await f.timed.deliveries(host, f.tab, f.lead)
- const messages = await db.superTabMessage.findMany({ where: { id: { in: rows.map(r => r.messageId) } } })
- return rows.map(r => (messages.find(m => m.id === r.messageId)!.source as { kind?: string }).kind)
- }
- expect(await kinds()).toContain('update-request')
- // Never claimed: the host is offline. New reports keep coming.
- f.clock.now += MINUTE
- await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Halfway' }, host, f.worker)
- f.clock.now += 3 * 60 * MINUTE
- expect((await kinds()).filter(kind => kind === 'update-request')).toHaveLength(1)
+ expect(await f.leadInbox()).toEqual([])
})
it('delivers a message on the very next poll, within a second of the last one', async () => {
@@ -1765,19 +1713,6 @@ describe('the delivery poll of an agent with a held delivery', () => {
const team: AuthUser = { ...host, harnessSessionId: 'team-elsewhere', harnessSessionKind: 'team', harnessComputerId: 'elsewhere' }
await expect(f.timed.deliveries(team, f.tab, f.lead)).rejects.toMatchObject({ code: 'TEAM_SESSION_LIMITED' })
})
-
- it('still runs the Lead\'s time checks: the five-minute update request arrives beside the held delivery', async () => {
- const f = await swarm()
- const row = await held(f)
- for (let second = 0; second < 5 * 60; second++) {
- f.clock.now += 1_000
- await f.timed.deliveries(host, f.tab, f.lead)
- }
- const rows = await f.timed.deliveries(host, f.tab, f.lead)
- expect(rows[0]!.id).toBe(row.id)
- const kinds = await db.superTabMessage.findMany({ where: { id: { in: rows.map(r => r.messageId) } } })
- expect(kinds.map(m => (m.source as { kind?: string } | null)?.kind)).toContain('update-request')
- })
})
// Hosts read an idle agent's deliveries only every 30 s once the server pushes (stability roadmap 2.4): each new one is
@@ -1964,16 +1899,6 @@ describe('the push for a new delivery', () => {
await f.execute({ type: 'agent.screen', agentId: f.worker, scrollback: 50 })
expect(heard).toEqual([{ machineId: 'test-host', tabId: f.tab, agentId: f.worker }])
})
-
- it('announces the update request the Lead\'s own poll writes for it', async () => {
- const { waiting, hooks } = announcing()
- const f = await swarm({ hooks })
- await f.leadInbox()
- waiting.length = 0
- f.clock.now += 5 * MINUTE
- await f.timed.deliveries(host, f.tab, f.lead)
- expect(waiting).toContainEqual({ machineId: 'lead-host', tabId: f.tab, agentId: f.lead })
- })
})
// Diego's review of 10-28, item 1: every write of the full poll is the Lead's, so a worker's poll only reads. Through the
diff --git a/backend/integration/superTabNoticeDigest.test.ts b/backend/integration/superTabNoticeDigest.test.ts
index d7b28d6df..8b27976a1 100644
--- a/backend/integration/superTabNoticeDigest.test.ts
+++ b/backend/integration/superTabNoticeDigest.test.ts
@@ -49,7 +49,7 @@ afterAll(async () => {
})
/** A Swarm whose coordinator runs on one machine and whose worker, on another, works on task "Ship the parser". The coordinator's
- * first update request (for the assignment) has gone, so nothing merges with a digest in the next 15 minutes, unless [fresh]. */
+ * first poll is a full one ([fresh] is kept for callers: no update request goes with the setup any more, task #3593). */
async function swarm({ fresh = false, told, capable = false }: { fresh?: boolean; told?: string[]; capable?: boolean } = {}) {
let now = Date.parse('2026-11-02T06:30:00.000Z')
const timed = new SuperTabStore(db, () => now, null, told ? { deliveriesWaiting: w => { told.push(w.agentId) } } : {})
@@ -95,12 +95,6 @@ async function swarm({ fresh = false, told, capable = false }: { fresh?: boolean
}
const status = (s: 'done' | 'blocked' | 'needs_human' | 'working', result = 'A result') =>
execute({ type: 'work.status', conversationId: group, assignmentId, status: s, result }, host, worker)
- if (!fresh) {
- clock.now += DUE + 1_000
- await poll()
- const early = await rowsOf(tab, { status: 'gathered' })
- expect(await Promise.all(early.map(d => db.superTabMessage.findUnique({ where: { id: d.messageId } }).then(m => [m?.text, m?.source])))).toEqual([])
- }
/** Writes one message as the store writes every message, for a notice no short command here sets off. */
const write = async (source: Record<string, unknown> | undefined, recipient: string, conversationId = group, text = 'A notice.', as = worker) => {
const id = randomUUID().replaceAll('-', '').slice(0, 24)
@@ -219,7 +213,8 @@ describe('the coordinator\'s poll releases what was gathered', () => {
await f.poll()
expect(await digests(f.tab)).toEqual([])
expect(await rowsOf(f.tab, { status: 'gathered' })).toHaveLength(2)
- f.clock.now += 1_000
+ // The next full poll is 30 seconds on (the quiet poll reads one row until then).
+ f.clock.now += 30_000
await f.poll()
expect((await digests(f.tab))[0]!.source).toMatchObject({ kind: 'notice-digest', count: 2 })
})
@@ -719,71 +714,15 @@ describe('when the coordinator changes', () => {
})
})
-describe('with the update request', () => {
- it('goes as one message when both are due in one poll, and the report still answers it', async () => {
- const f = await swarm({ fresh: true })
- await f.status('done', 'PR 2515')
- const done = await statusRow(f.tab, f.group, 'Done')
- f.clock.now += DUE
- const inbox = await f.poll()
- expect(await digests(f.tab)).toEqual([])
- const requests = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => kindOf(m) === 'update-request')
- expect(requests).toHaveLength(1)
- const [request] = requests
- expect(request!.text).toContain('Work changed in project')
- expect(request!.text.indexOf('Work changed')).toBeLessThan(request!.text.indexOf('Notices since'))
- expect(request!.text).toContain(`"Ship the parser": Done — PR 2515 (message ${done.id} in ${f.group})`)
- expect(request!.source).toMatchObject({ kind: 'update-request', notices: 1 })
- expect((await deliveryOf(done.id, f.lead)).status).toBe('digested')
- expect(inbox.filter(d => d.messageId === request!.id)).toHaveLength(1)
- // One new message for the coordinator.
- expect(inbox.filter(d => !d.messageId.startsWith(request!.id)).filter(d => d.conversationId === 'lead' && d.status === 'queued' && d.createdAt.getTime() === f.clock.now)).toEqual([])
- const through = (request!.source as { through: Record<string, number> }).through
- await f.execute({ type: 'project.report', projectId: (await f.timed.read(host, f.tab, undefined, f.lead)).state.projects![0]!.id, through, text: null }, host, f.lead)
- expect((await deliveryOf(request!.id, f.lead)).status).toBe('answered')
- })
-
- it('goes alone when the update request is not due', async () => {
+describe('the notice digest alone', () => {
+ it('goes alone, and no update request goes with it (#3593)', async () => {
const f = await swarm()
const id = await f.write({ kind: 'idle' }, f.lead)
f.clock.now += DUE
await f.poll()
expect(await digests(f.tab)).toHaveLength(1)
expect((await deliveryOf(id, f.lead)).status).toBe('digested')
- })
-
- it('does not merge into an update request already stored under its id, so no line is lost and the poll still goes', async () => {
- const f = await swarm({ fresh: true })
- const id = await f.write({ kind: 'idle' }, f.lead)
- f.clock.now += DUE
- const { projectUpdateRequest } = await import('../src/superTabs/projectUpdates.js')
- const { state } = await f.timed.read(host, f.tab, undefined, f.lead)
- const draft = projectUpdateRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!
- await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,
- mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })
- await f.poll()
- expect((await digests(f.tab))[0]!.text).toContain(`message ${id} `)
- expect((await deliveryOf(id, f.lead)).status).toBe('digested')
- })
-})
-
-// A kept message's deliveries were read by message id alone: a scan of all 43 k deliveries, 440 ms inside this write
-// transaction, 21 times a day (Atlas slow log, 2026-11-04).
-describe('a poll keeping a message already stored', () => {
- it('reads its deliveries by Swarm and message, examining only those', async () => {
- const f = await swarm({ fresh: true })
- await f.write({ kind: 'idle' }, f.lead)
- f.clock.now += DUE
- const { projectUpdateRequest } = await import('../src/superTabs/projectUpdates.js')
- const { state } = await f.timed.read(host, f.tab, undefined, f.lead)
- const draft = projectUpdateRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!
- await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,
- mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })
- const entries = await profiled(db, () => f.poll())
- const rows = reads(entries, 'SuperTabDelivery', ['messageId'], ['agentId'])
- expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
- expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, messageId: 1/)
- expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(1)
+ expect((await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => kindOf(m) === 'update-request')).toEqual([])
})
})
diff --git a/backend/integration/superTabPmSchedule.test.ts b/backend/integration/superTabPmSchedule.test.ts
index ab0b54dad..37da9c44a 100644
--- a/backend/integration/superTabPmSchedule.test.ts
+++ b/backend/integration/superTabPmSchedule.test.ts
@@ -18,7 +18,8 @@ import { revokeNativeContexts } from '../src/superTabs/native.js'
import { stableId, type MessageDraft, type SuperTabState } from '../src/superTabs/model.js'
import { logger } from '../src/utils/logger.js'
import { wantSchedule } from './noDefaultDigest.test-support.js'
-import { SCHEDULE_SLOT_MS, scheduleSlot } from '../src/superTabs/pmSchedule.js'
+import { SCHEDULE_SLOT_MS, scheduleRequest, scheduleSlot } from '../src/superTabs/pmSchedule.js'
+import { plan, profiled, reads } from './plans.test-support.js'
// Ken, 2026-11-04 (docs/plans/2026-11-04-pm-built-in-schedule-design.md): the coordinator's poll wakes it every 30 minutes for
// the built-in schedule when the sweep has something to do, in one message per poll. A fresh loopback replica set, created here.
@@ -50,7 +51,7 @@ afterAll(async () => {
})
/** A Swarm whose coordinator runs on one machine and whose worker, on another, works on task "Ship the parser". The coordinator's
- * first update request (for the assignment) has gone, so nothing merges with a digest in the next 15 minutes, unless [fresh]. */
+ * first poll is a full one ([fresh] is kept for callers: no update request goes with the setup any more, task #3593). */
async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[] } = {}) {
let now = Date.parse('2026-11-02T06:30:00.000Z')
const timed = new SuperTabStore(db, () => now, null, told ? { deliveriesWaiting: w => { told.push(w.agentId) } } : {})
@@ -96,12 +97,6 @@ async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[]
}
const status = (s: 'done' | 'blocked' | 'needs_human' | 'working', result = 'A result') =>
execute({ type: 'work.status', conversationId: group, assignmentId, status: s, result }, host, worker)
- if (!fresh) {
- clock.now += DUE + 1_000
- await poll()
- const early = await rowsOf(tab, { status: 'gathered' })
- expect(await Promise.all(early.map(d => db.superTabMessage.findUnique({ where: { id: d.messageId } }).then(m => [m?.text, m?.source])))).toEqual([])
- }
/** Writes one message as the store writes every message, for a notice no short command here sets off. */
const write = async (source: Record<string, unknown> | undefined, recipient: string, conversationId = group, text = 'A notice.', as = worker) => {
const id = randomUUID().replaceAll('-', '').slice(0, 24)
@@ -172,8 +167,9 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
expect(await schedules(f.tab)).toEqual([])
expect(await headOf(f.tab)).toEqual(before)
expect((await projectOf(f)).schedule).toBeUndefined()
- // Something to sweep later in the same slot wakes it once.
+ // Something to sweep later in the same slot wakes it once (at the next full poll, 30 seconds on).
await unassigned(f)
+ f.clock.now += 30_000
await f.poll()
expect(await schedules(f.tab)).toHaveLength(1)
})
@@ -211,7 +207,7 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
expect(await schedules(f.tab)).toHaveLength(1)
})
- it('sends no wake of its own while the update request that carried the last one is unread', async () => {
+ it('sends no wake of its own while the wake that carried the last one is unread', async () => {
const f = await swarm({ fresh: true })
wantSchedule()
await unassigned(f)
@@ -219,24 +215,10 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
await f.poll()
f.clock.now += SCHEDULE_SLOT_MS
await f.poll()
- expect((await schedules(f.tab)).map(kindOf)).toEqual(['update-request'])
- })
-
- it('goes in the update request when one is written in the same poll', async () => {
- // Fresh: the setup's own update request would still wait for its answer, and no second one goes meanwhile.
- const f = await swarm({ fresh: true })
- wantSchedule()
- await unassigned(f)
- f.clock.now += DUE
- await f.poll()
- const [wake] = await schedules(f.tab)
- expect(kindOf(wake!)).toBe('update-request')
- expect(wake!.source).toMatchObject({ kind: 'update-request', schedule: scheduleSlot(f.clock.now) })
- expect(wake!.text.indexOf('Work changed')).toBeLessThan(wake!.text.indexOf('Built-in schedule,'))
- expect((await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => kindOf(m) === 'schedule-request')).toEqual([])
+ expect((await schedules(f.tab)).map(kindOf)).toEqual(['schedule-request'])
})
- it('goes in the notice digest when one is written and no update request is', async () => {
+ it('goes in the notice digest when one is written', async () => {
const f = await swarm()
wantSchedule()
await f.write({ kind: 'idle' }, f.lead)
@@ -249,22 +231,6 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
expect(await schedules(f.tab)).toHaveLength(1)
})
- it('does not go in an update request already stored under its id', async () => {
- const f = await swarm({ fresh: true })
- wantSchedule()
- await f.write({ kind: 'idle' }, f.lead)
- await unassigned(f)
- f.clock.now += DUE
- const { projectUpdateRequest } = await import('../src/superTabs/projectUpdates.js')
- const { state } = await f.timed.read(host, f.tab, undefined, f.lead)
- const draft = projectUpdateRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!
- await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,
- mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })
- await f.poll()
- expect((await db.superTabMessage.findUniqueOrThrow({ where: { id: draft.id } })).text).not.toContain('Built-in schedule,')
- expect(await schedules(f.tab)).toHaveLength(1)
- })
-
it('sends nothing in a paused Swarm, and one wake for the current slot once it resumes', async () => {
const f = await swarm()
wantSchedule()
@@ -275,6 +241,7 @@ describe('the built-in schedule on the coordinator\'s poll', () => {
await f.poll()
expect(await schedules(f.tab)).toEqual([])
await f.execute({ type: 'tab.pause', paused: false })
+ f.clock.now += 30_000
await f.poll()
expect(await schedules(f.tab)).toHaveLength(1)
expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })
@@ -322,3 +289,24 @@ describe('the daily tidy on the coordinator\'s poll', () => {
expect(await tidies(f.tab)).toHaveLength(2)
})
})
+
+// A kept message's deliveries were read by message id alone: a scan of all 43 k deliveries, 440 ms inside this write transaction, 21 times
+// a day (Atlas slow log, 2026-11-04). The path is the Lead's poll keeping a message already stored; this wake is one (the update request
+// that used to carry this check is gone, task #3593).
+describe('a poll keeping a message already stored', () => {
+ it('reads its deliveries by Swarm and message, examining only those', async () => {
+ const f = await swarm({ fresh: true })
+ wantSchedule()
+ await unassigned(f)
+ f.clock.now += DUE
+ const { state } = await f.timed.read(host, f.tab, undefined, f.lead)
+ const { draft } = scheduleRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!
+ await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,
+ mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })
+ const entries = await profiled(db, () => f.poll())
+ const rows = reads(entries, 'SuperTabDelivery', ['messageId'], ['agentId'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, messageId: 1/)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(1)
+ })
+})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 69905813b..fa385a34f 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -860,9 +860,9 @@ describe('private swarm projects on the real control API', () => {
name: 'Moved lead', configuration: config, lead: false })).rejects.toMatchObject({ code: 'PROJECT_SESSION' })
})
- // Quiet project chats (Dee, 2026-10-31): a work group's change of state wakes the coordinator at most once every 15 minutes,
- // an ordinary message never; its report sets the project's status card and posts nothing; the digest is on by default.
- it('wakes the coordinator only on work changes, at most every 15 minutes, and keeps its report in the status card', async () => {
+ // Quiet project chats (Dee, 2026-10-31; task #3593): the server writes the status card's lines from task state and wakes the coordinator
+ // for none of them; its report adds its own lines after them and posts nothing; the digest is on by default.
+ it('wakes the coordinator for no work change, shows the server\'s card with its own lines, and sends the digest by default', async () => {
wantDefaultDigest()
// 14:00 in Vietnam: the default digest starts tomorrow at 08:00.
let now = Date.UTC(2026, 9, 31, 7, 0)
@@ -874,46 +874,37 @@ describe('private swarm projects on the real control API', () => {
harnessId: randomUUID(), name: 'Lead', configuration: config, lead: true })).result.agentId)
const updates = async () => (await timed.deliveries(host, tab, lead)).filter(d => d.conversationId === 'lead')
const chat = async () => db.superTabMessage.findMany({ where: { tabId: tab, conversationId: 'lead' } })
+ const status = async () => (await timed.read(owner, tab)).state.projects!.find(p => p.id === 'lead')!.status
expect(await updates()).toEqual([])
const group = String((await execute({ type: 'conversation.create', title: 'Work', brief: 'Implement it',
checks: [{ description: 'Verified', independent: true }] })).result.conversationId)
- // Five minutes on, so a burst of changes is one wake-up (the quiet poll's 30 s fit within that).
- now += 299_999
+ // No wake-up however long it waits: the poll that used to carry the card's request finds nothing.
+ now += 330_000
expect(await updates()).toEqual([])
- now += 30_001
- const polls = await Promise.all(Array.from({ length: 3 }, () => updates()))
- const ids = new Set(polls.flat().map(d => d.id))
- expect(ids.size).toBe(1)
- // After the row naming who added the Lead (#2207); a task no message asked for posts nothing in the chat (#2925).
- expect((await chat()).map(m => (m.source as Record<string, unknown>)?.kind)).toEqual(['system', 'update-request'])
- await execute({ ...message('New evidence'), conversationId: group } as Command)
now += 900_000
- expect((await updates()).map(d => d.id)).toEqual([...ids])
- // The Lead reports through what it read of each workgroup: the card, and nothing in the chat.
- const read = (await timed.read(owner, tab)).state.conversations.find(c => c.id === group)!
- const card = 'Work: implementation ready, verification next.'
- await execute({ type: 'project.report', projectId: 'lead', through: { [group]: read.lastMessageSequence }, text: card }, lead)
+ expect(await updates()).toEqual([])
+ // After the row naming who added the Lead (#2207); a task no message asked for posts nothing in the chat (#2925).
+ expect((await chat()).map(m => (m.source as Record<string, unknown>)?.kind)).toEqual(['system'])
+ // The server wrote the card: one line for the task, which waits on an owner.
+ expect((await status())!.text).toContain('"Work": to do. Waits on: an owner. Owner: none.')
+ // The Lead's report adds its own lines after the server's, and posts nothing.
+ const card = 'Freeze starts Friday.'
+ await execute({ type: 'project.report', projectId: 'lead', through: {}, text: card }, lead)
expect(await updates()).toEqual([])
expect((await chat()).filter(m => m.text === card || (m.source as Record<string, unknown>)?.kind === 'project-report')).toEqual([])
- expect((await timed.read(owner, tab)).state.projects!.find(p => p.id === 'lead')!.status).toEqual({ text: card, at: new Date(now).toISOString(), by: lead })
- // An ordinary message, here an hour of them, wakes nobody.
+ expect((await status())!.text).toContain('"Work": to do.')
+ expect((await status())!.text.endsWith(card)).toBe(true)
+ // An ordinary message, a second task and a merge wake nobody.
await execute({ ...message('Tests passed'), conversationId: group } as Command)
now += 3_600_000
- expect(await updates()).toEqual([])
- // Two changes within 15 minutes: one wake-up now, the second waits for the next window.
await execute({ type: 'conversation.create', title: 'Docs', brief: 'Write them', checks: [{ description: 'Read', independent: false }] })
- now += 300_000
- expect(await updates()).toHaveLength(1)
- const answered = (await timed.read(owner, tab)).state.conversations.filter(c => c.title === 'Docs' || c.id === group)
- await execute({ type: 'project.report', projectId: 'lead', through: Object.fromEntries(answered.map(c => [c.id, c.lastMessageSequence])), text: null }, lead)
- expect(await updates()).toEqual([])
await execute({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/example/app/pull/7' })
- now += 600_000
+ now += 900_000
expect(await updates()).toEqual([])
- now += 300_000
- expect(await updates()).toHaveLength(1)
- // The card stayed through the acknowledgement, and the morning digest comes by default at 08:00 the next day.
- expect((await timed.read(owner, tab)).state.projects!.find(p => p.id === 'lead')!.status!.text).toBe(card)
+ const lines = (await status())!.text
+ expect(lines).toContain('"Docs": to do.')
+ expect(lines.endsWith(card)).toBe(true)
+ // The morning digest comes by default at 08:00 the next day.
expect((await chat()).some(m => (m.source as Record<string, unknown>)?.kind === 'digest-request')).toBe(false)
now = Date.UTC(2026, 10, 1, 1, 0) + 30_000
await updates()
@@ -5196,14 +5187,11 @@ describe('Swarm sweeps', () => {
await run(tab, { type: 'project.report', projectId: 'lead', through: { [group]: read.lastMessageSequence }, text: null }, host, lead)
}
- it('puts a conversation archived by hand to sleep once its reports are acknowledged, and ordinary loads stop reading it', async () => {
+ it('puts a conversation archived by hand to sleep at once, with no report to wait for, and ordinary loads stop reading it (#3593)', async () => {
const { tab, lead } = await fixture()
const group = await finishedGroup(tab, lead)
await run(tab, { type: 'conversation.archive', conversationId: group, archived: true })
const loaded = async () => (await db.$transaction(tx => parts.loadActive(tx, tab))).groups.map(p => p.key)
- expect(await loaded()).toContain(group)
- await acknowledge(tab, lead, group)
- await sweepSwarms(db)
expect(await loaded()).not.toContain(group)
expect((await db.$transaction(tx => parts.loadDormant(tx, tab, {}))).map(p => p.key)).toEqual([group])
// Reopened, it is active again.
@@ -5217,10 +5205,7 @@ describe('Swarm sweeps', () => {
const listed = async () => (await store.read(owner, tab)).state.conversations.map(c => c.id)
await sweepSwarms(db, Date.now() + day - 60_000)
expect(await listed()).toContain(group)
- // Its reports are not acknowledged yet: it stays awake, where the Lead's report check sees it.
- await sweepSwarms(db, Date.now() + day + 60_000)
- expect(await listed()).toContain(group)
- await acknowledge(tab, lead, group)
+ // No report is waited for (task #3593): after the quiet day it sleeps.
await sweepSwarms(db, Date.now() + day + 60_000)
expect(await listed()).not.toContain(group)
// The Lead conversation stays awake whatever its age.
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index c46c3ea55..a3a74a24e 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -2,6 +2,7 @@ import { authorizeTaskApproval, pendingTaskApproval, personalApprovalCommand, re
import type { PullRequestFilesRead } from './pullRequestFiles.js'
import { legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'
import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'
+import { linesOf } from './statusCard.js'
import { applyPushOrigin, barredFromTeamWritten, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, ownersOwnAgent, ownersOwnMachine, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import { crewMoveFailed, takeOverCrewMember, wakeCrewMember } from './crewKeep.js'
import { moveTimingRow, startWake } from './crewTimes.js'
@@ -53,7 +54,7 @@ import { reviewCapacityNotice } from './reviewCapacity.js'
import { processOf, taskProcess, type ProjectProcess } from './process.js'
import { digestStartsAfter, knownTimeZone } from './digest.js'
import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'
-import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'
+import { reportGroups, summarize } from './projectUpdates.js'
import { cloneData } from './cloneData.js'
import { WORKSPACE_LABEL, workspaceCan, type WorkspaceRole } from './workspaces.js'
import { fixedOriginal, LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordFix, recordDecision, recordMerged, recordPost, recordProposal, recordReview, recordRun, recordStatus,
@@ -266,7 +267,7 @@ export const commandSchema = z.discriminatedUnion('type', [
// wake-up from before the store by parts named; it is accepted only up to that split (projectUpdates.ts).
z.object({ type: z.literal('project.report'), projectId: id, through: z.record(id, z.number().int().nonnegative().safe()).optional(),
throughRevision: z.number().int().nonnegative().safe().optional(),
- text: z.string().trim().min(1).max(PROJECT_STATUS_MAX, `Keep the status card under ${PROJECT_STATUS_MAX.toLocaleString('en-US')} characters: one short line per active task.`).nullable() }).strict()
+ text: z.string().trim().min(1).max(PROJECT_STATUS_MAX, `Keep your own status lines under ${PROJECT_STATUS_MAX.toLocaleString('en-US')} characters: the Swarm writes the line of every active task.`).nullable() }).strict()
.refine(c => (c.through === undefined) !== (c.throughRevision === undefined), 'Acknowledge with through, the map your wake-up names.'),
z.object({ type: z.literal('project.repository'), projectId: id, repositoryUrl }).strict(),
// The project's instructions, saved on the revision the writer read (instructions.ts). `askedBy`: the member whose words it
@@ -1087,7 +1088,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
for (const row of effects.messages) row.recipients = row.recipients.filter(id => pmAcceptsMessage(effects.state, id, row.source))
// Every open group is loaded for a command (parts/load.ts): the board's pulse is worked out on it (pulse.ts), for the project
// of the conversation the command names when it names one (it moves no other), else for every project.
- recordPulse(effects.state, context.now, pulseProjectOf(effects.state, input))
+ const only = pulseProjectOf(effects.state, input)
+ recordPulse(effects.state, context.now, only, linesOf(original, context.now, only))
return effects
}
@@ -2119,7 +2121,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// Without text the report only acknowledges, and the card stays.
if (command.text) {
mutableProjects(state)
- projectOf(state, project.id).status = { text: command.text, at: new Date(context.now).toISOString(), by: (actor as Extract<Actor, { kind: 'agent' }>).agentId }
+ projectOf(state, project.id).status = { text: command.text, at: new Date(context.now).toISOString(), by: (actor as Extract<Actor, { kind: 'agent' }>).agentId, own: true }
}
break
}
@@ -3224,9 +3226,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (tags.length) message(group.id, `Archived without shipping: the task was cancelled${cancelReason(group) ? ` (${cancelReason(group)})` : ''}.`, [], null, SYSTEM_ROW, undefined, tags)
group.archived = command.archived
if (command.archived) endStepsOf(group, `${group.title} was archived.`, true)
- // Archived by hand, it leaves the active set until it is reopened (spec, Archive), once its reports are acknowledged:
- // until then the sweep leaves it in the active set, where the report check sees it (design section 3.6).
- if (command.archived && !dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
+ // Archived by hand, it leaves the active set until it is reopened (spec, Archive). No report is waited for: the server writes
+ // the status card (task #3593).
+ if (command.archived) group.dormant = true
else delete group.dormant
break
}
diff --git a/backend/src/superTabs/hotFilters.allowed.json b/backend/src/superTabs/hotFilters.allowed.json
index 52242d03b..bf372a04a 100644
--- a/backend/src/superTabs/hotFilters.allowed.json
+++ b/backend/src/superTabs/hotFilters.allowed.json
@@ -17,7 +17,6 @@
"src/superTabs/store.ts superTab.findMany": 1,
"src/superTabs/store.ts superTabAttachment.findMany": 2,
"src/superTabs/store.ts superTabAttachment.updateMany": 2,
- "src/superTabs/store.ts superTabDelivery.findFirst": 1,
"src/superTabs/store.ts superTabDelivery.findMany": 1,
"src/superTabs/store.ts superTabDelivery.updateMany": 11,
"src/superTabs/store.ts superTabOperation.findMany": 1,
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 9f36e195d..587d2fbd0 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -1,4 +1,5 @@
import { recordPulse } from './pulse.js'
+import { linesOf } from './statusCard.js'
import { CREW_REOPEN_GRACE_MS, isCrew } from './crew.js'
import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,
type SuperTabState, type TaskLiveness } from './model.js'
@@ -504,9 +505,11 @@ function unpurged(state: SuperTabState, now: number): MessageDraft[] {
* Lead's poll runs them, where the whole active Swarm is loaded and the one they wake is listening: a machine's reading
* loads only running work and must write no group (read/host.ts). */
export function sweepForLead(state: SuperTabState, now: number, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
+ // Each task's status line before the sweep moves any (statusCard.ts): only the lines it moves are written.
+ const before = linesOf(state, now)
const drafts = [...sweepLiveness(state, now, rulesFor), ...recordTaskStates(state, now)]
// Where the whole active Swarm is loaded, as for a command: a task lost here may leave Working at 0 (pulse.ts).
- recordPulse(state, now)
+ recordPulse(state, now, undefined, before)
return drafts
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0477e22f7..68e50ea4a 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -11,6 +11,7 @@ import { downSince, expireRemovals, startPreparing } from './machines.js'
import { publicReason, readsRawReason } from './startFailure.js'
import { FIRST_INSTRUCTIONS } from './instructions.js'
import { visibleAccess } from './machineAccess.js'
+import { projectCard, withExtra } from './statusCard.js'
import { processOf, projectColumns } from './process.js'
import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, groupProject, ledProject, ownerlessProjects, ownsProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
@@ -574,6 +575,9 @@ export interface Conversation {
chatLimits?: import('./chatLimits.js').ChatLimits
/** On a project's chat: its project's pulse as last worked out (pulse.ts recordPulse), which every read sends in `derived`. */
pulse?: import('./pulse.js').Pulse
+ /** On a task: its line on its project's status card as the server last wrote it (statusCard.ts noteTaskLines, task #4419).
+ * Readers get the lines in the project's `status` text (visibleState), never as a field. */
+ statusLine?: import('./statusCard.js').StatusLine
}
/** A step up: the attempt it opened (2 or 3), the least quality from then on, why, when, and what the failed attempt left for
* the next one's brief; the failed start that caused it, if one did. */
@@ -1245,9 +1249,17 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
// loaded, by nobody.
visible.projects = visible.projects.map(({ owed: _owed, ...p }) => {
// What the PM owes is its host's alone (timeChecks.ts owedAsk): it may name a message in someone's private chat.
- if (p.status === undefined) return p
const chat = state.conversations.find(c => c.id === p.leadConversationId)
- if (chat && canReadGroup(state, actor, chat)) return p
+ if (chat && canReadGroup(state, actor, chat)) {
+ // The server's lines, built from the tasks' own (statusCard.ts), then the coordinator's own; the stored status text is only
+ // the latter.
+ if (p.status?.shown) return p
+ const card = projectCard(state, p, now)
+ if (!card.text) return p
+ const lastChange = card.changedAt ?? Date.now()
+ return { ...p, status: { text: withExtra(card.text, p.status?.own ? p.status.text : null), at: new Date(lastChange).toISOString(), by: p.status?.by ?? chat.leadId ?? '', shown: true } }
+ }
+ if (p.status === undefined) return p
const { status: _status, ...rest } = p
return rest
})
diff --git a/backend/src/superTabs/notices.test.ts b/backend/src/superTabs/notices.test.ts
index 42f6133ef..f86d901ae 100644
--- a/backend/src/superTabs/notices.test.ts
+++ b/backend/src/superTabs/notices.test.ts
@@ -87,8 +87,8 @@ describe('the notices the Swarm writes into a chat', () => {
// the Shipped line, now the task's own line (taskLine.ts; Quiet Swarm, Dee, 2026-11-02), people; a machine's removal ending,
// no longer said in any chat (anh Dee, 11-04, #2742), nobody; a task's own row under its requester's name, now only a person's
// own message (anh Dee, 11-04, 'bot messages', #2925), people; an instructions save's line, now only in the Instructions
- // history (Dee and Ken, 11-05, #3132), people.
- const retired = ['idle-stop', 'project-report', 'ship', 'machine-left', 'task-line', 'routing-reflection', 'instructions']
+ // history (Dee and Ken, 11-05, #3132), people; the card wake-up, now written by the server (anh Dee, 11-06, #3593), the Lead.
+ const retired = ['idle-stop', 'project-report', 'ship', 'machine-left', 'task-line', 'routing-reflection', 'instructions', 'update-request']
expect(Object.keys(NOTICE_READERS).filter(kind => !written.has(kind) && !retired.includes(kind))).toEqual([])
expect(retired.filter(kind => written.has(kind))).toEqual([])
})
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 10d00c2ac..97328586a 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -86,6 +86,7 @@ const conversation: Required<Conversation> = {
requesterId: 'p',
reviewOf: 'r',
reviewStamp: { assignmentId: 'w', handoff: 1 },
+ statusLine: { text: '', since: 0 },
step: 'Review',
stepIds: [],
stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index ca2a4d61b..b88d89569 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -42,6 +42,7 @@ export const GROUP_FIELDS = {
'proposal',
'pulse',
'reviewOf',
+ 'statusLine',
'taskApproval',
],
whenRunning: [
diff --git a/backend/src/superTabs/projectStatus.test.ts b/backend/src/superTabs/projectStatus.test.ts
index 960e4e90e..6105d4113 100644
--- a/backend/src/superTabs/projectStatus.test.ts
+++ b/backend/src/superTabs/projectStatus.test.ts
@@ -1,13 +1,12 @@
import { describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
import { createSuperTab, visibleState, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
-import { BATCH_MS, noteWorkChanges, projectUpdateRequest, WAKE_GAP_MS } from './projectUpdates.js'
import { DEFAULT_DIGEST, digestDue, digestOf } from './digest.js'
import { projectOf } from './projects.js'
import { numberMessages } from './parts/commit.js'
-// Quiet project chats (Dee, 2026-10-31): a report sets the project's status card and posts nothing, only a work group's
-// state wakes the coordinator, at most once every 15 minutes, and every project gets the morning digest by default.
+// Quiet project chats (Dee, 2026-10-31): a report sets the coordinator's own lines on the project's status card and posts nothing,
+// the server writes the card's lines itself and wakes nobody for them (task #3593), and every project gets the morning digest by default.
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]' }
@@ -19,10 +18,8 @@ function fixture() {
let sequence = 0, now = 1_000_000
/** A command as the store runs it: numbered messages, then the work changes it made (store.ts execute). */
const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
- const before = state
const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })
numberMessages(effects.state, effects.messages, now)
- noteWorkChanges(before, effects.state, now)
state = effects.state
return effects
}
@@ -50,10 +47,10 @@ describe('the project status card', () => {
const f = fixture()
const first = f.run(report('Offline editing: PR #12 waiting on CI'), f.leadActor)
expect(first.messages).toEqual([])
- expect(projectOf(f.state, 'lead').status).toEqual({ text: 'Offline editing: PR #12 waiting on CI', at: new Date(f.now).toISOString(), by: f.lead })
+ expect(projectOf(f.state, 'lead').status).toEqual({ text: 'Offline editing: PR #12 waiting on CI', at: new Date(f.now).toISOString(), by: f.lead, own: true })
f.tick(MINUTE)
expect(f.run(report('Offline editing: merged'), f.leadActor).messages).toEqual([])
- expect(projectOf(f.state, 'lead').status).toEqual({ text: 'Offline editing: merged', at: new Date(f.now).toISOString(), by: f.lead })
+ expect(projectOf(f.state, 'lead').status).toEqual({ text: 'Offline editing: merged', at: new Date(f.now).toISOString(), by: f.lead, own: true })
// No text only acknowledges: the card stays.
expect(f.run(report(null), f.leadActor).messages).toEqual([])
expect(projectOf(f.state, 'lead').status!.text).toBe('Offline editing: merged')
@@ -104,77 +101,32 @@ describe('the project status card', () => {
})
})
-describe('the coordinator\'s scheduled wake-up', () => {
- const lead = (f: ReturnType<typeof fixture>) => f.state.agents.find(a => a.id === f.lead)!
- /** The coordinator answers the request it got: everything summarized through what it read. */
- const answer = (f: ReturnType<typeof fixture>, request: NonNullable<ReturnType<typeof projectUpdateRequest>>) => {
- const progress = projectOf(f.state, 'lead').progress!
- progress.requested = { ...progress.requested, ...request.source!.through as Record<string, number> }
- progress.requestedAt = f.now
- f.run(report('Card', request.source!.through as Record<string, number>), f.leadActor)
- }
-
- it('is never asked for by an ordinary message or a progress note', () => {
+describe('no card wake-up for the coordinator (#3593)', () => {
+ // The server writes the card (statusCard.ts), so a work group's change marks nothing for the coordinator to read.
+ it('marks no work group for a report, whatever changes in it', () => {
const f = fixture(), group = f.group()
const engineer = f.add('engineer', group)
const as: Actor = { kind: 'agent', agentId: engineer, machineOwnerId: 'host-owner' }
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: engineer }).result.assignmentId as string
- f.tick(BATCH_MS)
- answer(f, projectUpdateRequest(f.state, lead(f), f.now)!)
- f.tick(WAKE_GAP_MS)
- f.run({ type: 'message.send', conversationId: group, text: 'Halfway there.', replyTo: null, recipientIds: [] }, as)
- f.run({ type: 'message.send', conversationId: group, text: 'How is it going?', replyTo: null, recipientIds: [engineer] }, owner)
- // Still working: a progress note changes no state.
- f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'working', result: 'Tests written' }, as)
- f.tick(WAKE_GAP_MS)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- // Ready for review is a change: it wakes the coordinator five minutes on.
+ f.tick(5 * MINUTE)
f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'PR #7' }, as)
- f.tick(BATCH_MS - 1)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(1)
- expect(projectUpdateRequest(f.state, lead(f), f.now)?.source).toMatchObject({ kind: 'update-request', through: { [group]: expect.any(Number) } })
+ f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/example/app/pull/7' })
+ f.tick(15 * MINUTE)
+ expect(f.state.conversations.find(c => c.id === group)!.reportSeq).toBeUndefined()
+ expect(projectOf(f.state, 'lead').progress).toBeUndefined()
})
- it('is asked for by a work group\'s change of state, at most once every 15 minutes', () => {
- const f = fixture()
- // A new group is a change: the wake-up comes five minutes on, so a burst of changes is one.
- const a = f.group()
- f.tick(BATCH_MS - 1)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(1)
- const first = projectUpdateRequest(f.state, lead(f), f.now)
- expect(first?.source).toMatchObject({ kind: 'update-request' })
- answer(f, first!)
- // Two changes within 15 minutes wake it once.
- f.tick(MINUTE)
- const b = f.group()
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(5 * MINUTE)
- f.run({ type: 'conversation.merged', conversationId: a, pullRequestUrl: 'https://github.com/example/app/pull/7' })
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(WAKE_GAP_MS - 6 * MINUTE - 1)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(1)
- const second = projectUpdateRequest(f.state, lead(f), f.now)!
- expect(Object.keys(second.source!.through as object).sort()).toEqual([a, b].sort())
- expect(second.text).toContain('status card')
- answer(f, second)
- f.tick(WAKE_GAP_MS)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
+ it('lets an archived group go quiet at once, with no report to wait for', () => {
+ const f = fixture(), group = f.group()
+ f.run({ type: 'conversation.archive', conversationId: group, archived: true })
+ expect(f.state.conversations.find(c => c.id === group)!.dormant).toBe(true)
})
- it('keeps its 15 minutes whatever cadence an older client set', () => {
- const f = fixture()
- f.run({ type: 'project.cadence', projectId: 'lead', minutes: 1 })
- f.group()
- f.tick(BATCH_MS)
- answer(f, projectUpdateRequest(f.state, lead(f), f.now)!)
- f.tick(MINUTE)
- f.group()
- expect(projectUpdateRequest(f.state, lead(f), f.now)).toBeNull()
- f.tick(WAKE_GAP_MS - MINUTE)
- expect(projectUpdateRequest(f.state, lead(f), f.now)).not.toBeNull()
+ it('still takes an older host\'s report with through, and keeps its text as the coordinator\'s own lines', () => {
+ const f = fixture(), group = f.group()
+ f.run(report('Freeze starts Friday.', { [group]: 1 }), f.leadActor)
+ expect(projectOf(f.state, 'lead').status!.text).toBe('Freeze starts Friday.')
+ expect(JSON.stringify(visibleState(f.state, owner))).toContain('Freeze starts Friday.')
})
})
diff --git a/backend/src/superTabs/projectUpdates.ts b/backend/src/superTabs/projectUpdates.ts
index 1a8fca6bc..f332e5136 100644
--- a/backend/src/superTabs/projectUpdates.ts
+++ b/backend/src/superTabs/projectUpdates.ts
@@ -1,9 +1,10 @@
-import { author, conversation, isLeads, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-import { agentProjectId, groupProject, NO_PROJECT, projectOf, type SwarmProject } from './projects.js'
+import { isLeads, type Conversation, type SuperTabState } from './model.js'
+import { groupProject, type SwarmProject } from './projects.js'
import type { ProgressData } from './parts/types.js'
-/** A project with no report progress yet starts clean at the start of every conversation's numbering. */
-const freshProgress = (now: number): ProgressData => ({ since: now, summarizedFloor: 0, summarized: {}, requestedFloor: 0, requested: {} })
+// The coordinator is no longer woken to rewrite the status card (task #3593): the server writes the card's lines (statusCard.ts), so
+// nothing marks a work group for a report. What stays is the watermark an older host's project.report still moves, and the check
+// that a group owes its project nothing before it sleeps.
/** The conversations whose posts count toward a project's reports: not its Lead conversation, not the Leads
* conversation, not a private conversation (its posts never reach the Lead's summary to everyone). */
@@ -11,53 +12,6 @@ export function reportGroups(state: SuperTabState, project: SwarmProject): Conve
return state.conversations.filter(c => !isLeads(c) && !c.audience && c.id !== project.leadConversationId && groupProject(state, c).id === project.id)
}
-/** A conversation is dirty while its last report is past what its Lead summarized (design section 3.6). */
-export function dirtyGroups(state: SuperTabState, project: SwarmProject): Conversation[] {
- const progress = project.progress
- if (!progress) return []
- return reportGroups(state, project).filter(g => (g.reportSeq ?? 0) > (progress.summarized[g.id] ?? progress.summarizedFloor))
-}
-
-/** The least time between two of a project's scheduled wake-ups (Dee, 2026-10-31: "even at 30 min that's 48 updates a day").
- * A question, a blocker or completion reaches the coordinator at once anyway, as the status line's recipients. */
-export const WAKE_GAP_MS = 15 * 60_000
-/** How long after a project's first change since its last report the wake-up waits, so a burst (a task created, assigned
- * and started) is one wake-up. */
-export const BATCH_MS = 5 * 60_000
-
-/** What of a work group's state wakes its coordinator: its task (assigned, a new one), the task's status (review, done,
- * blocked, needs_human, cancelled; a review group's verdict is its own task's status), a review's findings, its merges and
- * pull requests. Ordinary messages, progress notes, terminal turns and archiving change none of it. */
-const workState = (group: Conversation): string => JSON.stringify([group.assignment?.id ?? null, group.assignment?.status ?? null,
- group.assignment?.reviewFoundAt ?? null, group.ledger?.mergedAt ?? null, group.pullRequestUrls?.length ?? 0])
-
-/** Marks each work group whose state this write changed, or that it created, through its latest message, so the wake-up
- * asks the coordinator to read it; the project's progress changes only when the project goes from clean to dirty, so
- * changes in different conversations of one project never write the same part (spec ruling 1). */
-export function noteWorkChanges(before: SuperTabState, after: SuperTabState, now: number) {
- if (!after.projects) return
- const prior = new Map(before.conversations.map(g => [g.id, g]))
- for (const group of after.conversations) {
- if (isLeads(group) || group.audience) continue
- const was = prior.get(group.id)
- if (was && workState(was) === workState(group)) continue
- const project = groupProject(after, group)
- if (group.id === project.leadConversationId) continue
- const clean = !project.progress || !dirtyGroups(after, project).length
- project.progress ??= freshProgress(now)
- group.reportSeq = Math.max(group.reportSeq ?? 0, group.messageSeq ?? 0)
- if (clean) project.progress.since = now
- }
-}
-
-/** What each dirty conversation's report reaches, by conversation: what a wake-up asks the Lead to acknowledge. */
-const throughOf = (groups: Conversation[]) => Object.fromEntries(groups.map(g => [g.id, g.reportSeq ?? 0]).sort(([a], [b]) => a! < b! ? -1 : 1))
-
-/** How long an update request the Lead's host received holds later ones back while unanswered. On 26 Oct one was never
- * answered and held its project's every later request: its reports were never summarized, and 372 archived conversations
- * could not go quiet for two days (prod, 2026-10-28). One not yet received (its host offline) holds them as before. */
-export const UNANSWERED_REQUEST_MS = 2 * 60 * 60_000
-
/** How a report names [group]: its number (its title when it has none); a step also names its task (task steps design), and
* keeps its own number, which is the conversation whose messages the report asks the coordinator to read. */
export function reportedAs(state: SuperTabState, group: Conversation): string {
@@ -66,38 +20,6 @@ export function reportedAs(state: SuperTabState, group: Conversation): string {
return task ? `${name(group)} (step ${group.step ?? group.title} of ${name(task)})` : name(group)
}
-export function projectUpdateRequest(state: SuperTabState, target: Agent, now: number): MessageDraft | null {
- // An older Swarm without stored projects is one synthesized project. It keeps no report progress (noteWorkChanges),
- // so its Lead is woken only for lost work (liveness.ts), which replaced the wake-up for workers down two hours.
- if (state.paused) return null
- // An agent in no project (a Regular one between tasks, task #4116) leads none.
- if (agentProjectId(state, target) === NO_PROJECT) return null
- const project = projectOf(state, agentProjectId(state, target))
- const group = conversation(state, project.leadConversationId), progress = project.progress
- if (group.leadId !== target.id || group.archived) return null
- const dirty = dirtyGroups(state, project)
- // Five minutes after the first change, and at most once every 15 minutes, whatever cadence an older client set
- // (updateMinutes is still read, never used here).
- const reports = !!progress && dirty.some(g => (g.reportSeq ?? 0) > (progress.requested[g.id] ?? progress.requestedFloor)) &&
- now >= Math.max(progress.since + BATCH_MS, progress.requestedAt === undefined ? 0 : progress.requestedAt + WAKE_GAP_MS)
- if (!reports) return null
- const through = throughOf(dirty)
- const id = stableId('project-update', state.id, project.id, JSON.stringify(through))
- const after = (g: Conversation) => `${reportedAs(state, g)} after ${progress!.summarized[g.id] ?? progress!.summarizedFloor}`
- const text = `Work changed in project ${JSON.stringify(project.name)}. ` +
- `Read the new messages of these workgroups: ${dirty.map(after).join(', ')}; inspect their current work. ` +
- 'Then keep the project\'s status card current: one short line per active task saying where it is, what changed, and what it waits on; ' +
- 'nothing repeated from the cards in the chat. The card updates in place and posts nothing to the chat. This is a scheduled request, not a new task. ' +
- `Use harness super-tab --tab ${state.id} command UNIQUE_OPERATION_ID ` +
- `JSON with {"type":"project.report","projectId":"${project.id}","through":${JSON.stringify(through)},"text":"the whole card"}. ` +
- 'Use text:null to acknowledge when the card is still right. Reuse the same operation ID after a lost reply. ' +
- 'Post in the project chat only when work merges or ships, a person must decide something new, or work is badly stuck, in one or two lines with the link.'
- return { id, conversationId: group.id,
- author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }),
- text, replyTo: null, recipients: [target.id],
- source: { kind: 'update-request', projectId: project.id, through } }
-}
-
/** A Lead's report: each conversation it names is summarized through what it read, never past its last report. A legacy
* scalar from a wake-up written before the split covers every conversation up to that tab revision. */
export function summarize(state: SuperTabState, project: SwarmProject, through: Record<string, number>): void {
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 05e3ef5f4..e581c9513 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -144,7 +144,13 @@ export const GITHUB_SEEN = ['not-installed', 'not-approved', 'covered'] as const
export type GitHubSeen = typeof GITHUB_SEEN[number]
/** A project's status card: its text, when (ISO time) and by which agent it was written. */
-export interface ProjectStatus { text: string; at: string; by: string }
+export interface ProjectStatus { text: string; at: string; by: string
+ /** The text is the coordinator's own lines, shown after the server's (statusCard.ts, task #3593). Absent on a card saved before:
+ * that text was the whole card, whose lines the server now writes, so it is not shown beside them. */
+ own?: true
+ /** Set by visibleState on the text it shows readers (the server's lines with the coordinator's own): a view applied again to a
+ * view leaves it as it is. Never stored. */
+ shown?: true }
export const PROJECT_STATUS_MAX = 2_000
export const skillModeOf = (project: SwarmProject): SkillMode => project.skillMode ?? 'orchestration'
diff --git a/backend/src/superTabs/pulse.ts b/backend/src/superTabs/pulse.ts
index 2a1b8fbe3..1ab1a0aa6 100644
--- a/backend/src/superTabs/pulse.ts
+++ b/backend/src/superTabs/pulse.ts
@@ -12,6 +12,7 @@ import { heldView, type HeldReason } from './heldReason.js'
import { isLeads, type Author, type Conversation, type SuperTabState } from './model.js'
import { agentProjectId, groupProject, type SwarmProject } from './projects.js'
import { unconfirmedNote } from './processNotes.js'
+import { noteTaskLines, type LinesBefore } from './statusCard.js'
import { switched } from './boardRights.js'
/** One person's message to the PM not settled yet: its id, who wrote it, when, and the root of the thread it is in (its own
@@ -211,7 +212,7 @@ export const PULSE_LIST_MAX = 50
* and on the PM's sweep, so the board reddens on time without anyone's poll. Writes only on a change. When Working fell to 0
* while work waits is kept in it (`idleSince`) from one run to the next.
*/
-export function recordPulse(state: SuperTabState, now: number, only?: string): void {
+export function recordPulse(state: SuperTabState, now: number, only?: string, before?: LinesBefore): void {
// The asks of a person who left the Swarm are owed to nobody, however they left.
const people = new Set(state.people.map(p => p.id))
for (const group of state.conversations) if (group.owed?.some(ask => !people.has(ask.personId))) settle(group, ask => !people.has(ask.personId))
@@ -224,6 +225,9 @@ export function recordPulse(state: SuperTabState, now: number, only?: string): v
if (!chat) continue
const pulse = projectPulse(state, project, now, PULSE_LIMITS, index, chat.pulse?.idleSince ?? null)
if (JSON.stringify(pulse) !== JSON.stringify(chat.pulse)) chat.pulse = pulse
+ // Each task's status line (statusCard.ts), on the task, written only where this pass moved it (task #4419): a command and the
+ // Lead's sweep give the lines from before they changed anything.
+ if (before) noteTaskLines(state, project, index, now, dayOf(now), before)
}
}
diff --git a/backend/src/superTabs/read/changes.test.ts b/backend/src/superTabs/read/changes.test.ts
index 1932f757d..c1990a396 100644
--- a/backend/src/superTabs/read/changes.test.ts
+++ b/backend/src/superTabs/read/changes.test.ts
@@ -31,10 +31,10 @@ function write(parts: SwarmParts, kind: Kind, key: string, change: (part: Part)
return part
}
/** What the reader receives: its view of the active (live) parts, then the changed parts run through its read check. */
-function receive(parts: SwarmParts, changed: Part[], actor: Actor) {
+function receive(parts: SwarmParts, changed: Part[], actor: Actor, cursor?: number) {
const active = { ...parts, ...Object.fromEntries((['members', 'agents', 'groups', 'machines', 'starts', 'progress'] as Kind[])
.map(kind => [kind, (parts[kind] as Part[]).filter(p => !p.deleted && !p.dormant)])) } as SwarmParts
- return changesFor(readerView(active, actor, LATER, { teamMachines: [] }), changed, actor)
+ return changesFor(readerView(active, actor, LATER, { teamMachines: [] }), changed, actor, undefined, cursor)
}
const keys = (list: Array<{ key: string }>) => list.map(p => p.key)
@@ -47,6 +47,32 @@ describe('changes since a cursor (design 4.4)', () => {
expect(receive(parts, [head], peer).head).toMatchObject({ key: 'head', version: R + 1 })
})
+ // Tasks #3593, #4419: each task keeps its own status line, but readers get the card in the head's project; a change poll that
+ // sent only the task would leave Desktop and web on the old card until something else moved the head. The head goes only when
+ // a changed task's line moved since the reader's cursor: a task changes with every message, and the head is large.
+ it('sends the head with a task whose status line moved since the cursor, so a live reader sees the card move', () => {
+ const { s, parts } = scene()
+ const line = { text: '#1 "Web": working. Waits on: nothing. Owner: Ada.', since: NOW }
+ const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object }).statusLine = line })]
+ const received = receive(parts, changed, owner, NOW - 1_000)
+ expect(received.head).not.toBeNull()
+ expect(received.head!.data.projects![0]!.status!.text).toContain('#1 "Web": working.')
+ })
+
+ it('sends the head with a task whose line left the card since the cursor', () => {
+ const { s, parts } = scene()
+ const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object }).statusLine = { text: '', since: NOW } })]
+ expect(receive(parts, changed, owner, NOW - 1_000).head).not.toBeNull()
+ })
+
+ it('leaves the head out for a task change that left its line as the reader already has it', () => {
+ const { s, parts } = scene()
+ // The line moved long before the reader's cursor; the task changed since for another reason (a message, a title).
+ const line = { text: '#1 "Web": working. Waits on: nothing. Owner: Ada.', since: NOW - 3_600_000 }
+ const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object; title: string }).statusLine = line; (p.data as { title: string }).title = 'Web 3' })]
+ expect(receive(parts, changed, owner, NOW - 1_000).head).toBeNull()
+ })
+
it('sends a changed group whole to its readers and nothing to anyone else', () => {
const { s, parts } = scene()
const changed = [write(parts, 'groups', s.web, p => { (p.data as { title: string }).title = 'Web 2' }),
diff --git a/backend/src/superTabs/read/changes.ts b/backend/src/superTabs/read/changes.ts
index 5e7b9c46e..d3dd99c42 100644
--- a/backend/src/superTabs/read/changes.ts
+++ b/backend/src/superTabs/read/changes.ts
@@ -12,13 +12,15 @@ import { envelope, progressView, seenIn, visibleGroupView, type ReaderView } fro
export type PartChanges = Pick<ChangesDelta, 'head' | 'members' | 'agents' | 'groups' | 'machines' | 'machineReadings' | 'starts' | 'progress'>
+/** A command's own time can be a little before the stamp of the part it wrote, so a read between them still finds the card moved. */
+const CARD_SKEW_MS = 60_000
const stub = (part: Part): Tombstone => ({ key: part.key, version: part.version, changedAt: part.changedAt, deleted: true })
const dormantStub = (part: Part): DormantStub => ({ key: part.key, version: part.version, changedAt: part.changedAt, dormant: true })
/** A read check that names a project which no longer exists answers no. */
const safely = (check: () => boolean): boolean => { try { return check() } catch { return false } }
/** [light]: the reader asked for a line for a machine's own reading, and its cursor's time: anything else since then sends the part. */
-export function changesFor(view: ReaderView, changed: Part[], actor: Actor, light?: { since: number }): PartChanges {
+export function changesFor(view: ReaderView, changed: Part[], actor: Actor, light?: { since: number }, cursor?: number): PartChanges {
const { state, parts: seen } = view
const live = <T>(list: Array<{ key: string } & T>, key: string) => list.find(p => p.key === key)
const groupReadable = (group: Conversation) => safely(() => canReadGroup(state, actor, group))
@@ -51,6 +53,10 @@ export function changesFor(view: ReaderView, changed: Part[], actor: Actor, ligh
else if (groupReadable(part.data as Conversation)) {
const group = part.data as Conversation
out.groups.push(envelope(part, visibleGroupView(buddy ? groupForBuddy(group) : group, visibleAgents, seenMachines)))
+ // A task whose status line moved since the reader's cursor (statusCard.ts, tasks #3593, #4419): readers get the card in the
+ // head's project, so the head goes with it, or a live reader keeps the old card until something else moves the head. Only
+ // then: a task changes with every message, and the head is large. A reader with no cursor to compare gets it.
+ if (group.statusLine && !out.head && (cursor === undefined || group.statusLine.since >= cursor - CARD_SKEW_MS)) out.head = seen.head
}
break
}
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 6a92d1820..334d01f9a 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -222,7 +222,7 @@ export class SwarmReads {
...marks.map(mark => mark.conversationId), ...threadMarks.keys(), ...settings.keys()])].filter(id => !held.has(id))
const read = await this.load(tx, cached, user, tabId, asAgentId, t0, {},
async () => withStarts(withGroups(base, await readLightGroups(tx, cached, tabId, named)), extra), taggedRows)
- const sent = changesFor(read.view, changed, read.actor, options.lightMachines ? { since: from.since } : undefined)
+ const sent = changesFor(read.view, changed, read.actor, options.lightMachines ? { since: from.since } : undefined, from.since)
// A changed project chat comes whole from the change feed, with its stored newest main row (servedTops.ts).
if (!asAgentId) sent.groups = await this.servedTops.served(tabId, read.view.state, sent.groups)
return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index ff09615c0..aeddc7c4c 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -72,7 +72,7 @@ export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, d
/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping or the
* leaderboard's (the leaderboard read sums it), except when it shipped. */
export function groupView(group: Conversation, seenMachines: ReadonlySet<string>): GroupView {
- const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, owed: _owed, answered: _answered, chatLimits: _chatLimits, talkedAt: _talkedAt, pulse: _pulse, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
+ const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, owed: _owed, answered: _answered, chatLimits: _chatLimits, talkedAt: _talkedAt, pulse: _pulse, statusLine: _statusLine, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
// A Buddy chat names its owner instead of an audience: an app from before Buddies takes a private chat of the reader
// alone for their Chat with PM, and would send what they write for the PM to their Buddy instead (buddies.ts).
const readers = isBuddyChat(group) ? { buddyOwnerId: audience!.people[0]!.id } : audience ? { audience } : {}
diff --git a/backend/src/superTabs/statusCard.test.ts b/backend/src/superTabs/statusCard.test.ts
new file mode 100644
index 000000000..6a1d39729
--- /dev/null
+++ b/backend/src/superTabs/statusCard.test.ts
@@ -0,0 +1,176 @@
+// Task #3593 (anh Dee, rules to code): the server writes the project's status card from task, step, pull request and release state,
+// one line per active task, so the PM is not woken every 15 minutes to reread messages and rewrite it.
+import { describe, expect, it } from 'vitest'
+import { appendPullRequestUrls, visibleState } from './model.js'
+import { projectOf } from './projects.js'
+import { PROJECT_STATUS_MAX } from './projects.js'
+import { cardText, projectCard } from './statusCard.js'
+import { owner, stepsFixture } from './steps.test-support.js'
+import { usernameOf } from './usernames.js'
+
+const PR = 'https://github.com/acme/app/pull/7'
+
+function cardFixture() {
+ const f = stepsFixture()
+ const chat = () => f.group('lead')
+ const lines = () => projectCard(f.state, projectOf(f.state, 'lead'), f.now).lines
+ const line = (id = f.task) => lines().find(l => l.id === id)
+ const text = () => visibleState(f.state, owner).projects!.find(p => p.id === 'lead')!.status?.text
+ const assignment = () => f.group(f.task).assignment!.id
+ const work = (status: 'working' | 'review' | 'blocked' | 'needs_human' | 'done', result: string | null = null) => {
+ const effects = f.run({ type: 'work.status', conversationId: f.task, assignmentId: assignment(), status, result }, f.as(f.dev))
+ // As the store does after each command: the Ready line's link is the task's linked pull request.
+ if (result?.includes(PR)) { appendPullRequestUrls(f.group(f.task), [PR]); f.run({ type: 'message.send', conversationId: 'lead', text: 'tick', replyTo: null, recipientIds: [] }) }
+ return effects
+ }
+ return Object.assign(f, { chat, lines, line, text, work, assignment })
+}
+
+describe('the status card the server writes (#3593)', () => {
+ it('has one line per active task with its state, what it waits on and its owner', () => {
+ const f = cardFixture()
+ expect(f.lines()).toHaveLength(1)
+ expect(f.line()!.text).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules.')
+ const second = f.run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks: [{ description: 'Saves', independent: true }],
+ priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string
+ expect(f.lines().map(l => l.id).sort()).toEqual([f.task, second].sort())
+ expect(f.line(second)!.text).toContain('to do. Waits on: an owner. Owner: none.')
+ })
+
+ it('says review with its pull request and the steps it waits on, and blocked, needs a person and lost', () => {
+ const f = cardFixture()
+ f.step('Review')
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ expect(f.line()!.text).toBe(`#1 "Fix login": in review (PR #7). Waits on: step Review. Owner: Jules.`)
+ f.work('blocked', 'Needs the CI key.')
+ expect(f.line()!.text).toContain('blocked. Waits on: the PM.')
+ f.work('needs_human', 'Which API?')
+ expect(f.line()!.text).toContain('needs a person. Waits on: a decision.')
+ f.group(f.task).assignment!.status = 'lost'
+ f.run({ type: 'message.send', conversationId: f.task, text: 'ping', replyTo: null, recipientIds: [] })
+ expect(f.line()!.text).toContain('lost. Waits on: another engineer.')
+ })
+
+ it('says a task waits on its requester\'s approval, leaves out a rejected one, and says a paused one is paused (Swarm v3)', () => {
+ const f = cardFixture()
+ f.run({ type: 'member.approvalMode', mode: 'review' })
+ const proposed = f.run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks: [{ description: 'Saves', independent: true }],
+ priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string
+ expect(f.line(proposed)!.text).toBe(`#2 "Offline editing": proposed. Waits on: @${usernameOf(f.state, 'owner')}'s approval. Owner: none.`)
+ f.run({ type: 'task.reject', conversationId: proposed, reason: 'Not now.' })
+ expect(f.line(proposed)).toBeUndefined()
+ f.run({ type: 'work.pause', conversationId: f.task, paused: true, reason: 'release freeze' })
+ expect(f.line()!.text).toBe('#1 "Fix login": paused. Waits on: a person to resume it (release freeze). Owner: Jules.')
+ f.run({ type: 'work.pause', conversationId: f.task, paused: false })
+ expect(f.line()!.text).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules.')
+ })
+
+ it('drops a task whose work ended, and shows a merged one until its release carries it', () => {
+ const f = cardFixture()
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ f.run({ type: 'conversation.merged', conversationId: f.task, pullRequestUrl: PR }, f.as(f.lead))
+ f.work('done', `Merged ${PR}`)
+ expect(f.line()!.text).toBe('#1 "Fix login": merged (PR #7). Waits on: the next release. Owner: Jules.')
+ const ledger = projectOf(f.state, 'lead').releases!
+ ledger.pending[0]!.components = ['backend']
+ ledger.pending[0]!.shippedIn = { backend: 'v1.4.18' }
+ f.run({ type: 'message.send', conversationId: 'lead', text: 'hello', replyTo: null, recipientIds: [] })
+ expect(f.line()).toBeUndefined()
+ })
+
+ it('keeps a line\'s time while it says the same, and moves it when it changes', () => {
+ const f = cardFixture()
+ const first = f.line()!.since
+ f.tick(60_000)
+ f.run({ type: 'message.send', conversationId: f.task, text: 'Halfway.', replyTo: null, recipientIds: [] }, f.as(f.dev))
+ f.work('working', 'Tests written')
+ expect(f.line()!.since).toBe(first)
+ f.tick(60_000)
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ expect(f.line()!.since).toBe(first! + 120_000)
+ })
+
+ it('shows readers the lines and the PM\'s extra text, in the card\'s own text', () => {
+ const f = cardFixture()
+ expect(f.text()).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules. Since 00:00 UTC.')
+ f.run({ type: 'project.report', projectId: 'lead', through: {}, text: 'Freeze starts Friday.' }, f.as(f.lead))
+ expect(f.text()).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules. Since 00:00 UTC.\nFreeze starts Friday.')
+ // A change of the lines does not lose it.
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ expect(f.text()).toContain('Freeze starts Friday.')
+ expect(f.text()).toContain('in review (PR #7)')
+ // Without text the report leaves the extra lines as they are.
+ f.run({ type: 'project.report', projectId: 'lead', through: {}, text: null }, f.as(f.lead))
+ expect(f.text()).toContain('Freeze starts Friday.')
+ })
+
+ it('does not show a card saved before the server wrote it beside the server\'s lines', () => {
+ const f = cardFixture()
+ // The coordinator's whole card of an earlier release: stored with no mark that it is its own lines.
+ projectOf(f.state, 'lead').status = { text: 'Old whole card: #1 Fix login working.', at: new Date(0).toISOString(), by: f.lead }
+ f.run({ type: 'message.send', conversationId: 'lead', text: 'tick', replyTo: null, recipientIds: [] })
+ expect(f.text()).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules. Since 00:00 UTC.')
+ // Its next report is its own lines.
+ f.run({ type: 'project.report', projectId: 'lead', through: {}, text: 'Freeze starts Friday.' }, f.as(f.lead))
+ expect(f.text()!.endsWith('\nFreeze starts Friday.')).toBe(true)
+ expect(f.text()).not.toContain('Old whole card')
+ })
+
+ it('shows the same card when a read applies the reader\'s view twice', () => {
+ const f = cardFixture()
+ f.run({ type: 'project.report', projectId: 'lead', through: {}, text: 'Freeze starts Friday.' }, f.as(f.lead))
+ const once = visibleState(f.state, owner)
+ const twice = visibleState(once, owner)
+ expect(twice.projects!.find(p => p.id === 'lead')!.status!.text).toBe(once.projects!.find(p => p.id === 'lead')!.status!.text)
+ expect(twice.projects!.find(p => p.id === 'lead')!.status!.text).toContain('Freeze starts Friday.')
+ })
+
+ // Task #4419: the card on the project chat made every task-changing command write the chat, so the next one read it whole,
+ // 6-7 KB over #4368's budgets. Each task keeps its own line; a command writes only the lines that changed.
+ it('keeps each task\'s line on the task, writes only a changed one, and never a card on the project chat', () => {
+ const f = cardFixture()
+ const second = f.run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits.', checks: [{ description: 'Saves', independent: true }],
+ priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string
+ expect(f.group(f.task).statusLine).toEqual({ text: '#1 "Fix login": working. Waits on: nothing. Owner: Jules.', since: expect.any(Number) })
+ const kept = f.group(second).statusLine
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ expect(f.group(f.task).statusLine!.text).toContain('in review (PR #7)')
+ expect(f.group(second).statusLine).toEqual(kept)
+ expect(f.chat()).not.toHaveProperty('card')
+ })
+
+ // Tasks stored before #4419 keep no line: the first command after the release must not write every one of them (prod's busiest
+ // project has ~180 open, one transaction), so a line is written only by a command that moves it, and the card builds the rest.
+ it('writes no line for a task stored without one that a command does not move, and still shows it on the card', () => {
+ const f = cardFixture()
+ delete f.group(f.task).statusLine
+ f.run({ type: 'message.send', conversationId: 'lead', text: 'tick', replyTo: null, recipientIds: [] })
+ expect(f.group(f.task).statusLine).toBeUndefined()
+ expect(f.text()).toBe('#1 "Fix login": working. Waits on: nothing. Owner: Jules.')
+ // The command that moves it writes it.
+ f.work('review', `Ready for review: ${PR} at abc1234`)
+ expect(f.group(f.task).statusLine).toEqual({ text: '#1 "Fix login": in review (PR #7). Waits on: a review. Owner: Jules.', since: expect.any(Number) })
+ })
+
+ it('leaves an ended task\'s line empty, dated, so a reader learns the card dropped it', () => {
+ const f = cardFixture()
+ f.tick(60_000)
+ f.work('done', 'Shipped without a pull request.')
+ expect(f.line()).toBeUndefined()
+ expect(f.group(f.task).statusLine).toEqual({ text: '', since: expect.any(Number) })
+ })
+
+ it('keeps the card within its limit, naming how many tasks the last line leaves out', () => {
+ const lines = Array.from({ length: 200 }, (_, i) => ({ id: `t${i}`, text: `#${i} "A task with a title that takes room": working. Waits on: nothing. Owner: Jules.`, since: 0 }))
+ const text = cardText(lines, 'Extra line.')
+ expect(text.length).toBeLessThanOrEqual(PROJECT_STATUS_MAX)
+ expect(text).toContain('Extra line.')
+ expect(text).toMatch(/\n\d+ more tasks\./)
+ })
+
+ it('reaches only those who read the project chat', () => {
+ const f = cardFixture()
+ const withoutChat = { ...f.state, conversations: f.state.conversations.filter(c => c.id !== 'lead') }
+ expect(visibleState(withoutChat, owner).projects?.find(p => p.id === 'lead')).not.toHaveProperty('status')
+ })
+})
diff --git a/backend/src/superTabs/statusCard.ts b/backend/src/superTabs/statusCard.ts
new file mode 100644
index 000000000..4f9e9df70
--- /dev/null
+++ b/backend/src/superTabs/statusCard.ts
@@ -0,0 +1,181 @@
+/**
+ * The project's status card, written by the server (task #3593, anh Dee 11-06, rules to code). The PM was woken every 15 minutes
+ * to reread task messages and rewrite one line per task: the largest steady token cost found. The state the lines say is
+ * already stored, so the server builds them: where each active task is, what it waits on, who owns it, and since when.
+ *
+ * Each task keeps its own line on its own part (task #4419): after each command, where every open group is loaded (pulse.ts
+ * recordPulse), a task's line is written only when its text changed. A card kept on the project chat (#3302) moved the chat's
+ * part with every line, and the next command read the chat whole: 6-7 KB over #4368's per-command budgets. Readers get the card
+ * built from the lines (projectCard, model.ts visibleState). The PM's own lines (project.report) follow them.
+ */
+import { agentDisplayName } from './agentNames.js'
+import { holdOf, pulseIndex, type PulseIndex } from './pulse.js'
+import { pullRequestLinks, type Conversation, type SuperTabState } from './model.js'
+import { groupRepositoryUrl, type SwarmProject } from './projects.js'
+import { stepName } from './steps.js'
+import { isBuddyChat } from './buddies.js'
+import { usernameOf } from './usernames.js'
+
+/** A task's own line as it keeps it (Conversation.statusLine): its text without its time, and when it last changed. An empty text
+ * is a task whose line left the card at `since`: a change poll tells a live reader so (read/changes.ts). */
+export interface StatusLine { text: string; since: number }
+/** One active task's line: `id` its conversation; no `since` for a task that keeps no line yet (projectCard). */
+export interface CardLine { id: string; text: string; since?: number }
+/** A project's card as readers get it (projectCard): the lines (at most CARD_LINES_MAX), how many more tasks were left out, the
+ * lines' text with their times, and when a line last changed. Built on read, never stored. */
+export interface StatusCard { lines: CardLine[]; more?: number; text: string; changedAt?: number }
+
+/** A growth bound on the card: far above the tasks a project has open at once. */
+export const CARD_LINES_MAX = 50
+const ENDED = new Set(['done', 'stopped', 'cancelled'])
+const DONE_STEP = new Set(['done', 'stopped', 'cancelled'])
+
+const pullRequest = (url: string): string => { const n = url.match(/\/pull\/(\d+)(?:[/?#]|$)/)?.[1]; return n ? `PR #${n}` : url }
+
+/** The steps of [task] that are not finished, by name: what a task in review or at work waits on. */
+function openSteps(state: SuperTabState, task: Conversation): string[] {
+ return (task.stepIds ?? []).flatMap(id => {
+ const step = state.conversations.find(c => c.id === id)
+ return step && !step.archived && !DONE_STEP.has(step.assignment?.status ?? '') ? [stepName(step)] : []
+ })
+}
+
+/** Whether a release still has to carry [task]'s merge: its entry on the project's list with a component not shipped. */
+function awaitingRelease(project: SwarmProject, task: Conversation): boolean {
+ return !!project.releases?.pending.some(e => e.groupId === task.id
+ && (e.components ? e.components.some(c => !e.shippedIn?.[c]) : !Object.keys(e.shippedIn ?? {}).length))
+}
+
+/** [task]'s line (no time), or none when its work ended and nothing of it waits. */
+function lineOf(state: SuperTabState, project: SwarmProject, task: Conversation, today: string): string | null {
+ const assignment = task.assignment
+ const merged = task.ledger?.mergedAt != null
+ const waiting = merged && awaitingRelease(project, task)
+ if (assignment && ENDED.has(assignment.status) && !waiting) return null
+ // A task its requester rejected never runs (taskApproval.ts, Swarm v3): it is no longer active work.
+ if (!assignment && task.taskApproval?.state === 'rejected') return null
+ const name = task.number !== undefined ? `#${task.number} ${JSON.stringify(task.title)}` : JSON.stringify(task.title)
+ const owner = assignment ? agentDisplayName(state.agents, assignment.agentId) ?? 'an agent that left' : 'none'
+ const steps = openSteps(state, task)
+ const stepsText = steps.length ? `${steps.length > 1 ? 'steps' : 'step'} ${steps.join(', ')}` : null
+ // Its linked pull requests, and those its builder's result names: the store links those right after the command (store.ts), so a
+ // line written by the command says them already, as the card built after says them.
+ const unlinked = new Set(task.unlinkedPullRequests?.map(entry => entry.url))
+ const prs = [...new Set([...task.pullRequestUrls ?? [],
+ ...pullRequestLinks(assignment?.result ?? '', groupRepositoryUrl(state, task)).filter(url => !unlinked.has(url))])]
+ const prText = prs.length ? ` (${prs.slice(-2).map(pullRequest).join(', ')})` : ''
+ let status: string, waits: string
+ if (merged && (waiting || !assignment || assignment.status !== 'done')) {
+ status = `merged${prText}`
+ waits = waiting ? 'the next release' : 'its builder to close it'
+ } else if (task.paused) {
+ // Paused by someone who steers the project (boardRights.ts): its worker stops at a safe point, whatever its status says.
+ status = 'paused'; waits = `a person to resume it${task.paused.reason ? ` (${task.paused.reason})` : ''}`
+ } else if (!assignment && task.taskApproval?.state === 'proposal') {
+ // No work starts before the requesting person approves it (taskApproval.ts, Swarm v3).
+ const asked = usernameOf(state, task.taskApproval.personId)
+ status = 'proposed'; waits = asked ? `@${asked}'s approval` : 'its requester\'s approval'
+ } else if (!assignment) {
+ const hold = holdOf(task, today)
+ status = hold ? 'held' : 'to do'
+ waits = hold ? hold.reason ?? 'a person\'s word' : 'an owner'
+ } else switch (assignment.status) {
+ case 'review': status = `in review${prText}`; waits = stepsText ?? 'a review'; break
+ case 'needs_human': {
+ const asked = assignment.askedOf && usernameOf(state, assignment.askedOf)
+ status = 'needs a person'; waits = asked ? `@${asked}` : 'a decision'; break
+ }
+ case 'blocked': status = 'blocked'; waits = 'the PM'; break
+ case 'lost': status = 'lost'; waits = 'another engineer'; break
+ case 'reconciling': status = 'stopping'; waits = 'its host'; break
+ case 'planned': status = 'to do'; waits = 'its builder to start'; break
+ default: status = 'working'; waits = stepsText ?? 'nothing'
+ }
+ return `${name}: ${status}. Waits on: ${waits}. Owner: ${owner}.`
+}
+
+const lineNow = (state: SuperTabState, project: SwarmProject, task: Conversation, today: string): string | null =>
+ task.dormant || task.archived ? null : lineOf(state, project, task, today)
+/** Each open task's line (null: none, its work ended) before a pass changes anything, by task: what noteTaskLines compares with. */
+export type LinesBefore = ReadonlyMap<string, string | null>
+
+/** The lines of [state]'s open tasks at [now] (of project [only], or every project): taken before a command or a sweep changes
+ * anything, so noteTaskLines writes only the lines that pass moved. */
+export function linesOf(state: SuperTabState, now: number, only?: string): LinesBefore {
+ const index = pulseIndex(state, undefined, only), today = new Date(now).toISOString().slice(0, 10), lines = new Map<string, string | null>()
+ for (const project of state.projects ?? []) for (const task of index.work.get(project.id) ?? []) {
+ if (!task.reviewOf) lines.set(task.id, lineNow(state, project, task, today))
+ }
+ return lines
+}
+
+/**
+ * Writes each of [project]'s open tasks' own line ([index], the pulse's: every open group loaded) where this pass moved it, dated
+ * [now]: its line in [before] is another, or it was not there (a task the command made). A task whose line ended keeps it empty,
+ * dated when it ended, so a reader learns the card dropped it. The text is only what the time goes with: the card builds every
+ * line from task state (projectCard). Comparing with each task's stored text instead would write every open task at once
+ * whenever those go stale (tasks stored before #4419, or a release that rewords the lines): ~200 parts in one transaction, and
+ * the Swarm answers busy.
+ */
+export function noteTaskLines(state: SuperTabState, project: SwarmProject, index: PulseIndex, now: number, today: string, before: LinesBefore): void {
+ for (const task of index.work.get(project.id) ?? []) {
+ if (task.reviewOf) continue
+ const text = lineNow(state, project, task, today)
+ const old = before.has(task.id) ? before.get(task.id)! : undefined
+ if (old === text || (old === undefined && text === null)) continue
+ task.statusLine = { text: text ?? '', since: now }
+ }
+}
+
+/** [project]'s card at [now], one line per active task by number, each built from task state: what readers get (model.ts
+ * visibleState). A line's time is the one its task keeps while that is for the same text; none otherwise (a task stored before
+ * #4419 and not moved since, or a line a release reworded). A task archived, dormant, a step or with an audience of its own is
+ * not on it. */
+export function projectCard(state: SuperTabState, project: SwarmProject, now: number): StatusCard {
+ const today = new Date(now).toISOString().slice(0, 10)
+ const lines: CardLine[] = state.conversations
+ .filter(task => (task.projectId ?? 'lead') === project.id && task.id !== project.leadConversationId
+ && !task.reviewOf && !task.kind && !task.audience && !isBuddyChat(task) && !task.archived && !task.dormant)
+ .sort((a, b) => (a.number ?? Infinity) - (b.number ?? Infinity))
+ .flatMap(task => {
+ const text = lineOf(state, project, task, today)
+ if (text === null) return []
+ return [{ id: task.id, text, ...task.statusLine?.text === text ? { since: task.statusLine.since } : {} }]
+ })
+ const kept = lines.slice(0, CARD_LINES_MAX), more = lines.length - kept.length
+ const times = kept.flatMap(line => line.since === undefined ? [] : [line.since])
+ const changedAt = times.length ? Math.max(...times) : undefined
+ return { lines: kept, ...(more ? { more } : {}), text: cardText(kept, null, more), ...(changedAt !== undefined ? { changedAt } : {}) }
+}
+
+const clock = (at: number): string => new Date(at).toISOString().slice(11, 16)
+
+/** The card readers see: each line with its time, then the PM's own lines. When the lines do not all fit in LINES_ROOM, the last line says
+ * how many tasks it leaves out. */
+export function cardText(lines: readonly CardLine[], extra?: string | null, more = 0): string {
+ return withExtra(linesText(lines, more), extra)
+}
+
+/** The coordinator's own lines after the card's lines, at most EXTRA_ROOM of them. The whole card is at most PROJECT_STATUS_MAX. */
+export function withExtra(text: string, extra?: string | null): string {
+ const own = extra ? extra.slice(0, EXTRA_ROOM) : ''
+ return own ? (text ? `${text}\n${own}` : own) : text
+}
+
+/** What the lines take of the card: LINES_ROOM, the rest being the coordinator's. */
+const LINES_ROOM = 1_500
+const EXTRA_ROOM = 500
+
+function linesText(lines: readonly CardLine[], more: number): string {
+ const shown: string[] = []
+ let used = 0
+ for (const line of lines) {
+ const text = line.since === undefined ? line.text : `${line.text} Since ${clock(line.since)} UTC.`
+ // Keep room for the "N more tasks." line, which is at most this long.
+ if (used + text.length + 1 + 24 > LINES_ROOM) break
+ shown.push(text)
+ used += text.length + 1
+ }
+ const left = lines.length - shown.length + more
+ return [...shown, ...(left ? [`${left} more tasks.`] : [])].join('\n')
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index a8e8dee02..f4deebf17 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -72,7 +72,7 @@ import { SEED_RULES, seedRules, validMachineRules, type MachineRule, type Projec
import { coordinatorNameOf, FIRST_INSTRUCTIONS, FIRST_SUMMARY, liveNotes, MAX_REVISIONS } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'
-import { answersRequest, dirtyGroups, noteWorkChanges, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'
+import { answersRequest } from './projectUpdates.js'
import { cloneData } from './cloneData.js'
import { digestDue, digestMessageId, digestOf, digestRequest, digestSince } from './digest.js'
import { moveChatMark } from './read/threadMarkSeeds.js'
@@ -2301,10 +2301,8 @@ export class SuperTabStore {
await this.endDeliveries(tx, tabId, { matches: row => removedGroups.some(c => c.id === row.conversationId) }, () => tx.superTabDelivery.updateMany({ where: { tabId, conversationId: { in: removedGroups.map(c => c.id) },
status: { in: [...CANCELLABLE_DELIVERY] } }, data: { status: 'cancelled', holdReason: null, holdSince: null } }))
}
- // Each conversation numbers its own messages. Only a change of a work group's state wakes its coordinator, read through
- // its latest message; an ordinary message never does (Dee, 2026-10-31).
+ // Each conversation numbers its own messages.
const sequences = numberMessages(effects.state, effects.messages, context.now)
- noteWorkChanges(original, effects.state, context.now)
if (command.type === 'work.assign' || command.type === 'work.status' || command.type === 'message.send') {
const group = conversation(effects.state, command.conversationId)
const assignment = group.assignment
@@ -4801,7 +4799,7 @@ export class SuperTabStore {
}
private async fullDeliveries(user: AuthUser, tabId: string, agentId: string, view: CacheView, turn?: 'idle' | 'busy') {
- // Every write below is the Lead's: its time checks, idle stops, update request, digest and stale runs. Any other agent's
+ // Every write below is the Lead's: its time checks, idle stops, digest and stale runs. Any other agent's
// poll only reads, through the read cache with no transaction (Diego's review of 10-28, item 1: 20 workers were 40
// whole-Swarm loads, clones and empty commits a minute). The authority checks are the same; a claim checks them again.
const read = await this.readLoad(user, tabId, {}, view)
@@ -4853,29 +4851,8 @@ export class SuperTabStore {
const target = agent(state, agentId)
// The time checks and idle notices run in the backend worker (runTimeChecks), so they go on while this poll does not.
const written: MessageDraft[] = []
- // Before the update request, which may carry them. Same rules as a listed delivery; a refused row ends as a refused one does.
+ // Same rules as a listed delivery; a refused row ends as a refused one does.
const { notices, refused } = await this.releasableNotices(tx, state, target, release)
- const update = projectUpdateRequest(state, target, this.now())
- let woken = false
- if (update) {
- const progress = groupProject(state, conversation(state, update.conversationId)).progress!
- const received = this.now() - (progress.requestedAt ?? 0) < UNANSWERED_REQUEST_MS ? ['delivered'] : []
- const pending = progress.requestMessageId
- ? await tx.superTabDelivery.findFirst({ where: { tabId, agentId, messageId: progress.requestMessageId,
- status: { in: ['queued', 'claimed', 'uncertain', ...received] } } })
- : null
- if (!pending) {
- progress.requested = { ...progress.requested, ...update.source!.through as Record<string, number> }
- progress.requestedAt = this.now()
- progress.requestMessageId = update.id
- written.push(update)
- woken = true
- }
- }
- // Whether this poll's update request is new, so lines may go into it: one already stored keeps its row as it is, with
- // none of them (writeMessages keepStored). Read once, for the digest and the schedule both.
- let updateFresh: boolean | undefined
- const updateOpen = async () => woken && (updateFresh ??= !await tx.superTabMessage.findUnique({ where: { id: update!.id }, select: { id: true } }))
let digestDraft: MessageDraft | undefined
if (notices.length) {
// After this page's cancels, before its rows are marked: all that remain, less what this digest names.
@@ -4883,42 +4860,34 @@ export class SuperTabStore {
const lines = (section: InboxSection) => notices.filter(n => n.section === section).map(n => n.line)
const text = digestText(notices[0]!.delivery.createdAt, lines('results'), more, notices.some(n => n.otherAccount),
led ? owedLines(state, projectOf(state, led.id), this.now()) : [], { people: lines('people'), crew: lines('crew') })
- // One message when an update request goes in this poll: the PM gets one turn, not two. Never into one already stored: its row
- // would be kept as it is, with no lines, or fail the poll (writeMessages keepStored).
- const merged = await updateOpen()
- if (merged) {
- update!.text = `${update!.text}\n\n${text}`
- update!.source = { ...update!.source, notices: notices.length }
- } else {
- digestDraft = digestMessage(agentId, gathered[0]!.id, projectOf(state, led!.id).leadConversationId, author(state, { kind: 'agent', agentId, machineOwnerId: target.machineOwnerId }), text, notices.length)
- written.push(digestDraft)
- }
+ digestDraft = digestMessage(agentId, gathered[0]!.id, projectOf(state, led!.id).leadConversationId, author(state, { kind: 'agent', agentId, machineOwnerId: target.machineOwnerId }), text, notices.length)
+ written.push(digestDraft)
// By status too: two polls racing digest each row once. One by one: no `in` on this hot collection (hotFilters).
for (const { delivery } of notices) await tx.superTabDelivery.updateMany({ where: { id: delivery.id, tabId, status: 'gathered' }, data: { status: 'digested' } })
- afterCommit(tx, () => logger.info('[swarm-deliveries] notice digest', { tabId, count: notices.length, cancelled: refused, more, length: text.length, merged }))
+ afterCommit(tx, () => logger.info('[swarm-deliveries] notice digest', { tabId, count: notices.length, cancelled: refused, more, length: text.length }))
} else if (refused) {
// Every row of the page refused: no digest, and still seen.
afterCommit(tx, () => logger.info('[swarm-deliveries] notice digest', { tabId, count: 0, cancelled: refused }))
}
// The built-in schedule (pmSchedule.ts), only when one of its jobs is due: its slot is recorded in this same write,
- // woken or held back, so two racing polls wake the coordinator once. Its lines go into the update request, else the notice
- // digest, so the PM gets one turn; none while its last wake is still unread, so a PM deep in a long turn finds one, not one
+ // woken or held back, so two racing polls wake the coordinator once. Its lines go into the notice digest when there is one,
+ // so the PM gets one turn; none while its last wake is still unread, so a PM deep in a long turn finds one, not one
// per slot.
const scheduled = led ? scheduleRequest(state, target, this.now()) : null
if (scheduled) {
const project = projectOf(state, led!.id)
let wakeId = project.schedule?.wakeId
- let placed: 'update' | 'digest' | 'own' | 'skipped-open'
+ let placed: 'digest' | 'own' | 'skipped-open'
// The message that carried the last wake, by its delivery's primary key (writeMessages: one row per message and
// recipient): still unread is queued, claimed or uncertain.
const last = wakeId ? await tx.superTabDelivery.findUnique({ where: { id: stableId(wakeId, agentId) }, select: { status: true } }) : null
const open = !!last && ['queued', 'claimed', 'uncertain'].includes(last.status)
- const into = open ? null : await updateOpen() ? update! : digestDraft ?? null
+ const into = open ? null : digestDraft ?? null
if (open) placed = 'skipped-open'
else if (into) {
into.text = `${into.text}\n\n${scheduled.draft.text}`
into.source = { ...into.source, schedule: scheduled.slot }
- placed = into === digestDraft ? 'digest' : 'update'
+ placed = 'digest'
wakeId = into.id
} else {
written.push(scheduled.draft)
@@ -4956,8 +4925,7 @@ export class SuperTabStore {
// One write for all: the time checks' changes, the digest and the wake-ups'.
const sequences = numberMessages(state, written, this.now())
// A loss or a start's failure was judged from a machine's report: a newer report makes this write retry.
- await this.save(tx, loaded, state, clock.next(), [...judgedMachines(loaded.state, state, written),
- ...woken ? [{ kind: 'agent' as const, key: agentId }] : []])
+ await this.save(tx, loaded, state, clock.next(), judgedMachines(loaded.state, state, written))
await this.writeMessages(tx, tabId, state, written, sequences, true)
return this.allowedDeliveries(tx, state, tabId, agentId)
})
@@ -5788,7 +5756,7 @@ export class SuperTabStore {
// A step this pass cancelled hears why, as when a command ends it (commands.ts endStepsOf): its later verdict is refused.
const rows = [...line ? [line] : [], ...stepEndedRows(state, cancelled, reason, line?.author ?? null, step => stableId('auto-archive-step', step.id, String(now)))]
const sequences = numberMessages(state, rows, now)
- if (!dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
+ group.dormant = true
// As a person's archive does (execute): a claim of a delivery here conflicts with this write.
// Its finished steps archive here too (execute does the same): a cancelled one stays open, to hear why. One plain match per
// conversation: an `in` on this hot collection is sent as $expr, which no index bounds (hotFilters).
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index d86ae185e..8c436d9bd 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -1,7 +1,7 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import type { AgentStart, Conversation } from './model.js'
import { stepSleeps } from './steps.js'
-import { clock, guardedWrite, PartConflict, type HeadData, type ProgressData } from './parts/index.js'
+import { clock, guardedWrite, PartConflict, type HeadData } from './parts/index.js'
import { DORMANT_AFTER_MS, RETENTION_MS } from './parts/types.js'
import { deletedSwarms } from './deletion.js'
import { logger } from '../utils/logger.js'
@@ -69,14 +69,13 @@ async function guarded(db: PrismaClient, write: Parameters<typeof guardedWrite>[
/**
* A conversation leaves the active set (spec, Archive) when its work is done or cancelled and it has had no message for a
- * day, or when it was archived by hand, and in both cases only once its Lead acknowledged its reports: a dormant
- * conversation is never read by ordinary loads, so it must owe its project nothing (design section 3.6). A project's
+ * day, or when it was archived by hand. Nothing waits on the Lead's report: the server writes the status card (task #3593). A project's
* Lead conversation and the Leads conversation never sleep; a message wakes any of them. Candidates are read oldest
* first with a cursor, so rejected ones never hold later ones back.
*/
async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number> {
const base = { deleted: false, dormant: false, kind: null, OR: [{ lastActivityAt: { lt: new Date(now - DORMANT_AFTER_MS) } }, { archived: true }] }
- const leads = new Map<string, Set<string>>(), progress = new Map<string, ProgressData | null>()
+ const leads = new Map<string, Set<string>>()
const leadsOf = async (tabId: string) => {
if (!leads.has(tabId)) {
const head = await db.swarmHead.findUnique({ where: { id: `${tabId}:head` } })
@@ -85,11 +84,6 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>
}
return leads.get(tabId)!
}
- const progressOf = async (tabId: string, projectId: string) => {
- const id = `${tabId}:${projectId}`
- if (!progress.has(id)) progress.set(id, ((await db.swarmProgress.findUnique({ where: { id } }))?.data as unknown as ProgressData | undefined) ?? null)
- return progress.get(id)!
- }
const tasks = new Map<string, { archived: boolean; dormant: boolean } | null>()
const taskOf = async (tabId: string, key: string) => {
const id = `${tabId}:${key}`
@@ -110,8 +104,6 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>
if ((await leadsOf(row.tabId)).has(group.id)) continue
// A step sleeps with its task (task steps design): read once per task in this pass.
if (group.reviewOf && !stepSleeps(await taskOf(row.tabId, group.reviewOf))) continue
- const reports = group.audience ? null : await progressOf(row.tabId, group.projectId ?? 'lead')
- if (reports && (group.reportSeq ?? 0) > (reports.summarized[group.id] ?? reports.summarizedFloor)) continue
if (await guarded(db, { tabId: row.tabId, op: 'update', kind: 'group', key: row.key, seen: row.version, data: { ...group, dormant: true } })) slept++
}
if (rows.length < BATCH) return slept
diff --git a/docs/plans/2026-11-06-server-status-card-plan.md b/docs/plans/2026-11-06-server-status-card-plan.md
new file mode 100644
index 000000000..f92785887
--- /dev/null
+++ b/docs/plans/2026-11-06-server-status-card-plan.md
@@ -0,0 +1,50 @@
+# The server writes the status card from task state: plan (task #3593)
+
+> Way of working: the Engineer implements this plan task by task, test first (project instructions, Engineer). No Execution Handoff.
+
+**Goal:** The project's status card is built by the server from task, step, pull request and release state, one line per active task (where it is, what it waits on, owner, time). The PM is no longer woken every 15 minutes to reread task messages and rewrite it. `project.report` stays for the PM's extra lines only.
+
+**Architecture:** Mirror `pulse.ts`. `recordPulse` already runs after every command where every open group is loaded, and writes only on a change, onto the project's chat part (not the head). A new `statusCard.ts` builds the card's lines and `recordPulse` keeps them on the chat as `card`. `visibleState` shows readers `status.text` = the generated lines plus the PM's extra text, so no client changes. The wake-up (`projectUpdateRequest`, the dirty marking in `noteWorkChanges`) is removed.
+
+**Tech Stack:** TypeScript, vitest, `backend/src/superTabs/`.
+
+**Spec:** anh Dee 11-06, Inventory Table A #2 (rules to code). Acceptance: the card has one line per active task with state, last change, what it waits on, owner and time, with no PM call; no card wake-up is sent to the PM.
+
+## Global Constraints
+- Swarm code stays out of cli/src/core. No new client contract: `status.text` keeps its meaning (the whole card, at most 2,000 characters).
+- A card is written only when its text changes; a progress note, a message or a terminal turn changes no line.
+- A project.report with `through` and `text` still works (older PM hosts): it acknowledges and sets the PM's extra text.
+
+## Review Focus
+- The sleep sweep and archive still work with nothing marked dirty (`sweeps.ts`, `commands.ts` archive).
+- A task's "since" is the time its line last changed, kept by the card, not a message's time.
+- The PM's extra text survives a regenerated card and is bounded.
+- Readers who cannot read the project chat never get the card or its lines.
+
+## Design
+- growth: one line per active task, at most 50 lines and 2,000 characters; a task's line leaves when it ends. The card lives on the project chat part.
+- concurrency: the chat part only, as the pulse; no head write per task move.
+- read cost: computed after a command from the loaded groups, written only on a change; reads get the stored lines.
+- scale: 10x tasks is the 50-line cap; the metric is the card's truncation count (`more` in the last line).
+- compatibility: old clients read `status.text` as before; an old PM host's `project.report` still works; stored `dirty` progress is ignored.
+- migration + rollback: none to run; the card appears at the next command of each project. Rollback restores the wake-up code; stored cards are ignored.
+- audience: the server enforces it in `visibleState` (the card goes only to readers of the project chat).
+- identity: no login is read; owners are agent display names.
+- failure: a card that cannot be built leaves the last one; nothing else fails.
+- platforms: N/A, server text.
+
+### Task 1: build the card lines (`statusCard.ts`)
+**Files:** create `backend/src/superTabs/statusCard.ts`, `statusCard.test.ts`.
+**Interfaces:** `cardLines(state, project, index, previous, now): CardLine[]` with `CardLine = { id, text, since }`; `cardText(lines, extra): string`.
+- [ ] Failing tests: a line per active task with state, what it waits on, owner; steps and merged PRs shown; ended tasks gone; `since` kept while the text is unchanged and moved when it changes; cap.
+- [ ] Code.
+
+### Task 2: keep it on the chat and show it
+**Files:** `pulse.ts` (recordPulse), `model.ts` (Conversation.card, visibleState), `parts/light.ts` (field list), `commands.ts` (project.report keeps `extra`).
+- [ ] Failing tests: the card is on the chat after a command, changes only with a line; readers get `status.text`; the PM's extra text is appended; a reader without the chat gets none.
+- [ ] Code.
+
+### Task 3: stop the wake-up
+**Files:** `projectUpdates.ts`, `store.ts`, `projectStatus.test.ts`.
+- [ ] Failing tests: no update request is ever made, however the work changes; a group archived goes dormant.
+- [ ] Code: remove the dirty marking and `projectUpdateRequest` with its store wiring; keep `summarize` for older hosts.
diff --git a/docs/plans/2026-11-07-status-card-budget-plan.md b/docs/plans/2026-11-07-status-card-budget-plan.md
new file mode 100644
index 000000000..eec8b1bf0
--- /dev/null
+++ b/docs/plans/2026-11-07-status-card-budget-plan.md
@@ -0,0 +1,56 @@
+# The server writes the status card within each command's read budget: implementation plan
+
+> This plan is carried out by the project's Engineer way of working (test first, task by task, one pull request), not
+> subagent-driven-development. There is no execution handoff.
+
+**Goal:** Keep #3302's server-written status card (task #3593) and fit #4368's per-command read budgets, unchanged. This is
+task #4419.
+
+**Architecture:** #3302 kept the whole card on the project chat's part and rewrote it whenever a line changed. Each write
+moved the chat's version, so the next command read the chat whole again: 6–7 KB over budget on conversation.create,
+work.assign, work.status and the dispatch pass.
+
+Now each task keeps its own line on its own part, as `statusLine: { text, since }`. After a command, only a task whose
+line changed is written. A task that ends keeps an empty, dated line, so a reader learns its line left the card. The
+command that changes a line usually writes that task anyway.
+
+Readers get the card put together from the tasks' lines, in the project's `status` text, as before (`visibleState`). A
+change poll sends the head only with a task whose line moved since the reader's cursor (`read/changes.ts`), as #3302
+did for the chat's card.
+
+**Tech Stack:** TypeScript backend, vitest.
+
+**Spec:** Task #4419's brief; #3302's plan (`docs/plans/2026-11-06-server-status-card-plan.md`).
+
+## Global Constraints
+
+- Backend only. No read budget is raised: #4368's tests pass unchanged.
+- Old clients still read the card in `status.text`.
+- Audience unchanged: the card goes only to readers of the project chat, and it holds only tasks that have no audience
+ of their own.
+
+## Review Focus
+
+- A task that ends, is archived, or goes dormant drops off the card, and live readers see it drop.
+- A message, progress note or terminal turn moves no line, so the task isn't written for the card.
+- A card stored by #3302 on a chat is never read.
+
+---
+
+### Task 1: Each task keeps its own line
+
+**Files:** `statusCard.ts`, `pulse.ts`, `model.ts`, `parts/light.ts`, `read/views.ts`, `read/changes.ts`, and their tests.
+
+**Interfaces:**
+- `noteTaskLines(state, project, now, today): void` writes `statusLine` on the tasks whose line changed.
+- `projectCard(state, project): StatusCard` builds the lines from the tasks.
+
+- [ ] **Step 1: Failing tests.**
+ - #3302's card tests, read from the tasks' lines.
+ - A command writes only the changed task's line, and never a card on the chat.
+ - An ended task's line is empty and dated.
+ - The change feed sends the head for a moved line, and not for a task change that left its line as it was.
+ - #4368's budgets fail unchanged at the merge of main.
+- [ ] **Step 2: Implement.**
+- [ ] **Step 3: Run** those tests and `integration/superTabCommandReads.test.ts`, `superTabRead.test.ts`, `superTabs.test.ts`.
+ Expected: PASS.