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.

feat(swarm): the morning digest lists the decisions waiting, by conversation and person (#1772)

0xken15ceb1ec28b2d7
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index b89732245..0f84d511b 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -564,6 +564,56 @@ describe('the delivery poll of an agent with nothing waiting', () => {
})
describe('the morning digest', () => {
+ // #1772 review: every open decision counts, however many there are, and private ones never crowd out shared ones.
+ it('counts every decision waiting, past 200, and is not crowded out by newer private ones', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ const secret = String((await f.execute({ type: 'conversation.create', title: 'Salaries', brief: '', checks: [], audience: { personIds: [owner.sub] } } as Command)).result.conversationId)
+ const asked = (conversationId: string, count: number, from: number) => Array.from({ length: count }, (_, i) => ({ id: randomUUID(), tabId: f.tab,
+ batchId: 'batch', projectId, conversationId, assignmentId: null, personId: owner.sub, askerAgentId: f.lead, question: `Question ${i}?`,
+ options: ['Yes', 'No'], recommended: 0, unblocks: 'Work', createdAt: new Date(from + i) }))
+ const digestText = async () => {
+ f.clock.now += 24 * 60 * 60_000
+ await f.leadInbox()
+ return (await db.superTabMessage.findMany({ where: { tabId: f.tab }, orderBy: { sequence: 'desc' } })).find(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')!.text
+ }
+ // One shared decision, older than 200 private ones.
+ await db.superTabDecision.createMany({ data: [...asked(f.group, 1, 1_000), ...asked(secret, 200, 5_000)] })
+ f.clock.now = 3 * 60 * 60_000 - 24 * 60 * 60_000
+ expect(await digestText()).toMatch(/\nDecisions waiting:\n- #1 Ship the parser: 1 for owner@example\.com$/)
+ await db.superTabDecision.createMany({ data: asked(f.group, 200, 10_000) })
+ expect(await digestText()).toMatch(/\nDecisions waiting:\n- #1 Ship the parser: 201 for owner@example\.com$/)
+ })
+
+ it('lists a decision still waiting in a conversation that has gone quiet', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ await f.execute({ type: 'decision.ask', conversationId: f.group, personId: owner.sub,
+ questions: [{ question: 'Keep the old parser?', options: ['Keep it', 'Drop it'], recommended: 1, unblocks: 'The cleanup' }] }, host, f.lead)
+ // Ordinary loads no longer read it (sweeps.ts puts quiet conversations to sleep), and it has been quiet since before the
+ // digest's day, so nothing it shipped brings it back.
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: f.group }, data: { dormant: true, lastActivityAt: new Date(0) } })
+ f.clock.now = 3 * 60 * 60_000 + 2 * 24 * 60 * 60_000
+ await f.leadInbox()
+ const digest = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).find(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')!
+ expect(digest.text).toMatch(/\nDecisions waiting:\n- #1 Ship the parser: 1 for owner@example\.com$/)
+ })
+
+ it('lists the decisions waiting, by conversation and person, never their questions', async () => {
+ const f = await swarm()
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ const question = (text: string) => ({ question: text, options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' })
+ await f.execute({ type: 'decision.ask', conversationId: f.group, personId: owner.sub, questions: [question('Secret launch plan?'), question('Price it?')] }, host, f.lead)
+ f.clock.now = 3 * 60 * 60_000
+ await f.leadInbox()
+ const digest = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).find(m => (m.source as { kind?: string } | null)?.kind === 'digest-request')!
+ expect(digest.text).toMatch(/\nDecisions waiting:\n- #1 Ship the parser: 2 for owner@example\.com$/)
+ expect(digest.text).not.toMatch(/Secret launch plan|Price it|Behind a flag/)
+ })
+
it('is sent once when two of the Lead\'s polls run at the same moment', async () => {
const f = await swarm()
const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.ts
index be62c5c6e..93936c223 100644
--- a/backend/src/superTabs/decisions.ts
+++ b/backend/src/superTabs/decisions.ts
@@ -140,6 +140,14 @@ async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Acto
})
}
+/** How many of a project's open decisions wait in each conversation for each person, for its digest (digest.ts
+ * decisionLines): never what they ask. Counted by the database, so every one counts, however many there are, and private
+ * ones filtered out later never crowd out shared ones (review of #1772). */
+export async function waitingInProject(tx: Tx, tabId: string, projectId: string): Promise<Array<{ conversationId: string; personId: string; count: number }>> {
+ const groups = await tx.superTabDecision.groupBy({ by: ['conversationId', 'personId'], where: { tabId, projectId, ...waiting }, _count: { _all: true } })
+ return groups.map(g => ({ conversationId: g.conversationId, personId: g.personId, count: g._count._all }))
+}
+
export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>): Promise<number> {
return (await readable(tx, tabId, state, actor, true)).length
}
diff --git a/backend/src/superTabs/digest.test.ts b/backend/src/superTabs/digest.test.ts
index fa56f2e54..01dd4ee60 100644
--- a/backend/src/superTabs/digest.test.ts
+++ b/backend/src/superTabs/digest.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { Agent, Assignment, Conversation, SuperTabState, WorkStatus } from './model.js'
-import { digestDue, digestRequest, projectDigest } from './digest.js'
+import { decisionLines, digestDue, digestRequest, projectDigest } from './digest.js'
const HOUR = 60 * 60_000
/** 08:00 on 27 October in Vietnam (UTC+7), the project's digest time. */
@@ -20,7 +20,7 @@ const group = (number: number, title: string, assignment: Assignment | null, ove
function fixture(): SuperTabState {
return {
version: 1, id: 'tab', name: 'Swarm', ownerId: 'owner', environment: 'prod', paused: false, invitations: [],
- people: [{ id: 'owner', email: '[email protected]', role: 'owner', generation: 'g' }] as SuperTabState['people'],
+ people: [{ id: 'owner', email: '[email protected]', role: 'owner', generation: 'g' }, { id: 'ann', email: '[email protected]', role: 'collaborator', generation: 'g' }] as SuperTabState['people'],
agents: [agent('lead', 'Lead'), agent('nico', 'Nico'), agent('ana', 'Ana'), agent('bo', 'Bo'), agent('cy', 'Cy'), agent('di', 'Di'), agent('ed', 'Ed')],
projects: [
{ id: 'p1', name: 'lampOS', ownerId: 'owner', leadConversationId: 'lead-p1', visibility: 'public', members: [], updateMinutes: 5,
@@ -41,6 +41,7 @@ function fixture(): SuperTabState {
// Merged and archived overnight: it still shipped (#1757 review, 4).
group(10, 'Release notes', work('bo', 'done'), { archived: true, dormant: true, pullRequestUrls: ['https://github.com/example/lampos/pull/15'] }),
group(9, 'Bootloader', work('nico', 'working'), { projectId: 'p2', leadId: 'lead-2' }),
+ group(11, 'Salaries', null, { audience: { people: [{ id: 'owner', generation: 'g' }] } as Conversation['audience'] }),
],
} as SuperTabState
}
@@ -63,10 +64,31 @@ describe('a project\'s morning digest', () => {
})
it('shows the decisions waiting only when there are some', () => {
- expect(projectDigest(fixture(), lampOS(fixture()), LAST, ['Ship the night shift to every Swarm?'])).toMatch(/\nDecisions waiting:\n- Ship the night shift to every Swarm\?$/)
+ expect(projectDigest(fixture(), lampOS(fixture()), LAST, ['- Ship the night shift to every Swarm?'])).toMatch(/\nDecisions waiting:\n- Ship the night shift to every Swarm\?$/)
expect(projectDigest(fixture(), lampOS(fixture()), LAST, [])).not.toContain('Decisions waiting')
})
+ // Decisions are read only by the person asked, the agent that asked and the Lead (decisions.ts readerWhere); the digest
+ // goes to the whole project, so it says where and whom, never what is asked, and nothing of a private conversation.
+ it('lists the decisions waiting by conversation and person, without their questions, from conversations the project reads', () => {
+ const state = fixture()
+ expect(decisionLines(state, lampOS(state), [{ conversationId: 'g7', personId: 'owner', count: 1 }, { conversationId: 'g7', personId: 'owner', count: 1 },
+ { conversationId: 'g3', personId: 'ann', count: 1 }, { conversationId: 'g7', personId: 'ann', count: 1 }, { conversationId: 'g11', personId: 'owner', count: 1 },
+ { conversationId: 'g9', personId: 'owner', count: 1 }, { conversationId: 'g3', personId: 'gone', count: 1 }, { conversationId: 'deleted', personId: 'owner', count: 1 },
+ { conversationId: 'lead-p1', personId: 'ann', count: 1 }])).toEqual([
+ '- This chat: 1 for [email protected]',
+ '- #3 Lexer: 1 for [email protected]',
+ '- #7 Pricing: 2 for [email protected], 1 for [email protected]',
+ ])
+ expect(decisionLines(state, lampOS(state), [])).toEqual([])
+ })
+
+ it('puts the decisions waiting in the Lead\'s digest wake-up only when there are some', () => {
+ const state = fixture(), lead = state.agents.find(a => a.id === 'lead')!
+ expect(digestRequest(state, lead, EIGHT, [{ conversationId: 'g7', personId: 'ann', count: 1 }])!.text).toMatch(/\nDecisions waiting:\n- #7 Pricing: 1 for ann@example\.com$/)
+ expect(digestRequest(state, lead, EIGHT, [])!.text).not.toContain('Decisions waiting')
+ })
+
it('says so when nothing moved', () => {
const state = fixture()
state.conversations = state.conversations.filter(c => !c.number || c.projectId !== 'p1')
diff --git a/backend/src/superTabs/digest.ts b/backend/src/superTabs/digest.ts
index 37771cc62..85c144a6f 100644
--- a/backend/src/superTabs/digest.ts
+++ b/backend/src/superTabs/digest.ts
@@ -1,6 +1,6 @@
import { activeWork, author, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
import { agentDisplayName } from './agentNames.js'
-import { ledProject, type SwarmProject } from './projects.js'
+import { canReadGroup, ledProject, type SwarmProject } from './projects.js'
import { reportGroups } from './projectUpdates.js'
// Night shift (v2 B): people wake to one message per project saying what the Swarm did overnight. At the project's local
@@ -61,13 +61,34 @@ export function projectDigest(state: SuperTabState, project: SwarmProject, since
const why = g.assignment!.status === 'lost' ? g.assignment!.lost?.reason : g.assignment!.result
return `- ${named(g)}: ${HELD_UP[g.assignment!.status]} (${who(g)})${why ? `: ${why.replace(/\s+/g, ' ').slice(0, 300)}` : ''}`
})
- const parts = [['Shipped', shipped], ['In progress', moving], ['Blocked', held], ['Decisions waiting', decisions.map(d => `- ${d}`)]] as const
+ const parts = [['Shipped', shipped], ['In progress', moving], ['Blocked', held], ['Decisions waiting', decisions]] as const
const text = parts.filter(([, lines]) => lines.length).map(([title, lines]) => [`${title}:`, ...lines].join('\n')).join('\n')
return text || 'Nothing shipped, in progress or blocked.'
}
+/**
+ * The decisions waiting in a project (`waiting`: how many per conversation and person), one line per conversation: how
+ * many wait for whom. Decisions are read only by the
+ * person asked, the agent that asked and the Lead (decisions.ts readerWhere), while the digest goes to the whole project,
+ * so it never says what is asked, and leaves out private conversations and people who no longer read the conversation.
+ */
+export function decisionLines(state: SuperTabState, project: SwarmProject, waiting: ReadonlyArray<{ conversationId: string; personId: string; count: number }>): string[] {
+ const chat = state.conversations.find(c => c.id === project.leadConversationId)
+ const groups = [...chat ? [chat] : [], ...reportGroups(state, project).filter(g => g.number !== undefined).sort((a, b) => a.number! - b.number!)]
+ const counts = new Map<string, Map<string, number>>()
+ for (const { conversationId, personId, count } of waiting) {
+ const group = groups.find(g => g.id === conversationId), asked = state.people.find(p => p.id === personId)
+ if (!group || !asked || !canReadGroup(state, { kind: 'person', userId: asked.id, email: asked.email }, group)) continue
+ const people = counts.get(group.id) ?? new Map<string, number>()
+ counts.set(group.id, people.set(asked.email, (people.get(asked.email) ?? 0) + count))
+ }
+ return groups.filter(g => counts.has(g.id)).map(g => `- ${g === chat ? 'This chat' : `#${g.number} ${g.title}`}: `
+ + [...counts.get(g.id)!].map(([email, n]) => `${n} for ${email}`).join(', '))
+}
+
/** The Lead's wake-up for its project's digest when one is due, or null. The caller records it as sent (store.ts). */
-export function digestRequest(state: SuperTabState, target: Agent, now: number): MessageDraft | null {
+export function digestRequest(state: SuperTabState, target: Agent, now: number,
+ waiting: ReadonlyArray<{ conversationId: string; personId: string; count: number }> = []): MessageDraft | null {
if (state.paused) return null
const project = ledProject(state, target.id)
const on = project && digestDue(project, now)
@@ -76,8 +97,7 @@ export function digestRequest(state: SuperTabState, target: Agent, now: number):
const text = `Morning digest for project ${JSON.stringify(project.name)} (${digest.time}, ${digest.timeZone}). This is a scheduled request, not a new task. `
+ 'Check that each pull request under Shipped is merged, and move one that is not to In progress. Then post one message to the people in this chat '
+ 'with these parts, in plain words, without commands or internal IDs.\n\n'
- // Decision packets (Echo's group) are not stored yet: until they are, the decisions part is left out.
- + projectDigest(state, project, digestSince(project, now))
+ + projectDigest(state, project, digestSince(project, now), decisionLines(state, project, waiting))
return { id: stableId('digest', state.id, project.id, on), conversationId: project.leadConversationId,
author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }),
text, replyTo: null, recipients: [target.id], source: { kind: 'digest-request', projectId: project.id, on } }
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 7ce4cfbef..80d4ffb83 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -33,7 +33,7 @@ import { accrueLent } from './leaderboard/lent.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, closeUnassignedStart, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
import { listMentions, markDone, mentionsWaiting, readMention, resolveByReply, writeMentions } from './mentions.js'
-import { answerable, listDecisions, readAskedDecision, recordAnswer, writeDecisions } from './decisions.js'
+import { answerable, listDecisions, readAskedDecision, recordAnswer, waitingInProject, writeDecisions } from './decisions.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'
import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,
saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'
@@ -1579,10 +1579,14 @@ export class SuperTabStore {
// Work finished since the last digest and archived or asleep since still shipped, but ordinary loads leave it out
// (#1757 review, 4): a due digest loads it.
const led = ledProject(loaded.state, agentId)
+ let asked: Array<{ conversationId: string; personId: string; count: number }> = []
if (led && digestDue(led, this.now())) {
const finished = await tx.swarmGroup.findMany({ where: { tabId, deleted: false, dormant: true, lastActivityAt: { gte: new Date(digestSince(led, this.now())) },
OR: [{ projectId: led.id }, ...led.id === 'lead' ? [{ projectId: null }] : []] }, select: { key: true } })
- if (finished.length) loaded = await this.ensure(tx, loaded, { groupIds: finished.map(g => g.key) })
+ // A decision waits in its conversation even once that conversation went quiet.
+ asked = await waitingInProject(tx, tabId, led.id)
+ const groupIds = [...new Set([...finished.map(g => g.key), ...asked.map(d => d.conversationId)])]
+ if (groupIds.length) loaded = await this.ensure(tx, loaded, { groupIds })
}
const state = structuredClone(loaded.state)
author(state, await this.actor(tx, user, state, agentId), true)
@@ -1606,7 +1610,7 @@ export class SuperTabStore {
}
}
// The morning digest is due once a day; recording it as sent is part of this same write, so it is sent once.
- const digest = digestRequest(state, target, this.now())
+ const digest = digestRequest(state, target, this.now(), asked)
if (digest) {
const project = projectOf(state, digest.source!.projectId as string)
project.digest = { ...project.digest!, lastOn: digest.source!.on as string, lastAt: this.now() }