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.

Hotfix: a POST command reads only the Swarm parts it touches (#4368) (#3497)

0xken15709a1ce5da10
diff --git a/backend/integration/superTabCommandReads.test.ts b/backend/integration/superTabCommandReads.test.ts
new file mode 100644
index 000000000..b56d842ad
--- /dev/null
+++ b/backend/integration/superTabCommandReads.test.ts
@@ -0,0 +1,166 @@
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { Prisma, PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'
+import { loadMachineAccounts } from '../src/superTabs/parts/index.js'
+import { filterOf, planDatabase, profiled } from './plans.test-support.js'
+import type { ProfileEntry } from './bench/profile.js'
+
+// Ken's prod scan, 09:20 VN 2026-11-07 (task #4368): a POST command read 28.2 queries and 1,156 KB, and the whole-Swarm reads
+// (every agent, machine, member, start and progress part) ran 1.4-1.5 times per command. A Swarm of prod's size here: 60
+// machines, 60 agents, 200 conversations, with the GitHub reads prod's store runs before a command.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '430000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const MACHINES = 60, OWN_MACHINES = 20, AGENTS = 60, GROUPS = 200
+
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('swarm_command_reads_test'))
+ await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: 'prod' } })
+ await db.machine.createMany({ data: Array.from({ length: MACHINES }, (_, i) => ({ machineId: `mac-${i}`, userId: owner.sub, apiKey: `fixture-reads-${i}`,
+ managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' })) })
+ await listNamedIndexes(db)
+}, 120_000)
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A prod-sized Swarm on a store with prod's GitHub reads, each answering at once. */
+async function swarm() {
+ const store = new SuperTabStore(db, Date.now, null, { pushOrigin: async () => 'clean', repositoryReach: async () => undefined,
+ pullRequestFiles: async () => null,
+ pullRequestReader: () => { throw new Error('No pull request is read here') } })
+ const tab = (await store.create(owner, randomUUID(), 'Reads', 'public')).id
+ const execute = (command: Command, asAgentId?: string) => store.execute(owner, tab, { operationId: randomUUID(), command }, asAgentId)
+ // One person adds at most 20 machines: the rest are copies of the first, as their own rows.
+ for (let i = 0; i < OWN_MACHINES; i++) {
+ await execute({ type: 'machine.contribute', machineId: `mac-${i}`, name: `Mac ${i}`, cwd: '/repo', engines: ['codex'], maxAgents: 8 })
+ }
+ const machine = await db.swarmMachine.findFirstOrThrow({ where: { tabId: tab, key: { startsWith: 'mac-0' } } })
+ const { id: _machineId, ...machineShape } = machine
+ await db.swarmMachine.createMany({ data: Array.from({ length: MACHINES - OWN_MACHINES }, (_, i) => {
+ const key = machine.key.replace('mac-0', `copy-mac-${i}`)
+ return { ...machineShape, id: `${tab}:${key}`, key, data: JSON.parse(JSON.stringify(machine.data).replaceAll('mac-0', `copy-mac-${i}`)) } as Prisma.SwarmMachineCreateManyInput
+ }) })
+ const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'mac-0', harnessId: randomUUID(), name: 'Lead',
+ configuration: config, lead: true })).result.agentId)
+ const agents: string[] = []
+ for (let i = 1; i < AGENTS; i++) {
+ agents.push(String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: `mac-${i % OWN_MACHINES}`, harnessId: randomUUID(), name: `Agent ${i}`,
+ configuration: config, lead: false })).result.agentId))
+ }
+ const task = async (title: string) => String((await execute({ type: 'conversation.create', title, checks: [],
+ task: { goal: `${title}.`, changes: 'The change.', constraints: 'None.', owns: ['backend/a.ts'] } })).result.conversationId)
+ const group = await task('Seed')
+ // The rest copied from it, as their own rows: a third of them dormant, as on prod.
+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: group } })
+ const { id: _id, ...shape } = part
+ const brief = 'Implement it. '.repeat(300)
+ const rows = Array.from({ length: GROUPS - 1 }, (_, i) => {
+ const key = `copy-${i}`, dormant = i % 3 === 0
+ return { ...shape, id: `${tab}:group:${key}`, key, dormant, data: { ...part.data as object, id: key, title: `Copy ${i}`, brief, ...dormant ? { dormant: true } : {} } } as Prisma.SwarmGroupCreateManyInput
+ })
+ await db.swarmGroup.createMany({ data: rows })
+ return { store, tab, execute, lead, agents, task }
+}
+
+/** A whole-Swarm read: a read of one of a Swarm's part collections that names no part and examines its documents. A listing
+ * served by an index alone examines none. */
+const PART_COLLECTIONS = ['SwarmAgent', 'SwarmMachine', 'SwarmMember', 'SwarmStart', 'SwarmProgress', 'SwarmGroup']
+const NAMES = ['_id', 'key', 'agentId', 'agentIds', 'projectId', 'executionMachineId', 'machineId', 'changedAt', 'readAt']
+function wholeReads(entries: ProfileEntry[]): Record<string, number> {
+ const out: Record<string, number> = {}
+ for (const entry of entries) {
+ const collection = entry.ns.slice(entry.ns.indexOf('.') + 1)
+ if (!PART_COLLECTIONS.includes(collection) || !['query', 'command'].includes(entry.op) || !entry.docsExamined) continue
+ const filter = JSON.stringify(filterOf(entry) ?? null)
+ if (!filter.includes('tabId') || NAMES.some(name => filter.includes(`"${name}"`) || filter.includes(`"$${name}"`))) continue
+ out[collection] = (out[collection] ?? 0) + 1
+ }
+ return out
+}
+/** What one command read: its queries, the KB Mongo sent back, and its whole-Swarm reads by collection. */
+const measured = (entries: ProfileEntry[]) => {
+ const reads = entries.filter(e => !e.ns.endsWith('.$cmd') && !e.ns.includes('system.') && ['query', 'command', 'getmore'].includes(e.op))
+ return { queries: reads.length, kb: Math.round(reads.reduce((n, e) => n + (e.responseLength ?? 0), 0) / 1024), whole: wholeReads(entries) }
+}
+
+/** Each command's most queries and KB on this store, a little above what it read (the PR's numbers). What is left is each
+ * kind's listing, ~110 bytes a part, and the parts the command wrote: on prod, parts are larger and more. */
+const BUDGET = {
+ 'conversation.create': { queries: 24, kb: 36 },
+ 'work.assign': { queries: 36, kb: 44 },
+ 'work.status': { queries: 22, kb: 36 },
+ 'work.status review': { queries: 36, kb: 52 },
+ 'post': { queries: 20, kb: 34 },
+ 'react': { queries: 22, kb: 34 },
+ 'dispatch pass': { queries: 12, kb: 32 },
+} as const
+
+describe('what a common command reads in a prod-sized Swarm (task #4368)', () => {
+ let s: Awaited<ReturnType<typeof swarm>>
+ let worker: string, conversationId = '', assignmentId = '', messageId = ''
+ const seen: Record<string, ReturnType<typeof measured>> = {}
+ const measure = async (name: keyof typeof BUDGET, run: () => Promise<unknown>) => {
+ seen[name] = measured(await profiled(db, run))
+ return seen[name]!
+ }
+ const within = (name: keyof typeof BUDGET) => {
+ const read = seen[name]!
+ expect({ name, whole: read.whole }).toEqual({ name, whole: {} })
+ expect(read.queries, `${name} queries`).toBeLessThanOrEqual(BUDGET[name].queries)
+ expect(read.kb, `${name} KB`).toBeLessThanOrEqual(BUDGET[name].kb)
+ }
+
+ beforeAll(async () => {
+ s = await swarm()
+ worker = s.agents[5]!
+ // Once, so this server has read the Swarm as a busy one has.
+ await s.task('Warm')
+ }, 300_000)
+ afterAll(() => { console.log(`[command reads] ${JSON.stringify(seen)}`) })
+
+ it('conversation.create', async () => {
+ await measure('conversation.create', async () => { conversationId = await s.task('Measured') })
+ within('conversation.create')
+ })
+ it('work.assign', async () => {
+ await measure('work.assign', () => s.execute({ type: 'work.assign', conversationId, agentId: worker }))
+ assignmentId = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: s.tab, key: conversationId } })).data as { assignment: { id: string } }).assignment.id
+ within('work.assign')
+ })
+ it('work.status', async () => {
+ await measure('work.status', () => s.execute({ type: 'work.status', conversationId, assignmentId, status: 'working', result: 'On it.' } as Command, worker))
+ within('work.status')
+ })
+ it('a post', async () => {
+ await measure('post', async () => { messageId = String((await s.execute({ type: 'message.send', conversationId, text: 'hello', replyTo: null, recipientIds: [] } as Command, worker)).result.messageId) })
+ within('post')
+ })
+ it('a reaction', async () => {
+ await measure('react', () => s.execute({ type: 'message.react', conversationId, messageId, emoji: 'eyes', on: true } as Command))
+ within('react')
+ })
+ it('a Ready, with its GitHub reads', async () => {
+ await measure('work.status review', () => s.execute({ type: 'work.status', conversationId, assignmentId, status: 'review',
+ result: 'Ready: https://github.com/example/repo/pull/1' } as Command, worker))
+ within('work.status review')
+ })
+ it('the dispatch pass a write schedules', async () => {
+ await measure('dispatch pass', () => s.store.dispatchCrew(s.tab))
+ within('dispatch pass')
+ })
+ // Its match names the Swarm and live rows as the held index does: read by `_id`, named, it examines one machine of 60.
+ it('an agent\'s machine account, read by id', async () => {
+ const { key } = await db.swarmMachine.findFirstOrThrow({ where: { tabId: s.tab, deleted: false } })
+ const machines = (await profiled(db, () => db.$transaction(tx => loadMachineAccounts(tx, s.tab, [key]))))
+ .filter(e => e.ns.endsWith('.SwarmMachine') && e.op !== 'getmore')
+ expect(machines.map(e => [e.planSummary, e.docsExamined])).toEqual([['IXSCAN { _id: 1 }', 1]])
+ })
+})
diff --git a/backend/integration/superTabHeldParts.test.ts b/backend/integration/superTabHeldParts.test.ts
index b8c7b14a5..51cbcb22d 100644
--- a/backend/integration/superTabHeldParts.test.ts
+++ b/backend/integration/superTabHeldParts.test.ts
@@ -61,8 +61,13 @@ async function write(tabId: string, pick: (all: parts.SwarmParts) => parts.PartW
const liveOf = <T>(list: parts.Part<T>[]) => list.filter(p => !p.deleted)
const observed = (tabId: string, held: HeldParts) => db.$transaction(tx => parts.loadObserved(tx, tabId, 'host', held))
-/** A command's load (store.ts loadRow), naming one quiet conversation as a command naming it does. */
-const commanded = (tabId: string, held: HeldParts | null, groupIds: string[] = []) => db.$transaction(tx => parts.loadActive(tx, tabId, { groupIds }, held))
+/** A command's load (store.ts loadRow), naming one quiet conversation as a command naming it does. Agents, machines, members
+ * and progress in key order: a whole read comes in its plan's order, which no reader depends on (shape.ts orders by ordinal). */
+const commanded = async (tabId: string, held: HeldParts | null, groupIds: string[] = []) => {
+ const loaded = await db.$transaction(tx => parts.loadActive(tx, tabId, { groupIds }, held))
+ const sorted = <T extends { key: string }>(list: T[]) => [...list].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
+ return { ...loaded, agents: sorted(loaded.agents), machines: sorted(loaded.machines), members: sorted(loaded.members), progress: sorted(loaded.progress) }
+}
describe('a full report\'s held parts (B3, #2597)', () => {
it('load what a server holding nothing loads, after every kind of write', { timeout: 120_000 }, async () => {
@@ -114,7 +119,7 @@ describe('a full report\'s held parts (B3, #2597)', () => {
}
})
- it('reads the machines\' columns through the Swarm\'s index, examining only what it returns, and whole only the one that changed', async () => {
+ it('lists the machines\' columns from their held index, examining no document, and reads whole only the one that changed', async () => {
const tabId = await scene()
await scene()
const held = new HeldParts()
@@ -124,7 +129,7 @@ describe('a full report\'s held parts (B3, #2597)', () => {
const entries = (await profiled(db, () => observed(tabId, held))).filter(e => e.ns.endsWith('.SwarmMachine'))
const live = (await db.swarmMachine.count({ where: { tabId, deleted: false } }))
expect(entries.map(e => [e.planSummary?.startsWith('IXSCAN') || e.planSummary === 'IDHACK' || e.planSummary === 'EXPRESS_IXSCAN', e.docsExamined, e.nreturned]))
- .toEqual([[true, live, live], [true, 1, 1]])
+ .toEqual([[true, 0, live], [true, 1, 1]])
})
it('reads the machines that changed in one read by id, however many changed (task #3119)', async () => {
const tabId = await scene()
@@ -138,7 +143,7 @@ describe('a full report\'s held parts (B3, #2597)', () => {
}
const entries = (await profiled(db, () => observed(tabId, held))).filter(e => e.ns.endsWith('.SwarmMachine'))
expect(entries.map(e => [e.planSummary?.startsWith('IXSCAN') || e.planSummary === 'IDHACK' || e.planSummary === 'EXPRESS_IXSCAN', e.docsExamined, e.nreturned]))
- .toEqual([[true, machines.length, machines.length], [true, 2, 2]])
+ .toEqual([[true, 0, machines.length], [true, 2, 2]])
})
})
@@ -184,3 +189,62 @@ describe('a command\'s held conversations (#3146)', () => {
}
})
})
+
+// Ken's prod scan, 2026-11-07 (task #4368): every command read each live agent, machine, member and progress part of its
+// Swarm whole, ~85% of what a post read. A command lists them from an index that holds every column it compares, and reads
+// whole only those that changed since this server last read them.
+describe('a command\'s held agents, machines, members and progress (#4368)', () => {
+ const KINDS = [['agent', 'SwarmAgent'], ['machine', 'SwarmMachine'], ['member', 'SwarmMember'], ['progress', 'SwarmProgress']] as const
+
+ it('load what a server holding nothing loads, after every kind of write', { timeout: 120_000 }, async () => {
+ const tabId = await scene()
+ const warm = new HeldParts(), tiny = new HeldParts(1)
+ let n = 0
+ const at = () => Date.now() + ++n
+ const some = <T>(list: parts.Part<T>[]) => liveOf(list)[0]!
+ const cases: Array<[string, () => Promise<boolean>]> = [
+ ['an agent changed', () => write(tabId, all => { const a = some(all.agents)
+ return { op: 'update', kind: 'agent', key: a.key, seen: a.version, data: { ...a.data!, name: `A${n}` } } }, at())],
+ ['an agent touched (its version alone moves)', () => write(tabId, all => { const a = some(all.agents)
+ return { op: 'touch', kind: 'agent', key: a.key, seen: a.version } }, at())],
+ ['an agent removed', () => write(tabId, all => { const a = some(all.agents)
+ return { op: 'remove', kind: 'agent', key: a.key, seen: a.version, data: a.data } }, at())],
+ ['an agent added again under its key', () => write(tabId, all => { const a = all.agents.find(x => x.deleted)!
+ return { op: 'insert', kind: 'agent', key: a.key, ordinal: a.ordinal, data: a.data } }, at())],
+ ['a member changed', () => write(tabId, all => { const m = some(all.members)
+ return { op: 'update', kind: 'member', key: m.key, seen: m.version, data: { ...m.data!, ordinalNote: n } as never } }, at())],
+ ['a progress part added', () => write(tabId, () => ({ op: 'insert', kind: 'progress', key: `p-${n}`, ordinal: 900 + n, data: { note: n } as never }), at())],
+ ['a machine\'s reading alone (dated readAt)', () => write(tabId, all => { const m = some(all.machines)
+ return { op: 'update', kind: 'machine', key: m.key, seen: m.version, data: { ...m.data!, ordinalNote: n } as never } }, at())],
+ ['an agent rewritten at the version it had, under a new date (purged, then added again)', async () => {
+ const row = await db.swarmAgent.findFirstOrThrow({ where: { tabId, deleted: false } })
+ await db.swarmAgent.update({ where: { id: row.id }, data: { changedAt: new Date(at()), data: { ...row.data as object, name: 'rewritten' } } })
+ return true
+ }],
+ ]
+ expect(await commanded(tabId, warm)).toEqual(await commanded(tabId, null))
+ for (const [name, change] of cases) {
+ expect(await change(), name).toBe(true)
+ const fresh = await commanded(tabId, null)
+ expect(await commanded(tabId, warm), name).toEqual(fresh)
+ expect(await commanded(tabId, tiny), name).toEqual(fresh)
+ }
+ })
+
+ it('lists each kind through its held index, examining no document, and reads whole only the part that changed', async () => {
+ const tabId = await scene()
+ const held = new HeldParts()
+ await commanded(tabId, held)
+ await write(tabId, all => { const a = liveOf(all.agents)[0]!
+ return { op: 'update', kind: 'agent', key: a.key, seen: a.version, data: { ...a.data!, name: 'Changed' } } })
+ const entries = await profiled(db, () => commanded(tabId, held))
+ const read = (collection: string) => entries.filter(e => e.ns.endsWith(`.${collection}`)).map(e => [e.planSummary, e.docsExamined])
+ for (const [kind, collection] of KINDS) {
+ const listing = read(collection)[0]
+ expect([kind, listing?.[0], listing?.[1]]).toEqual([kind, expect.stringMatching(/^IXSCAN \{ tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1/), 0])
+ }
+ // The one agent that changed, by id; nothing else of any kind.
+ expect(read('SwarmAgent').slice(1)).toEqual([[expect.stringMatching(/IDHACK|EXPRESS|IXSCAN \{ _id: 1 \}/), 1]])
+ for (const collection of ['SwarmMachine', 'SwarmMember', 'SwarmProgress']) expect([collection, read(collection).length]).toEqual([collection, 1])
+ })
+})
diff --git a/backend/integration/superTabOneGroup.test.ts b/backend/integration/superTabOneGroup.test.ts
index 45d89279d..27047913c 100644
--- a/backend/integration/superTabOneGroup.test.ts
+++ b/backend/integration/superTabOneGroup.test.ts
@@ -307,9 +307,11 @@ describe('one group read by id (task #2875)', () => {
const byKey = groupRows.filter(r => /^IXSCAN \{ tabId: 1, deleted: 1, key: 1/.test(r.planSummary ?? ''))
expect(byKey, describeRows(groupRows)).toHaveLength(1)
expect(byKey[0]!.docsExamined).toBe(1)
- // An agent's machine: its account fields by _id, one document.
+ // An agent's machine: its account fields, one document. This suite names no index, as a server before its first listing,
+ // and Mongo may plan it on `_id` or the held index alike; a server that listed them names `_id` (superTabCommandReads).
const machineRows = rows.filter(r => r.ns.endsWith('.SwarmMachine') && r.op !== 'getmore')
- expect(machineRows.map(r => [r.planSummary, r.docsExamined]), describeRows(machineRows)).toEqual(asAgentId ? [['IXSCAN { _id: 1 }', 1]] : [])
+ expect(machineRows.map(r => [/^IXSCAN \{ (_id: 1 \}|tabId: 1, deleted: 1, key: 1)/.test(r.planSummary ?? ''), r.docsExamined]), describeRows(machineRows))
+ .toEqual(asAgentId ? [[true, 1]] : [])
}
}, 120_000)
diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.ts
index 861a8883b..12c6e4b07 100644
--- a/backend/integration/superTabSwarmBuddy.test.ts
+++ b/backend/integration/superTabSwarmBuddy.test.ts
@@ -870,10 +870,12 @@ describe('several Buddies through the store (#3818)', () => {
const research = await named(f, 'Research')
await quiet(f, research.chat)
const reads = await profiled(db, () => send(f, 'lead', 'Hello', {}, owner))
- // Every live row of the Swarm, by tab: not one row's version check by its id.
+ // Every live row of the Swarm, by tab: not one row's version check by its id. Prisma's filters name a field as `$tabId`, a
+ // plain match (the held listing, parts/held.ts) as `tabId`.
+ const names = (filter: string, field: string) => filter.includes(`"$${field}"`) || filter.includes(`"${field}":`)
const wholeSwarm = (collection: string) => reads.filter(e => e.ns.endsWith(`.${collection}`) && e.op !== 'update').filter(e => {
const filter = JSON.stringify(e.command?.pipeline ?? e.command?.filter ?? {})
- return filter.includes('"$tabId"') && filter.includes('"$deleted"') && !filter.includes('"$_id"')
+ return names(filter, 'tabId') && names(filter, 'deleted') && !names(filter, '_id')
}).length
expect(['SwarmMachine', 'SwarmAgent', 'SwarmMember', 'SwarmProgress'].map(c => [c, wholeSwarm(c)]))
.toEqual([['SwarmMachine', 1], ['SwarmAgent', 1], ['SwarmMember', 1], ['SwarmProgress', 1]])
diff --git a/backend/integration/swarmAgentTombstones.test.ts b/backend/integration/swarmAgentTombstones.test.ts
index fd8e987f0..c96cfae4d 100644
--- a/backend/integration/swarmAgentTombstones.test.ts
+++ b/backend/integration/swarmAgentTombstones.test.ts
@@ -47,13 +47,13 @@ afterAll(async () => {
})
describe('the live-agent read', () => {
- it('uses the [tabId, deleted] index and examines only live agents', async () => {
+ it('uses an index led by [tabId, deleted] and examines only live agents', async () => {
let parts: Awaited<ReturnType<typeof loadDeliveryParts>> | undefined
const entries = await profiled(db, async () => { parts = await db.$transaction(tx => loadDeliveryParts(tx, busy, [], [])) })
expect(parts!.agents.map(a => a.key).sort()).toEqual(Array.from({ length: LIVE }, (_, i) => `live-${i}`).sort())
const read = reads(entries, 'SwarmAgent', ['tabId', 'deleted'])
expect(read, JSON.stringify(plan(read))).toHaveLength(1)
- expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1 \}/)
+ expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1[ ,]/)
expect(read[0]!.docsExamined, JSON.stringify(plan(read))).toBe(LIVE)
})
@@ -62,7 +62,7 @@ describe('the live-agent read', () => {
const entries = await profiled(db, async () => { parts = await db.$transaction(tx => loadDeliveryParts(tx, empty, [], [])) })
expect(parts!.agents).toEqual([])
const read = reads(entries, 'SwarmAgent', ['tabId', 'deleted'])
- expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1 \}/)
+ expect(read[0]!.planSummary, JSON.stringify(plan(read))).toMatch(/IXSCAN \{ tabId: 1, deleted: 1[ ,]/)
expect(read[0]!.docsExamined, JSON.stringify(plan(read))).toBe(0)
})
})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index f0f40b062..ff6d7977d 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1951,6 +1951,8 @@ model SwarmMember {
@@unique([tabId, key])
@@index([tabId, changedAt])
+ /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
+ @@index([tabId, deleted, key, version, changedAt])
/// Tombstones past their purge time, compacted by the hourly sweep (superTabs/sweeps.ts compactTombstones). Not a TTL: the tombstone stays.
@@index([purgeAt])
}
@@ -2035,8 +2037,11 @@ model SwarmAgent {
@@unique([tabId, key])
@@index([tabId, changedAt])
/// A Swarm's live agents (parts/light.ts, load.ts, read/host.ts): without it the read planned on [tabId, changedAt] and
- /// examined every tombstone too (prod 2026-11-02: 1,070 examined for 40 returned).
+ /// examined every tombstone too (prod 2026-11-02: 1,070 examined for 40 returned). The held index below has it as its prefix;
+ /// it stays until a prod scan shows that one in use (task #4368).
@@index([tabId, deleted])
+ /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
+ @@index([tabId, deleted, key, version, changedAt])
@@index([machineId, deleted])
@@index([tabId, contributorId])
/// One agent's registrations in every Swarm (confidential.ts, sessionScope.ts): host rows read them on every changed tab.
@@ -2071,6 +2076,8 @@ model SwarmMachine {
@@unique([tabId, key])
@@index([tabId, changedAt])
@@index([tabId, readAt])
+ /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
+ @@index([tabId, deleted, key, version, changedAt, readAt])
@@index([machineId, deleted])
/// Machines whose settings changed since a host's cursor (read/host.ts woken).
@@index([tabId, hostChangedAt])
@@ -2120,6 +2127,8 @@ model SwarmProgress {
@@unique([tabId, key])
@@index([tabId, changedAt])
+ /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
+ @@index([tabId, deleted, key, version, changedAt])
/// Removed parts go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
@@index([purgeAt], map: "part_purge")
}
diff --git a/backend/src/superTabs/parts/held.ts b/backend/src/superTabs/parts/held.ts
index 386b80846..1052f0b41 100644
--- a/backend/src/superTabs/parts/held.ts
+++ b/backend/src/superTabs/parts/held.ts
@@ -1,5 +1,5 @@
/**
- * The parts a machine's full report last read, held in this process at their exact version (B3, #2597). Every reading
+ * The parts a command or a machine's full report last read, held in this process at their exact version (B3, #2597). Every reading
* re-read the Swarm's machine parts and its running and Lead conversations whole (prod, 2026-11-04: 1.57 GB an hour, the
* route with the most database time), though between two reports most of them had not changed. A read here first asks
* MongoDB, in the report's own transaction, only for each selected part's columns that every write moves (`version`,
@@ -11,8 +11,8 @@ import type { Prisma } from '@prisma/client'
import { sizeOf } from '../cache.js'
import { recordCache } from '../cacheStats.js'
import { ms, rawPartRow } from './light.js'
-import { groupsBy, type GroupIndex } from './indexed.js'
-import { partId, type PartRow } from './write.js'
+import { groupsBy, readBy, type GroupIndex } from './indexed.js'
+import { delegate, partId, type PartRow } from './write.js'
type Transaction = Prisma.TransactionClient
type Where = Record<string, unknown>
@@ -29,7 +29,15 @@ function columnsOf(row: Record<string, unknown>): string {
return `${Number(row.version)}|${date(row.changedAt)}|${date(row.readAt)}|${row.dormant ? 1 : 0}`
}
const byKey = (rows: PartRow[]) => rows.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
-const COLUMNS = { _id: 0, key: 1, version: 1, changedAt: 1, readAt: 1, dormant: 1 }
+/** The kinds held whole by key besides groups, and their collections. */
+export type HeldKind = 'member' | 'agent' | 'machine' | 'progress'
+const COLLECTION = { member: 'SwarmMember', agent: 'SwarmAgent', machine: 'SwarmMachine', progress: 'SwarmProgress' } as const
+/** Each kind's `swarm cache` entry. */
+const ENTRY = { member: 'held-members', agent: 'held-agents', machine: 'held-machines', progress: 'held-progress', group: 'held-groups' } as const
+/** Each kind's columns, every one in its held index (parts/indexed.ts), so a listing reads no document: only a machine has a
+ * readAt, and none of them is ever dormant. */
+const COLUMNS = { _id: 0, key: 1, version: 1, changedAt: 1 }
+const MACHINE_COLUMNS = { ...COLUMNS, readAt: 1 }
/** A group's columns: it has no readAt, and every other one is in the held index (parts/indexed.ts `held`), so a listing of the
* awake ones through it reads no document. */
const GROUP_COLUMNS = { _id: 0, key: 1, version: 1, changedAt: 1, dormant: 1 }
@@ -55,7 +63,7 @@ export class HeldParts {
return held.value
}
- /** @internal */ holds(tab: Tab, kind: 'machine' | 'group'): boolean {
+ /** @internal */ holds(tab: Tab, kind: HeldKind | 'group'): boolean {
for (const id of tab.parts.keys()) if (id.startsWith(`${kind}:`)) return true
return false
}
@@ -94,34 +102,32 @@ export class HeldParts {
/** The process's held parts: machine reports'. */
export const HELD = new HeldParts()
/** Commands' (parts/load.ts loadActive), apart from the reports': each read lets go of what it did not select, and a report
- * selects only running work and Lead conversations, where a command selects every awake conversation. */
+ * selects only running work and Lead conversations, where a command selects every awake conversation and every live agent,
+ * machine, member and progress part (task #4368). */
export const COMMAND_HELD = new HeldParts()
export class HeldRead {
constructor(private readonly owner: HeldParts, private readonly tab: Tab, private readonly at: number) {}
- /** The Swarm's live machine parts, as `findMany({ where: { tabId, deleted: false } })` returns them, in key order. */
- async machines(tx: Transaction): Promise<PartRow[]> {
+ /** The Swarm's live parts of `kind`, as `findMany({ where: { tabId, deleted: false } })` returns them, in key order. */
+ async parts(tx: Transaction, kind: HeldKind): Promise<PartRow[]> {
const { tabId } = this.tab
- const all = () => tx.swarmMachine.findMany({ where: { tabId, deleted: false } }) as unknown as Promise<PartRow[]>
+ const all = () => delegate(tx, kind).findMany({ where: { tabId, deleted: false } }) as unknown as Promise<PartRow[]>
// Holding none of them, the whole read alone, as before.
- if (!this.owner.holds(this.tab, 'machine')) return byKey(this.kept('machine', await all(), 'cold'))
- const listed = await tx.swarmMachine.aggregateRaw({ pipeline: [{ $match: { tabId, deleted: false } }, { $project: COLUMNS }] }) as unknown as
- Array<Record<string, unknown>>
+ if (!this.owner.holds(this.tab, kind)) return byKey(this.kept(kind, await all(), 'cold'))
+ const listed = await readBy(tx, COLLECTION[kind], 'held', [{ $match: { tabId, deleted: false } }, { $project: kind === 'machine' ? MACHINE_COLUMNS : COLUMNS }])
const rows = new Map<string, PartRow>()
const changed: string[] = []
for (const row of listed) {
- const value = this.owner.take(this.tab, `machine:${row.key as string}`, columnsOf(row), this.at)
+ const value = this.owner.take(this.tab, `${kind}:${row.key as string}`, columnsOf(row), this.at)
if (value) rows.set(row.key as string, value as PartRow)
else changed.push(row.key as string)
}
- if (!changed.length) recordCache('held-machines', 'hit')
+ if (!changed.length) recordCache(ENTRY[kind], 'hit')
else {
- // However many changed, one read by id: one `findUnique` each was a top slow shape on prod (task #3119). Raw, so the ids
- // are a plain `$in` on `_id`.
- const read = (await tx.swarmMachine.aggregateRaw({ pipeline: [{ $match: { _id: { $in: changed.map(key => partId(tabId, key)) }, deleted: false } }] }) as
- unknown as Array<Record<string, unknown>>).map(rawPartRow)
- for (const row of this.kept('machine', read, 'parts')) rows.set(row.key, row)
+ // However many changed, one read by id: one `findUnique` each was a top slow shape on prod (task #3119).
+ const read = (await readBy(tx, COLLECTION[kind], 'id', [{ $match: { _id: { $in: changed.map(key => partId(tabId, key)) }, deleted: false } }])).map(rawPartRow)
+ for (const row of this.kept(kind, read, 'parts')) rows.set(row.key, row)
}
return byKey([...rows.values()])
}
@@ -142,16 +148,16 @@ export class HeldRead {
if (value) rows.set(row.key as string, value as Record<string, unknown>)
else changed.push(row.key as string)
}
- if (!changed.length) recordCache('held-groups', 'hit')
+ if (!changed.length) recordCache(ENTRY.group, 'hit')
else for (const row of this.kept('group', await groupsBy(tx, 'key', [{ $match: { tabId, deleted: false, key: { $in: changed } } }]), 'parts')) rows.set(row.key as string, row)
return listed.flatMap(row => rows.has(row.key as string) ? [rows.get(row.key as string)!] : [])
}
- /** Holds the parts just read whole, and counts them (`swarm cache`, entries `held-machines` and `held-groups`). */
- private kept<T extends { key: string } | Record<string, unknown>>(kind: 'machine' | 'group', rows: T[], reason: 'cold' | 'parts'): T[] {
+ /** Holds the parts just read whole, and counts them (`swarm cache`, entries `held-machines`, `held-groups` and the like). */
+ private kept<T extends { key: string } | Record<string, unknown>>(kind: HeldKind | 'group', rows: T[], reason: 'cold' | 'parts'): T[] {
let bytes = 0
for (const row of rows) bytes += this.owner.keep(this.tab, `${kind}:${(row as { key: string }).key}`, columnsOf(row as Record<string, unknown>), row, this.at)
- recordCache(kind === 'machine' ? 'held-machines' : 'held-groups', 'full', { bytes, parts: rows.length, reason })
+ recordCache(ENTRY[kind], 'full', { bytes, parts: rows.length, reason })
return rows
}
diff --git a/backend/src/superTabs/parts/index.ts b/backend/src/superTabs/parts/index.ts
index 3a89a67b2..2b4660f02 100644
--- a/backend/src/superTabs/parts/index.ts
+++ b/backend/src/superTabs/parts/index.ts
@@ -7,7 +7,7 @@ export * from './types.js'
export { clock, createClock } from './clock.js'
export { knownKind, reassemble, split, toLegacyState } from './shape.js'
-export { DORMANT_PAGE, FEED_IDS, FEED_PAGE, FEED_READS, insertParts, lastChangedAt, loadAccess, loadActive, loadAll, loadChanged, loadDelta, loadDormant, loadFeed, loadFinishedStarts, loadGroups, loadGroupUnless, loadMachineParts, loadMachines, loadMachineAccounts, loadNamed, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'
+export { DORMANT_PAGE, FEED_IDS, FEED_PAGE, FEED_READS, insertParts, lastChangedAt, loadAccess, loadActive, loadAll, loadChanged, loadDelta, loadDormant, loadFeed, loadFinishedStarts, loadGroups, loadGroupsByKey, loadGroupUnless, loadMachineParts, loadMachines, loadMachineAccounts, loadNamed, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'
export type { SwarmDelta } from './load.js'
export { loadLight, loadLightGroups } from './light.js'
export { guardedWrite, PartConflict, type PartWrite } from './write.js'
diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.ts
index a7277c3d4..4ae3a14ed 100644
--- a/backend/src/superTabs/parts/indexed.ts
+++ b/backend/src/superTabs/parts/indexed.ts
@@ -58,16 +58,18 @@ export const NAMED_INDEX = {
autoJoin: { autonomousEnv: 1, autoJoinDomain: 1 },
},
/** Each part kind's changes since a cursor; machines also by when they were last read. `id`: rows by id, a delta's whole
- * rows of the versions it has not read (parts/load.ts loadDelta). */
+ * rows of the versions it has not read (parts/load.ts loadDelta). `held`: a command's live parts by the columns a held part
+ * is compared by (parts/held.ts), so the listing reads no document (task #4368). */
SwarmHead: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 } },
/** `purge`: tombstones past their purge time (the hourly sweep). */
- SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },
- SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },
- SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 } },
+ SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
+ SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
+ SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 },
+ held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1, readAt: 1 } },
/** `expiry`: live starts by finish time (the hourly sweep). `agents`: a Swarm's starts of some agents (agentTombstones.ts):
* unnamed, Mongo planned that read on `expiry` and read every live start of every Swarm. */
SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 }, agents: { tabId: 1, agentId: 1 }, id: { _id: 1 } },
- SwarmProgress: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 } },
+ SwarmProgress: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
SuperTabMessage: {
/** A conversation's page in (sequence, id) order. */
sequence: { tabId: 1, conversationId: 1, sequence: 1, _id: 1 },
diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.ts
index 47cd6a4d5..2e912be54 100644
--- a/backend/src/superTabs/parts/load.ts
+++ b/backend/src/superTabs/parts/load.ts
@@ -7,7 +7,7 @@ import { recordDeltaRows } from '../cacheStats.js'
import type { AgentStart } from '../model.js'
import { ms, rawGroupRow, rawPartRow } from './light.js'
import { groupsBy, readBy, type GroupIndex, type NamedCollection } from './indexed.js'
-import { COMMAND_HELD, HELD, type HeldParts, type HeldRead } from './held.js'
+import { COMMAND_HELD, HELD, type HeldKind, type HeldParts, type HeldRead } from './held.js'
type Transaction = Prisma.TransactionClient
type Where = Record<string, unknown>
@@ -24,8 +24,9 @@ async function liveGroups(tx: Transaction, tabId: string, reads: GroupReads, hel
return [...new Map(found.flat().map(row => [row.key as string, rawGroupRow(row)])).values()]
}
-/** `null` for a kind leaves it out: none are loaded. Groups go by `where` (every part, tombstones too) or as named reads. */
-async function assemble(tx: Transaction, tabId: string, where: Record<Exclude<PartKind, 'head' | 'group'>, Where | null> & { group: Where | GroupReads },
+/** `null` for a kind leaves it out: none are loaded. `'held'`: its live parts through `held`, whole only those changed since it
+ * last read them. Groups go by `where` (every part, tombstones too) or as named reads. */
+async function assemble(tx: Transaction, tabId: string, where: Record<HeldKind, Where | null | 'held'> & { start: Where | null } & { group: Where | GroupReads },
held?: HeldRead): Promise<SwarmParts> {
const head = await tx.swarmHead.findUnique({ where: { id: partId(tabId, 'head') } })
if (!head) throw Object.assign(new Error(`Swarm ${tabId} has no parts`), { code: 'PARTS_MISSING' })
@@ -33,6 +34,7 @@ async function assemble(tx: Transaction, tabId: string, where: Record<Exclude<Pa
const [members, agents, groups, machines, starts, progress] = await Promise.all((['member', 'agent', 'group', 'machine', 'start', 'progress'] as const)
.map(kind => kind === 'group' && Array.isArray(group) ? liveGroups(tx, tabId, group, held).then(rows => rows.map(row => toPart(kind, row)))
: where[kind] === null ? Promise.resolve([])
+ : where[kind] === 'held' ? held!.parts(tx, kind as HeldKind).then(rows => rows.map(row => toPart(kind, row)))
: delegate(tx, kind).findMany({ where: { tabId, ...where[kind] as Where } }).then(rows => rows.map(row => toPart(kind, row)))))
return { tabId, head: toPart<HeadData>('head', head as unknown as PartRow), members, agents, groups, machines, starts, progress,
sequenceBase: head.sequenceBase, visibilityEpoch: head.visibilityEpoch, groupCounter: head.groupCounter } as SwarmParts
@@ -54,12 +56,15 @@ export async function loadActive(tx: Transaction, tabId: string,
// A group stored with no project belongs to the default one (projects.ts groupProject), as in a Swarm from before projects;
// a null match is a missing field too.
const projectIds = [...opts.projectIds ?? [], ...opts.projectIds?.includes('lead') ? [null] : []]
- // The awake groups through the held index, held (task #3146): each command read every one of them whole. Every live group
- // (allGroups) is a rare read, made whole as before.
- const read = held && !opts.allGroups ? held.read(tabId) : undefined
+ // The awake groups through the held index, held (task #3146), and every live agent, machine, member and progress part
+ // (task #4368): each command read every one of them whole. A read of every live group (allGroups, rare) adds the dormant
+ // ones; the next command's read lets them go.
+ const read = held?.read(tabId)
+ const kept = read ? 'held' as const : live
+ const awake: GroupReads = [['held', { dormant: false }]]
const parts = await assemble(tx, tabId, {
- member: live, agent: live, machine: live, progress: live,
- group: opts.allGroups ? [['live', {}]] : [['held', { dormant: false }], ...opts.groupIds?.length ? [['key', { key: { $in: opts.groupIds } }] as const] : [],
+ member: kept, agent: kept, machine: kept, progress: kept,
+ group: opts.allGroups ? [...awake, ['dormancy', { dormant: true }]] : [...awake, ...opts.groupIds?.length ? [['key', { key: { $in: opts.groupIds } }] as const] : [],
...opts.agentIds?.length ? [['agents', { agentIds: { $in: opts.agentIds } }] as const] : [],
...projectIds.length ? [['project', { projectId: { $in: projectIds } }] as const] : []],
start: opts.includeRecentStarts ? live : or({ finishedAt: null }, !!opts.startIds?.length && { key: { in: opts.startIds } },
@@ -111,7 +116,7 @@ export async function loadObserved(tx: Transaction, tabId: string, machineId: st
const read = held.read(tabId)
const [loaded, machineRows] = await Promise.all([
assemble(tx, tabId, { member: live, agent: live, machine: null, progress: null, start: { ...live, finishedAt: null }, group: [] }),
- read.machines(tx)])
+ read.parts(tx, 'machine')])
const machines = machineRows.map(row => toPart<MachineData>('machine', row))
const { projects } = loaded.head.data!
// The Lead conversations; the removed Leads conversation is no longer read (model.ts leadsRemoved).
@@ -148,6 +153,13 @@ export function loadReadBase(tx: Transaction, tabId: string): Promise<SwarmParts
start: { ...live, finishedAt: null }, progress: live })
}
+/** The head and the live groups with these keys, dormant ones too, and no other part: what the GitHub reads before a
+ * command look up (store.ts factsLoad). A whole command load there read every agent and machine (task #4368). */
+export function loadGroupsByKey(tx: Transaction, tabId: string, keys: string[]): Promise<SwarmParts> {
+ return assemble(tx, tabId, { member: null, agent: null, machine: null, start: null, progress: null,
+ group: keys.length ? [['key', { key: { $in: [...new Set(keys)] } }]] : [] })
+}
+
/** What a read check needs of a Swarm, and no more (read/service.ts oneGroup, task #2875): its head, members and agents. The
* read cache holds it as `access` and patches it from those kinds alone (cachePatch.ts accessRule). */
export function loadAccess(tx: Transaction, tabId: string): Promise<SwarmParts> {
@@ -171,14 +183,15 @@ export async function loadGroupUnless(tx: Transaction, tabId: string, key: strin
/** These live machine parts by key, in one read by `_id`, with only what says which account an agent there runs as
* (projects.ts teamAccountPool): its host Mac and its session kind. Its lists read empty. What a one-group read checks an
- * agent's host against (read/service.ts oneGroup), never a whole machine row with its readings. */
+ * agent's host against (read/service.ts oneGroup), never a whole machine row with its readings. By `_id`, named: with `tabId`
+ * and `deleted` in its match, Mongo could plan it on the held index and examine every machine of the Swarm (task #4368). */
export async function loadMachineAccounts(tx: Transaction, tabId: string, keys: string[]): Promise<Part<MachineData>[]> {
if (!keys.length) return []
const none = { $literal: [] }
- const rows = await tx.swarmMachine.aggregateRaw({ pipeline: [{ $match: { _id: { $in: [...new Set(keys)].map(key => partId(tabId, key)) }, tabId, deleted: false } },
+ const rows = await readBy(tx, 'SwarmMachine', 'id', [{ $match: { _id: { $in: [...new Set(keys)].map(key => partId(tabId, key)) }, tabId, deleted: false } },
{ $project: { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, 'data.machineId': 1, 'data.contribution.machineId': 1,
'data.contribution.hostMachineId': 1, 'data.contribution.observation.sessionKind': 1, 'data.reservations': none, 'data.released': none,
- 'data.closingSessions': none, 'data.cleanups': none } }] }) as unknown as Array<Record<string, unknown>>
+ 'data.closingSessions': none, 'data.cleanups': none } }])
return rows.map(row => toPart<MachineData>('machine', rawPartRow(row)))
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 4b81dbb24..f1b6ac280 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -87,7 +87,7 @@ import { endedReply, taskLineChats } from './taskLine.js'
import { owedAsk } from './timeChecks.js'
import { ledgerGroupIds, settleReleases, type ReleaseFacts, type ReleaseRules, type SettledReleases } from './releases.js'
import { groupsOf, archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'
-import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadNamed, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
+import { clock, insertParts, loadActive, loadGroups, loadGroupsByKey, loadLightGroups, loadMachineParts, loadNamed, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'
import type { MachineRename } from './machineRenames.js'
@@ -1033,14 +1033,25 @@ export class SuperTabStore {
private async ensure(tx: Transaction, loaded: Loaded, named: Named): Promise<Loaded> {
const has = (ids: string[] | undefined, present: (id: string) => boolean) => (ids ?? []).every(present)
const { state } = loaded
- if (!named.allGroups && has(named.groupIds, id => state.conversations.some(c => c.id === id)) && has(named.startIds, id => !!state.starts?.some(s => s.id === id))
+ if (has(named.groupIds, id => state.conversations.some(c => c.id === id)) && has(named.startIds, id => !!state.starts?.some(s => s.id === id))
&& !named.agentIds?.length && !named.projectIds?.length && !named.startAgentIds?.length) return loaded
recordReload()
- // Every live group, dormant ones too, is the rare whole read; any other name adds only what it names to this load.
- if (named.allGroups) return loadRow(tx, loaded.row, { ...named, groupIds: [...new Set([...named.groupIds ?? [], ...loaded.parts.groups.filter(g => g.dormant).map(g => g.key)])] })
+ // A name adds only what it names to this load.
return loadedFrom(loaded.row, await loadNamed(tx, loaded.parts, named))
}
+ /**
+ * The Swarm a caller may address with only its head and the conversations a command names, each step's task too: what the
+ * GitHub reads before a command look up (a conversation's project and pull requests). Each loaded the whole Swarm, so a
+ * work.assign read it three times and a Ready five (task #4368). They authorize nothing; the command's own load does.
+ */
+ private async factsLoad(tx: Transaction, user: AuthUser, tabId: string, command: unknown): Promise<Loaded> {
+ const row = await this.row(tx, user, tabId)
+ const parts = await loadGroupsByKey(tx, row.id, namedFor(command as Command).groupIds ?? [])
+ const tasks = parts.groups.flatMap(g => g.data?.reviewOf ? [g.data.reviewOf] : [])
+ return loadedFrom(row, tasks.length ? await loadNamed(tx, parts, { groupIds: tasks }) : parts)
+ }
+
/** A Swarm with one start loaded even when finished, and the start's group even when dormant. */
private async loadStart(tx: Transaction, user: AuthUser, tabId: string, startId: string): Promise<Loaded> {
const loaded = await this.load(tx, user, tabId, { startIds: [startId] })
@@ -1701,7 +1712,7 @@ export class SuperTabStore {
if (typeof ref === 'string' && this.hooks.branchPushOrigin) {
const branch = ref.replace(/^refs\/(heads|remotes\/origin)\//, '')
const repositoryUrl = await transaction(this.db, async tx => {
- const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const { state } = await this.factsLoad(tx, user, tabId, command)
if (asked.type === 'lead.start') return projectsOf(state).find(p => p.id === asked.projectId)?.repository?.repositoryUrl ?? null
const group = state.conversations.find(c => c.id === asked.request?.conversationId)
return group ? groupProject(state, group).repository?.repositoryUrl ?? null : undefined
@@ -1711,7 +1722,7 @@ export class SuperTabStore {
const reads = asked.type === 'work.assign' || asked.type === 'work.teamWritten' || (asked.type === 'conversation.agent' && asked.present === true) || (asked.type === 'work.status' && asked.status === 'review')
if (!hook || typeof asked.conversationId !== 'string' || !reads) return undefined
const facts = await transaction(this.db, async tx => {
- const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const { state } = await this.factsLoad(tx, user, tabId, command)
const group = state.conversations.find(c => c.id === asked.conversationId)
if (!group) return null
const task = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined
@@ -1761,7 +1772,7 @@ export class SuperTabStore {
if (!hook || typeof conversationId !== 'string') return undefined
try {
const project = await transaction(this.db, async tx => {
- const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const { state } = await this.factsLoad(tx, user, tabId, command)
const group = state.conversations.find(c => c.id === conversationId)
return group ? groupProject(state, group) : undefined
})
@@ -1786,7 +1797,7 @@ export class SuperTabStore {
let facts: { repositoryUrl: string | null; urls: string[] } | null = null
try {
facts = await transaction(this.db, async tx => {
- const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const { state } = await this.factsLoad(tx, user, tabId, command)
const group = state.conversations.find(c => c.id === asked.conversationId)
if (!group || group.reviewOf) return null
const repositoryUrl = groupProject(state, group).repository?.repositoryUrl ?? null
@@ -2543,7 +2554,7 @@ export class SuperTabStore {
const same = (sha: string) => sha.toLowerCase() === head.toLowerCase()
if (!task || !url || (known && (same(known.head) || known.carries?.some(same)) && (base === undefined || base === known.base))) return null
return { task, urls: [url] }
- }, [command.conversationId])
+ })
}
/** After a task's Ready, the heads of the pull requests it names that the task links, else its newest link (task #3628). */
@@ -2556,21 +2567,19 @@ export class SuperTabStore {
const named = typeof command.result === 'string' ? pullRequestsIn(command.result, groupProject(state, task).repository?.repositoryUrl ?? null) : []
const urls = linked.filter(url => named.includes(url))
return { task, urls: urls.length ? urls : linked.slice(-1) }
- }, [])
+ })
}
/** [pick]'s pull requests of a task read from GitHub now and recorded (pullRequestEvents.ts readPullRequestsNow), outside any
* command's transaction, as GitHub may take seconds. A failure leaves the record as it was and is logged: the command is
- * judged on the record then, as before. [groups]: the command's groups whose task, when they are a step, is loaded too. */
+ * judged on the record then, as before. */
private async headsReadNow(user: AuthUser, tabId: string, command: Command,
- pick: (state: SuperTabState) => { task: Conversation; urls: string[] } | null, groups: string[]): Promise<void> {
+ pick: (state: SuperTabState) => { task: Conversation; urls: string[] } | null): Promise<void> {
let picked: { task: TaskHeads; urls: string[] } | null = null
try {
picked = await transaction(this.db, async tx => {
- const loaded = await this.load(tx, user, tabId, namedFor(command))
- // A step's task may be dormant: loaded by its id.
- const reviewOf = groups.map(id => loaded.state.conversations.find(c => c.id === id)?.reviewOf).filter((id): id is string => !!id)
- const { state } = reviewOf.length ? await this.ensure(tx, loaded, { groupIds: [...groups, ...reviewOf] }) : loaded
+ // A step's task, dormant ones too, is loaded with it.
+ const { state } = await this.factsLoad(tx, user, tabId, command)
const chosen = pick(state)
return chosen && chosen.urls.length ? { task: { key: chosen.task.id, heads: chosen.task.pullRequestHeads ?? null,
steps: chosen.task.stepIds ?? null }, urls: chosen.urls } : null
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index bc87547d9..db7c55889 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -7,6 +7,6 @@ export default defineConfig({ test: { include: ['integration/superTabProposalCar
'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts', 'integration/superTabScorecard.test.ts',
- 'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
+ 'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabCommandReads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
'integration/superTabInstructions.test.ts', 'integration/superTabInstructionsRebase.test.ts', 'integration/superTabInstructionsRestore.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabTimeChecks.test.ts', 'integration/superTabReleases.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabCanChat.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts', 'integration/crewDispatch.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/docs/plans/2026-11-07-command-reads-plan.md b/docs/plans/2026-11-07-command-reads-plan.md
new file mode 100644
index 000000000..1b0369a00
--- /dev/null
+++ b/docs/plans/2026-11-07-command-reads-plan.md
@@ -0,0 +1,107 @@
+# A POST command reads only the Swarm parts it touches: 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:** A common command (post, react, work.status, work.assign, conversation.create) and the crew dispatch pass it
+schedules read no Swarm part collection whole, within per-command query and byte budgets on a prod-sized store (task #4368).
+
+**Architecture:** Three causes, measured on a prod-sized store (60 machines, 60 agents, 200 conversations) with the
+Mongo profiler. (1) Every command load (`parts/load.ts loadActive`) reads every live member, agent, machine and progress
+part whole; only awake groups go through the held parts (`parts/held.ts`, #3146). (2) Before the command's own load,
+`work.assign` and a Ready `work.status` load the whole Swarm again, once per GitHub pre-read (`pushOriginFor`,
+`repositoryReachFor`, `pullRequestFilesFor`, `headsReadNow`), only to find one conversation and its project. (3) A write
+that frees or opens work schedules `dispatchCrew`, which loads the whole Swarm too, billed to the POST route. The fix:
+the held parts cover members, agents, machines and progress, listed from a covering index and read whole only when
+changed; the pre-reads read the head and the named conversations alone; the dispatch pass's load is a command load, so
+(1) fixes it.
+
+**Tech Stack:** TypeScript, Prisma on MongoDB 7, vitest with mongodb-memory-server.
+
+**Spec:** Task #4368's brief (Ken's prod scan 09:20 VN 2026-11-07: 28.2 queries, 1,156 KB, 1,274 ms DB time per POST
+command; POST p95 1,080 ms against ≤ 475; Atlas CPU 45.8% against ≤ 40%).
+
+## Global Constraints
+
+- Backend only; ships as a backend hotfix.
+- No production access: Ken's numbers and a local real store.
+- Audience stays server-enforced: a narrower read never shows a person or agent more than before.
+- No stale read that loses a write: a command works on exactly what a whole read in its transaction would return.
+- Every query uses an index; a listing names its index (`parts/indexed.ts readBy`).
+
+## Review Focus
+
+- A part another server changed between two commands here: the next command sees the change (held compares version,
+ changedAt and readAt in the command's own snapshot).
+- A machine whose reading alone moved (`readAt`, not `changedAt`): read whole again, never served from what was held.
+- A part removed and its key made again (version back to 1): `changedAt` differs, so it is read whole.
+- A database without the new indexes yet (the release's schema step runs after a server starts): the listing runs
+ without the hint and is still correct (`readBy` falls back).
+- The held cap (32 MB per process): a Swarm let go reads cold, as before.
+
+---
+
+### Task 1: Per-command read budgets on a prod-sized store
+
+**Files:**
+- Create: `backend/integration/superTabCommandReads.test.ts`
+- Modify: `backend/vitest.super-tabs.config.ts` (include it)
+
+**Interfaces:**
+- Produces: `wholeReads(entries: ProfileEntry[]): Record<string, number>` (a read of a part collection filtered on the
+ Swarm alone that examines documents) and `measured(entries)` → `{ queries, kb, whole }`.
+
+- [ ] **Step 1: Write the failing tests.** A Swarm of 60 machines, 60 agents, 200 conversations (a third dormant), on a
+ store with prod's GitHub pre-read hooks answering at once. After one warm-up command, each of post, react,
+ work.status, work.assign, conversation.create and a dispatch pass is profiled: `whole` is `{}`, and queries and KB
+ stay within the budgets the PR records.
+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabCommandReads.test.ts`.
+ Expected: FAIL, every command reading SwarmAgent, SwarmMachine, SwarmMember and SwarmProgress whole; work.assign three
+ times.
+- [ ] **Step 3: Commit** the failing test.
+
+### Task 2: The GitHub pre-reads read the head and the named conversations alone
+
+**Files:**
+- Modify: `backend/src/superTabs/parts/load.ts` (new `loadGroupsByKey`)
+- Modify: `backend/src/superTabs/store.ts` (`pushOriginFor`, `repositoryReachFor`, `pullRequestFilesFor`, `headsReadNow`)
+
+**Interfaces:**
+- Produces: `loadGroupsByKey(tx, tabId, keys: string[]): Promise<SwarmParts>`: the head and the live groups with these
+ keys, dormant ones too; no other part.
+- Produces: `SuperTabStore.factsLoad(tx, user, tabId, groupIds): Promise<Loaded>`: the Swarm row check `load` makes, then
+ `loadGroupsByKey`, with each loaded step's task added the same way.
+
+- [ ] **Step 1: Run Task 1's work.assign test.** Expected: FAIL with three whole reads of each kind.
+- [ ] **Step 2: Implement.** Each pre-read loads through `factsLoad` with the conversation it names; what it computes
+ (the repository URL, the task's and step's pull requests) is unchanged. They authorize nothing, before or after: the
+ command's own load does.
+- [ ] **Step 3: Run Task 1's tests and `integration/superTabGithub.test.ts`, `superTabReviewSteps.test.ts`,
+ `superTabPullRequestEvents.test.ts`.** Expected: work.assign reads each kind whole once; the others pass.
+- [ ] **Step 4: Commit.**
+
+### Task 3: Held parts for members, agents, machines and progress
+
+**Files:**
+- Modify: `backend/prisma/schema.prisma` (a covering index per kind)
+- Modify: `backend/src/superTabs/parts/indexed.ts` (`NAMED_INDEX.<collection>.held`)
+- Modify: `backend/src/superTabs/parts/held.ts` (`HeldRead.machines` becomes `HeldRead.parts(tx, kind)`)
+- Modify: `backend/src/superTabs/parts/load.ts` (`assemble`, `loadActive`, `loadObserved`)
+- Modify: `backend/src/superTabs/store.ts` (`ensure`: its `allGroups` branch has no caller and goes)
+- Test: `backend/integration/superTabHeldParts.test.ts`
+
+**Interfaces:**
+- Produces: `HeldRead.parts(tx, kind: 'member' | 'agent' | 'machine' | 'progress'): Promise<PartRow[]>`: the live parts
+ of that kind, as `findMany({ where: { tabId, deleted: false } })` returns them, in key order.
+- Indexes: `[tabId, deleted, key, version, changedAt]` on SwarmMember, SwarmAgent (replacing `[tabId, deleted]`, its
+ prefix) and SwarmProgress; `[tabId, deleted, key, version, changedAt, readAt]` on SwarmMachine.
+
+- [ ] **Step 1: Write the failing tests** in `superTabHeldParts.test.ts`: an agent another server changed, and a machine
+ whose reading alone moved, are seen by the next command; the listing of each kind is an IXSCAN on its `held` index
+ examining no document.
+- [ ] **Step 2: Run them.** Expected: FAIL (the listing reads documents whole).
+- [ ] **Step 3: Implement.** `loadActive` (allGroups too) lists each kind through the held read; groups as before. An
+ `allGroups` read keeps the awake groups held and reads the dormant ones whole.
+- [ ] **Step 4: Run Task 1's tests, `superTabHeldParts`, `superTabCommandLoads`, `superTabMachineReports`,
+ `superTabIndexes`, `crewDispatch`.** Expected: PASS, no whole read on any common command.
+- [ ] **Step 5: Commit.**