The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
perf(backend): bound delivery claim, ack and hold authority reads (#2011)
0xken1510b35dc60deb
diff --git a/backend/integration/superTabHotReads.test.ts b/backend/integration/superTabHotReads.test.tsindex db332f187..cd92abe4b 100644--- a/backend/integration/superTabHotReads.test.ts+++ b/backend/integration/superTabHotReads.test.ts@@ -8,6 +8,7 @@ import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'+import { listGroupIndexes } from '../src/superTabs/parts/indexed.js'import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import { waitingIn } from '../src/superTabs/decisions.js'import { HostReads } from '../src/superTabs/read/host.js'@@ -40,6 +41,7 @@ beforeAll(async () => {db = new PrismaClient({ datasources: { db: { url: uri } } })await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: 'prod' } })store = new SuperTabStore(db, () => clock)+ await listGroupIndexes(db)})afterAll(async () => {await db?.$disconnect()@@ -92,7 +94,8 @@ async function profiled(run: () => Promise<unknown>): Promise<ProfileEntry[]> {} finally {await db.$runCommandRaw({ profile: 0 })}- const reply = await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: PROFILE_STAGES, cursor: { batchSize: 100000 } }) as unknown as { cursor: { firstBatch: ProfileEntry[] } }+ const reply = await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: [+ { $project: { ...PROFILE_STAGES[0]!.$project, 'command.hint': 1 } }], cursor: { batchSize: 100000 } }) as unknown as { cursor: { firstBatch: ProfileEntry[] } }return reply.cursor.firstBatch.map(profileEntry)}@@ -139,6 +142,29 @@ it('reuses the host timestamp at the same stamp, including a repeated wake withexpect((await direct.changes(owner, s.machineId, { full: true })).tabs).toEqual(changed.tabs)})+describe('delivery authority reads', () => {+ it.each(['person', 'agent'] as const)('claim, hold and ack from a %s leave unrelated conversations and machine parts unread', async sender => {+ const s = await scene()+ // Keep unrelated conversations active: dormant rows already escape loadActive.+ await db.swarmGroup.updateMany({ where: { tabId: s.tabId }, data: { dormant: false } })+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'message.send',+ conversationId: s.web, text: 'Please continue.', recipientIds: [s.worker], replyTo: null } }, sender === 'agent' ? s.lead : undefined)+ const delivery = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: s.tabId, agentId: s.worker, status: 'queued' } })+ for (const action of [{ type: 'claim', claimId: 'bounded' },+ { type: 'hold', claimId: 'bounded', reason: 'team_waiting_idle' },+ { type: 'ack', claimId: 'bounded', receipt: 'typed', uncertain: false }] as const) {+ const entries = await profiled(() => store.delivery(owner, s.tabId, s.worker, delivery.id, action))+ const groups = entries.filter(e => e.ns.endsWith('.SwarmGroup') && e.op !== 'update')+ const returned = groups.reduce((sum, e) => sum + (e.nreturned ?? 0), 0)+ console.log(`delivery ${action.type}: groups=${returned}, docs=${entries.reduce((sum, e) => sum + (e.docsExamined ?? 0), 0)}`)+ // The project and Swarm Lead conversations plus the receiver's group; no quiet groups or finished work.+ expect(returned, `${action.type}: ${JSON.stringify(plan(groups))}`).toBe(3)+ expect(groups.every(e => !!e.command?.hint), 'delivery reads use the installed group indexes').toBe(true)+ expect(entries.filter(e => e.ns.endsWith('.SwarmMachine'))).toEqual([])+ }+ })+})+describe('hot reads read only what they return (roadmap 2.7)', () => {let entries: ProfileEntry[]let s: Awaited<ReturnType<typeof scene>>diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex bacf0e229..92586281f 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -127,6 +127,74 @@ afterAll(async () => {await replica?.stop()})+describe('delivery authority dependencies', () => {+ it('refuses a native delivery to another receiver when the terminal agent has a private PM chat', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const group = String((await run(tab, { type: 'conversation.create', title: 'Terminal source', brief: '', checks: [] })).result.conversationId)+ const worker = String((await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Terminal agent', configuration: config, lead: false })).result.agentId)+ const { contextId } = await store.native.open(peer, tab, { operationId: randomUUID(), conversationId: group, agentId: worker })+ const turn = await store.native.append(host, tab, contextId, { turnId: 'private-terminal', kind: 'prompt', previousEventId: null,+ text: 'Typed before the session became private.', truncated: false, interrupted: false }) as { eventId: string }+ const delivery = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: tab, messageId: turn.eventId, agentId: lead } })+ expect(delivery.nativeContextId).toBe(contextId)+ expect(delivery.agentId).not.toBe(worker)+ // An older stored registration can carry privacy through group membership without a confidential mark or a revoked+ // context. Only the terminal agent's groups reveal it; the receiver is the Lead in the public source conversation.+ const state = await storedState(tab)+ expect(state.agents.find(a => a.id === worker)!.confidential).toBeUndefined()+ state.conversations.push({ ...structuredClone(state.conversations.find(c => c.id === group)!), id: randomUUID(), title: 'Private PM chat',+ agentIds: [worker], leadId: null, assignment: null, audience: { people: [{ id: owner.sub, generation: state.people.find(p => p.id === owner.sub)!.generation }] } })+ await saveState(tab, state)+ expect((await db.superTabNativeContext.findUniqueOrThrow({ where: { id: contextId } })).revoked).toBe(false)+ await expect(store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() }))+ .rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ })++ it('refuses an older agent without a project when its private project cannot deliver to an outsider', async () => {+ const { tab, lead } = await fixture()+ const projectId = String((await run(tab, { type: 'project.create', name: 'Private legacy project', visibility: 'private', brief: '' })).result.projectId)+ const group = String((await run(tab, { type: 'conversation.create', projectId, title: 'Legacy source', brief: '', checks: [] })).result.conversationId)+ const sender = String((await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),+ name: 'Legacy sender', configuration: config, lead: false })).result.agentId)+ const state = await storedState(tab)+ const legacy = state.agents.find(a => a.id === sender)!+ delete legacy.projectId+ await saveState(tab, state)+ // A stale cross-project delivery from before migration must not acquire the public receiver's project identity.+ const sent = await run(tab, message('Stale legacy delivery.'))+ const delivery = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: tab, agentId: lead, messageId: sent.result.messageId as string } })+ await db.superTabDelivery.update({ where: { id: delivery.id }, data: { authorKind: 'agent', authorId: sender,+ authorGeneration: legacy.membershipGeneration } })+ await expect(store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() }))+ .rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ })++ it('refuses a claim when its person sender is removed after the authority read', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const sent = await run(tab, message('Sent before removal.'), peer)+ const delivery = await db.superTabDelivery.findFirstOrThrow({ where: { tabId: tab, agentId: lead, messageId: sent.result.messageId as string } })+ let removed = false+ const raced = new SuperTabStore(beforeFirstWrite(db, async () => {+ if (removed) return+ removed = true+ // Remove the authority part independently of delivery cancellation, so only the sender touch can reject a stale+ // authorization decision. The other fixture paths already cover commands cancelling the delivery row itself.+ await swarmTransaction(db, async tx => {+ const member = await tx.swarmMember.findFirstOrThrow({ where: { tabId: tab, key: peer.sub } })+ await guardedWrite(tx, tab, { op: 'remove', kind: 'member', key: peer.sub, seen: member.version,+ data: member.data as unknown as SuperTabState['people'][number] }, parts.clock.next())+ })+ }))+ await expect(raced.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() }))+ .rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })+ expect(removed).toBe(true)+ expect((await db.superTabDelivery.findUniqueOrThrow({ where: { id: delivery.id } })).status).toBe('queued')+ })+})+describe('durable group pull request links', () => {const pr = (number: number) => `https://github.com/example/project/pull/${number}`const links = async (tab: string, groupId = 'lead') => {diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 9e5e2e229..bb0efa72d 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -72,6 +72,36 @@ async function undecidedWork(agents: Part<Agent>[], groups: Part<GroupData>[], lconst toPart = <T>(kind: PartKind, row: PartRow): Part<T> => ({ kind, key: row.key, version: row.version, changedAt: row.changedAt.getTime(),ordinal: row.ordinal, data: row.data as T })+/** Delivery authority only: no machine reports, starts, progress, or unrelated work. Keep the Lead conversations for+ * ledProject, and the named agents' groups for legacy project identity and native-context privacy checks. These projected+ * groups must never be committed as state; a delivery only touches its authority parts and updates its own row. */+export async function loadDeliveryParts(tx: Transaction, tabId: string, groupIds: string[], agentIds: string[], nativeAgentId?: string): 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' })+ const { projects, leadsConversationId } = head.data as unknown as HeadData+ const keys = [...projects ? projects.map(p => p.leadConversationId) : ['lead'], leadsConversationId ?? '']+ const [members, agents] = await Promise.all([+ tx.swarmMember.findMany({ where: { tabId, deleted: false } }),+ tx.swarmAgent.findMany({ where: { tabId, deleted: false } }),+ ])+ // Modern agents carry their project. Older agents derive it from their first loaded group. Native privacy checks+ // additionally inspect every group of the terminal's agent, which need not be the delivery's receiver.+ const related = [...agents.filter(a => agentIds.includes(a.key) && !(a.data as unknown as Agent).projectId).map(a => a.key),+ ...nativeAgentId ? [nativeAgentId] : []]+ // One read per index, like loadLight: an $or spanning key and membership indexes would invoke the query planner again.+ const [named, linked] = await Promise.all([+ groupsBy(tx, 'key', [{ $match: { tabId, deleted: false, key: { $in: [...groupIds, ...keys] },+ $or: [{ dormant: false }, { key: { $in: groupIds } }] } }, { $project: LIGHT_GROUP }]),+ related.length ? groupsBy(tx, 'agents', [{ $match: { tabId, deleted: false, dormant: false,+ agentIds: { $in: related } } }, { $project: LIGHT_GROUP }]) : Promise.resolve([]),+ ])+ const groups = [...new Map([...named, ...linked].map(row => [row.key, lightGroup(row)])).values()]+ return { tabId, head: toPart<HeadData>('head', head as unknown as PartRow),+ members: members.map(row => toPart('member', row)), agents: agents.map(row => toPart('agent', row)),+ groups, machines: [], starts: [], progress: [],+ sequenceBase: head.sequenceBase, visibilityEpoch: head.visibilityEpoch, groupCounter: head.groupCounter } as SwarmParts+}+/*** The live parts of one Swarm with conversations light. Conversations: every active one (`groups: 'active'`, as* `loadActive`), or only the Lead conversations and those with running work (`'working'`: what visibility and deriveddiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex e4b345fb6..7f7073cd9 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -26,6 +26,8 @@ import { archivable, archiveLine, stopIdleWorkers, stoppedMachines } from './tidimport { clock, insertParts, loadActive, reassemble, split, type HeadData, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, withoutHints } from './parts/indexed.js'import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'+import { loadDeliveryParts } from './parts/light.js'+import { guardedWrite } from './parts/write.js'import { touchesFor } from './parts/touches.js'import { freeze, swarmReadCache, swarmTransaction, type CacheView, type SwarmCache } from './cache.js'import { DIRECT, readLastChangedAt, readParts, type ReadNamed } from './cachedReads.js'@@ -2075,10 +2077,17 @@ export class SuperTabStore {action: { type: 'claim'; claimId: string } | { type: 'ack'; claimId: string; receipt: string; uncertain: boolean }| { type: 'hold'; claimId: string; reason: HoldReason }) {return transaction(this.db, async tx => {- const named = await tx.superTabDelivery.findFirst({ where: { id: deliveryId, tabId, agentId }, select: { conversationId: true } })- const loaded = await this.load(tx, user, tabId, { groupIds: named ? [named.conversationId] : [] }), state = loaded.state- author(state, await this.actor(tx, user, state, agentId), true)const delivery = await tx.superTabDelivery.findFirst({ where: { id: deliveryId, tabId, agentId } })+ await this.row(tx, user, tabId)+ // A native message may be delivered to its Lead in a different conversation from the terminal it came from.+ const context = delivery?.nativeContextId ? await tx.superTabNativeContext.findFirst({+ where: { id: delivery.nativeContextId, tabId }, select: { agentId: true } }) : null+ const parts = await loadDeliveryParts(tx, tabId, delivery ? [delivery.conversationId] : [],+ [agentId, ...delivery?.authorKind === 'agent' ? [delivery.authorId] : [], ...context ? [context.agentId] : []], context?.agentId)+ const state = reassemble(parts, { share: true })+ parkLaterConversations(state)+ syncLeads(state)+ author(state, await this.actor(tx, user, state, agentId), true)// The delivery pass ended a hold (it keeps the hold's reason) as its host, its terminal free again, typed it: the// host's own confirmation counts, or the agent has it while its sender sees Not sent and sends it again (review of// #1941). Nothing else brings an ended delivery back.@@ -2098,7 +2107,11 @@ export class SuperTabStore {}// No Swarm-wide write: revocation and group changes write this delivery row, and the claim relies on its receiver and// its sender, whose parts it touches (spec ruling 9, design section 3.5).- await this.save(tx, loaded, state, clock.next(), deliveryTouches(delivery))+ const stamp = clock.next()+ for (const touch of deliveryTouches(delivery)) {+ const part = parts.members.find(p => p.key === touch.key)+ if (part) await guardedWrite(tx, tabId, { op: 'touch', ...touch, seen: part.version }, stamp)+ }const updated = await tx.superTabDelivery.update({ where: { id: delivery.id }, data: { status, claimId: action.claimId,...(action.type === 'ack' ? { receipt: action.receipt, holdReason: null, holdSince: null,...(!action.uncertain ? { deliveredAt: delivery.deliveredAt ?? new Date(this.now()) } : {}) } : {}) } })