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.

Batch E: #2035 #2016 #2030 #2039 #1988 #2034 #1992 #1987 (#2043)

0xken153587268a138c
diff --git a/backend/integration/schemaRelease.test.ts b/backend/integration/schemaRelease.test.ts
new file mode 100644
index 000000000..beac5164e
--- /dev/null
+++ b/backend/integration/schemaRelease.test.ts
@@ -0,0 +1,202 @@
+import { randomUUID } from 'node:crypto'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import { ensureIndex } from '../src/lib/db/indexes.js'
+import { releaseSchema } from '../src/lib/db/schemaRelease.js'
+import { DIRECT, readLight, readParts } from '../src/superTabs/cachedReads.js'
+import * as parts from '../src/superTabs/parts/index.js'
+import { swarm } from '../src/superTabs/read/fixture.test-support.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database; each test has a
+// database of its own. On 10-28 a release's schema step dropped every expiry index Prisma does not describe and the worker
+// built each one again over its whole collection: Swarm reads, whose transactions wait at most 5 ms for a lock, failed on
+// the groups and starts collections. Mongo's profiler shows every command a release sends and the locks each one took.
+let replica: MongoMemoryReplSet
+let folder: string
+const DAY = 86_400
+const SCHEMA = join(process.cwd(), 'prisma/schema.prisma')
+
+/** Every index Prisma cannot describe, as the worker has always made it: collection, name, key, seconds to expiry. */
+const EXPIRY: Array<[string, string, Record<string, number>, number]> = [
+ ...['SwarmHead', 'SwarmGroup', 'SwarmStart', 'SwarmProgress'].map(c => [c, 'part_purge', { purgeAt: 1 }, 0] as [string, string, Record<string, number>, number]),
+ ...['SwarmWorkspace', 'SwarmWorkspaceMember', 'SwarmWorkspaceRemoval'].map(c => [c, 'workspace_purge', { purgeAt: 1 }, 0] as [string, string, Record<string, number>, number]),
+ ['SwarmWorkspaceInvitation', 'workspace_invitation_expiry', { expiresAt: 1 }, 0],
+ ['SuperTabMention', 'mention_expiry', { createdAt: 1 }, 30 * DAY],
+ ['SuperTabTerminalRequest', 'terminal_request_expiry', { createdAt: 1 }, 120],
+ ['product_usage_receipts', 'product_usage_expiry', { expiresAt: 1 }, 0],
+ ['product_usage_totals', 'product_usage_expiry', { dayUtc: 1 }, 396 * DAY],
+ ...['user_daily_presence', 'user_daily_client_presence', 'user_daily_remote_usage', 'user_daily_device_presence', 'machine_daily_presence',
+ 'agent_daily_presence', 'analytics_daily_buckets', 'analytics_daily_machines'].map(c => [c, 'product_usage_expiry', { dayUtc: 1 }, 35 * DAY] as [string, string, Record<string, number>, number]),
+ ['product_usage_activity', 'product_usage_expiry', { expiresAt: 1 }, 0],
+ ['harness_sessions', 'harness_session_expiry', { expiresAt: 1 }, 30 * DAY],
+]
+
+type Profiled = { ts: Date; ns: string; errCode?: number; command?: Record<string, unknown>; locks?: Record<string, { acquireCount?: Record<string, number> }> }
+
+async function database() {
+ const uri = replica.getUri(`schema_release_test_${randomUUID().replaceAll('-', '_')}`)
+ const db = new PrismaClient({ datasources: { db: { url: uri } } })
+ await db.$runCommandRaw({ profile: 2 })
+ return { db, target: { databaseUrl: uri } }
+}
+
+async function profiled(db: PrismaClient, since: Date): Promise<Profiled[]> {
+ const answer = await db.$runCommandRaw({ find: 'system.profile', filter: { ts: { $gt: { $date: since.toISOString() } } }, batchSize: 100_000, singleBatch: true }) as
+ { cursor: { firstBatch: Profiled[] } }
+ return answer.cursor.firstBatch
+}
+
+/** The index changes a release made: index builds, drops and option changes, in order, as `command collection name`. */
+async function indexChanges(db: PrismaClient, since: Date): Promise<string[]> {
+ return (await profiled(db, since)).flatMap(entry => {
+ const command = entry.command ?? {}
+ if (entry.errCode !== undefined) return []
+ if ('createIndexes' in command) return (command.indexes as Array<{ name: string }>).map(i => `createIndexes ${command.createIndexes} ${i.name}`)
+ if ('dropIndexes' in command) return [`dropIndexes ${command.dropIndexes} ${command.index}`]
+ if ('collMod' in command) return [`collMod ${command.collMod} ${(command.index as { name?: string } | undefined)?.name ?? ''}`]
+ return []
+ })
+}
+
+/** Operations that took a database or collection lock in exclusive mode (W), which every other read and write waits behind. */
+async function exclusiveLocks(db: PrismaClient, since: Date): Promise<string[]> {
+ return (await profiled(db, since)).filter(entry => ['Database', 'Collection'].some(resource => entry.locks?.[resource]?.acquireCount?.W))
+ .map(entry => `${Object.keys(entry.command ?? {})[0]} ${entry.ns}`)
+}
+
+async function expiryIndexes(db: PrismaClient): Promise<Array<[string, string, Record<string, number>, number | undefined]>> {
+ const found: Array<[string, string, Record<string, number>, number | undefined]> = []
+ for (const [collection, name] of EXPIRY) {
+ const answer = await db.$runCommandRaw({ listIndexes: collection }) as { cursor: { firstBatch: Array<{ name: string; key: Record<string, number>; expireAfterSeconds?: number }> } }
+ const index = answer.cursor.firstBatch.find(i => i.name === name)
+ if (index) found.push([collection, index.name, index.key, index.expireAfterSeconds])
+ }
+ return found
+}
+
+/** The release's schema with `edit` applied, in a file of its own. */
+async function schemaWith(edit: (schema: string) => string): Promise<string> {
+ const path = join(folder, `${randomUUID()}.prisma`)
+ const schema = await readFile(SCHEMA, 'utf8')
+ const edited = edit(schema)
+ expect(edited).not.toBe(schema)
+ await writeFile(path, edited)
+ return path
+}
+const groupIndex = (line: string) => (schema: string) => schema.replace(' @@index([workFinished, archived, lastActivityAt])\n', ` @@index([workFinished, archived, lastActivityAt])\n ${line}\n`)
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ folder = await mkdtemp(join(tmpdir(), 'schema-release-'))
+})
+afterAll(async () => {
+ await replica?.stop()
+ if (folder) await rm(folder, { recursive: true, force: true })
+})
+
+describe('a release\'s schema step', () => {
+ it('gives a new database every expiry index, each with its time', async () => {
+ const { db, target } = await database()
+ await releaseSchema(db, target)
+ expect(await expiryIndexes(db)).toEqual(EXPIRY)
+ await db.$disconnect()
+ }, 240_000)
+
+ it('changes no index and takes no exclusive lock when the schema has not changed', async () => {
+ const { db, target } = await database()
+ await releaseSchema(db, target)
+ const since = new Date()
+ await releaseSchema(db, target)
+ expect(await indexChanges(db, since)).toEqual([])
+ expect(await exclusiveLocks(db, since)).toEqual([])
+ expect(await expiryIndexes(db)).toEqual(EXPIRY)
+ await db.$disconnect()
+ }, 240_000)
+
+ it('builds only the new index when the schema changed, and drops no expiry index', async () => {
+ const { db, target } = await database()
+ await releaseSchema(db, target)
+ const since = new Date()
+ await releaseSchema(db, { ...target, schema: await schemaWith(groupIndex('@@index([tabId, purgeAt])')) })
+ expect(await indexChanges(db, since)).toEqual(['createIndexes SwarmGroup SwarmGroup_tabId_purgeAt_idx'])
+ // The build's own moment: Mongo builds in the background and locks the collection exclusively only to begin and to finish.
+ expect(await exclusiveLocks(db, since)).toEqual([expect.stringMatching(/^createIndexes \w+\.SwarmGroup$/)])
+ expect(await expiryIndexes(db)).toEqual(EXPIRY)
+ await db.$disconnect()
+ }, 240_000)
+
+ it('gives an expiry index whose time changed its new time, without a rebuild', async () => {
+ const { db, target } = await database()
+ await releaseSchema(db, target)
+ await db.$runCommandRaw({ collMod: 'SuperTabMention', index: { name: 'mention_expiry', expireAfterSeconds: 7 * DAY } })
+ const since = new Date()
+ await releaseSchema(db, target)
+ expect(await indexChanges(db, since)).toEqual(['collMod SuperTabMention mention_expiry'])
+ expect(await expiryIndexes(db)).toEqual(EXPIRY)
+ await db.$disconnect()
+ }, 240_000)
+})
+
+describe('ensureIndex', () => {
+ it('creates the collection and its index when neither exists', async () => {
+ const { db } = await database()
+ await ensureIndex(db, 'not_yet_made', { key: { at: 1 }, name: 'not_yet_made_expiry', expireAfterSeconds: 60 })
+ const answer = await db.$runCommandRaw({ listIndexes: 'not_yet_made' }) as { cursor: { firstBatch: Array<{ name: string; expireAfterSeconds?: number }> } }
+ expect(answer.cursor.firstBatch.map(i => [i.name, i.expireAfterSeconds])).toEqual([['_id_', undefined], ['not_yet_made_expiry', 60]])
+ await db.$disconnect()
+ })
+})
+
+/** Resolves once `ready` holds, checking every 10 ms. */
+async function until(ready: () => boolean | Promise<boolean>): Promise<void> {
+ while (!await ready()) await new Promise(resolve => setTimeout(resolve, 10))
+}
+
+describe('a Swarm read on a cache miss while a release changes an index on its collection', () => {
+ // The 10-28 failure, made certain: a transaction that has read the groups holds its lock until it ends, an index build
+ // queues for its exclusive lock behind it, and every transaction after that waits behind the build. Mongo lets a
+ // transaction wait 5 ms for a lock, so the read's first attempt always fails; the open transaction ends only once the read
+ // has had to try again.
+ for (const [name, read] of [
+ ['reading the active parts', (db: PrismaClient) => readParts(db, DIRECT, 't')],
+ ['a light read', (db: PrismaClient) => readLight(db, DIRECT, 't', {})],
+ ] as const) {
+ it(`${name} waits the lock out instead of failing`, async () => {
+ const { db } = await database()
+ const fixture = swarm(Date.now())
+ fixture.group('Web')
+ await db.$transaction(tx => parts.insertParts(tx, parts.split(fixture.state, { tabId: 't', version: 1, now: Date.now() })))
+ const groups = fixture.state.conversations.map(c => c.id).sort()
+ let release!: () => void, opened!: () => void
+ const held = new Promise<void>(resolve => { release = resolve }), isOpen = new Promise<void>(resolve => { opened = resolve })
+ const open = db.$transaction(async tx => { await tx.swarmGroup.findMany({ where: { tabId: 't' } }); opened(); await held }, { timeout: 60_000 })
+ await isOpen
+ // Prisma sends a query only once it is awaited or given a then.
+ const build = db.$runCommandRaw({ createIndexes: 'SwarmGroup', indexes: [{ key: { tabId: 1, ordinal: 1 }, name: 'built_during_a_read' }] }).then(answer => answer)
+ const admin = new PrismaClient({ datasources: { db: { url: replica.getUri('admin') } } })
+ await until(async () => {
+ const ops = await admin.$runCommandRaw({ aggregate: 1, pipeline: [{ $currentOp: {} }, { $match: { 'command.createIndexes': 'SwarmGroup', waitingForLock: true } }], cursor: {} }) as
+ { cursor: { firstBatch: unknown[] } }
+ return ops.cursor.firstBatch.length > 0
+ })
+ await admin.$disconnect()
+ let attempts = 0
+ const counting = new Proxy(db, { get: (target, key, receiver) => key === '$transaction'
+ ? (...args: Parameters<PrismaClient['$transaction']>) => { attempts++; return (target.$transaction as (...a: unknown[]) => unknown)(...args) }
+ : Reflect.get(target, key, receiver) })
+ let settled = false
+ const reading = read(counting).finally(() => { settled = true })
+ await until(() => attempts >= 2 || settled)
+ release()
+ await Promise.all([open, build])
+ expect((await reading).groups.map(g => g.key).sort()).toEqual(groups)
+ expect(attempts).toBeGreaterThanOrEqual(2)
+ await db.$disconnect()
+ }, 60_000)
+ }
+})
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
new file mode 100644
index 000000000..d0a2a3a25
--- /dev/null
+++ b/backend/integration/superTabBuddies.test.ts
@@ -0,0 +1,110 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+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 type { Command } from '../src/superTabs/commands.js'
+import { poolRows } from './hostRows.test-support.js'
+
+// Buddies end to end through the store (buddies.ts): a person adds one on their own Swarm machine, its host starts it, they
+// talk to it alone, and it sends their proposal to the PM. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '300000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const peer: AuthUser = { sub: '300000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_buddies_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const user of [owner, peer]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })
+ for (const [machineId, user] of [['owner-mac', owner], ['peer-mac', peer]] as const) {
+ await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ }
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm whose PM runs on the owner's Mac, peer a member with their own Mac in the Machines list, and Buddies on. */
+async function swarm() {
+ const store = new SuperTabStore(db, () => Date.now())
+ const tab = (await store.create(owner, randomUUID(), 'Buddies', 'public')).id
+ const execute = (command: Command, user = owner, asAgentId?: string, hostMachineId?: string) =>
+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId)
+ const invitation = await execute({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
+ const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(), name: 'PM',
+ configuration: config, lead: true })).result.agentId)
+ await execute({ type: 'machine.contribute', machineId: 'peer-mac', name: 'Peer Mac', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 2 }, peer)
+ const generation = (await poolRows(store, peer, 'peer-mac')).find(p => p.tabId === tab)!.machine.generation
+ await store.observeMachine(peer, tab, 'peer-mac', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })
+ await execute({ type: 'tab.buddies', enabled: true })
+ return { store, tab, execute, lead }
+}
+
+/** peer's Buddy, added and started by peer-mac's host as a running host does. */
+async function buddy(f: Awaited<ReturnType<typeof swarm>>) {
+ const added = await f.execute({ type: 'buddy.create', projectId: 'lead', machineId: 'peer-mac', engine: 'claude' }, peer)
+ const startId = String(added.result.startId), chat = String(added.result.conversationId)
+ const pool = (await poolRows(f.store, peer, 'peer-mac')).find(p => p.tabId === f.tab)!
+ const host = (command: Command) => f.execute(command, peer, undefined, 'peer-mac')
+ await host({ type: 'agent.startDispatch', startId })
+ const agentId = String((await host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)
+ await host({ type: 'agent.startSettled', startId, warning: null })
+ return { chat, agentId, pool }
+}
+
+describe('a Buddy through the store', () => {
+ it('starts on its owner\'s machine from a list older hosts do not read, and joins its owner\'s chat', async () => {
+ const f = await swarm()
+ const { chat, agentId, pool } = await buddy(f)
+ expect(pool.starts).toEqual([])
+ expect(pool.buddyStarts).toHaveLength(1)
+ const read = await f.store.read(peer, f.tab)
+ expect(read.state.agents.find(a => a.id === agentId)).toMatchObject({ buddyOf: { personId: peer.sub } })
+ const messages = await f.store.messages(peer, f.tab, chat, {})
+ expect(messages.messages.map(m => m.text)).toEqual(['peer\'s Buddy is ready. Tell it what you have in mind.'])
+ })
+
+ it('is read by its owner and its Buddy alone: neither the Swarm owner nor the PM reads its chat', async () => {
+ const f = await swarm()
+ const { chat, agentId } = await buddy(f)
+ await f.execute({ type: 'message.send', conversationId: chat, text: 'A private idea', replyTo: null, recipientIds: [] }, peer)
+ const delivered = await db.superTabDelivery.findMany({ where: { tabId: f.tab, conversationId: chat } })
+ expect(delivered.map(d => d.agentId)).toEqual([agentId])
+ expect((await f.store.messages(peer, f.tab, chat, {}, agentId)).messages.map(m => m.text)).toContain('A private idea')
+ await expect(f.store.messages(owner, f.tab, chat, {})).rejects.toThrow('unavailable')
+ await expect(f.store.messages(owner, f.tab, chat, {}, f.lead)).rejects.toThrow('unavailable')
+ expect((await f.store.read(owner, f.tab)).state.conversations.map(c => c.id)).not.toContain(chat)
+ })
+
+ it('sends its owner\'s proposal to the PM in the project chat, once per ask', async () => {
+ const f = await swarm()
+ const { chat, agentId } = await buddy(f)
+ const ask = String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Send it to the PM', replyTo: null, recipientIds: [] }, peer)).result.messageId)
+ const propose = () => f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, goal: 'Offline sync', scope: 'Desktop only',
+ priority: 'normal' }, peer, agentId)
+ const sent = await propose()
+ const row = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: String(sent.result.messageId) } })
+ expect(row).toMatchObject({ conversationId: 'lead', recipientIds: [f.lead], source: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: ask },
+ text: 'Proposal from peer\'s Buddy, on peer\'s behalf.\n\nGoal: Offline sync\nScope: Desktop only\nPriority: normal' })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: row.id, agentId: f.lead } })).toBe(1)
+ await expect(propose()).rejects.toThrow('already sent')
+ await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: 'Hi PM', replyTo: null, recipientIds: [] }, peer, agentId))
+ .rejects.toThrow('A Buddy posts only in its own chat')
+ })
+})
diff --git a/backend/integration/superTabHotReads.test.ts b/backend/integration/superTabHotReads.test.ts
index cd92abe4b..62f8f4464 100644
--- a/backend/integration/superTabHotReads.test.ts
+++ b/backend/integration/superTabHotReads.test.ts
@@ -12,6 +12,7 @@ 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'
+import { SwarmReads } from '../src/superTabs/read/service.js'
import { cursorFor } from '../src/superTabs/read/cursor.js'
import { lastChangedAt } from '../src/superTabs/parts/index.js'
import type { SuperTabState } from '../src/superTabs/model.js'
@@ -229,3 +230,35 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {
expect(scans.map(e => `${e.ns.slice(e.ns.indexOf('.') + 1)} ${queryShape((e.command?.pipeline as Array<{ $match?: unknown }> | undefined)?.[0]?.$match ?? e.command?.filter ?? e.command?.q)}`)).toEqual([])
})
})
+
+// Diego's backend review, item 5 (2026-10-28): which machines are signed in as a team account is the same answer for every
+// reader, and machines report every 15 s, so the read API asks for it at most once per 15 s per Swarm and machine list.
+describe('which machines take teammates\' work is read once per 15 s per Swarm', () => {
+ it('two polls within 15 s read the team machines once; a machine turning team shows 15 s after the read', async () => {
+ const s = await scene()
+ const swarmReads = new SwarmReads(store, { now: () => clock })
+ const teamReads = (entries: ProfileEntry[]) => reads(entries, 'machines', ['machineId', 'sessionKind'])
+ const teamWork = (read: { derived: { machines: Record<string, { teamWork: unknown }> } }) => read.derived.machines[s.machineId]!.teamWork
+ clock = Date.now()
+ const readAt = clock
+ let cursor = ''
+ const within = await profiled(async () => {
+ const first = await swarmReads.firstLoad(owner, s.tabId)
+ expect(teamWork(first)).toEqual({ allowed: true })
+ clock += 3_000
+ cursor = (await swarmReads.changes(owner, s.tabId, first.cursor)).cursor
+ // The machine's account turns team: a team machine that never reported is offline for teammates' work.
+ await db.machine.update({ where: { machineId: s.machineId }, data: { sessionKind: 'team' } })
+ clock += 3_000
+ const polled = await swarmReads.changes(owner, s.tabId, cursor)
+ expect(teamWork(polled)).toEqual({ allowed: true })
+ cursor = polled.cursor
+ })
+ expect(teamReads(within)).toHaveLength(1)
+ clock = readAt + 15_000
+ const later = await profiled(async () => {
+ expect(teamWork(await swarmReads.changes(owner, s.tabId, cursor))).toMatchObject({ allowed: false, code: 'MACHINE_OFFLINE' })
+ })
+ expect(teamReads(later)).toHaveLength(1)
+ })
+})
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 92b4062e5..641338248 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -253,6 +253,76 @@ describe('work that loses its owner', () => {
messageId: stableId('work-lost', f.assignmentId, String(f.clock.now), 'agent') } })).toBe(1)
})
+ // One duplicate stopped every later report and poll for 45 minutes that day. A notice of the time checks found already
+ // stored as that same notice is kept, and its missing deliveries are written, so its recipients still receive it.
+ describe('a lost notice already stored', () => {
+ const lostIds = (f: Awaited<ReturnType<typeof swarm>>) =>
+ ({ lead: stableId('work-lost', f.assignmentId, String(f.clock.now)), agent: stableId('work-lost', f.assignmentId, String(f.clock.now), 'agent') })
+ const STOPPED = 'its session on Worker Mac stopped'
+ /** Stores `text` under `id` as the loss notice the time checks write for this task, or as one with `source` changed. */
+ const store = (f: Awaited<ReturnType<typeof swarm>>, id: string, text: string,
+ { conversationId = f.group, source = {} }: { conversationId?: string; source?: Record<string, unknown> } = {}) => db.superTabMessage.create({ data: { id,
+ tabId: f.tab, conversationId, sequence: 1, author: { kind: 'agent', id: f.lead },
+ source: { kind: 'work-lost', agentId: f.worker, assignmentId: f.assignmentId, reason: STOPPED, ...source },
+ text, replyTo: null, recipientIds: [], mentions: [] } })
+
+ it('is kept on its machine\'s report, and the Lead and the worker still receive it', async () => {
+ const f = await swarm()
+ f.clock.now += MINUTE
+ const ids = lostIds(f)
+ await store(f, ids.lead, 'Stored for the Lead')
+ await store(f, ids.agent, 'Stored for the worker')
+ await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })
+ expect(await f.assignment()).toMatchObject({ status: 'lost', lost: { reason: 'its session on Worker Mac stopped' } })
+ expect((await f.leadInbox()).map(m => m.text)).toContain('Stored for the Lead')
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: f.worker, messageId: ids.agent } })).toBe(1)
+ })
+
+ it('is kept on its Lead\'s poll, and the Lead receives it', async () => {
+ const f = await swarm()
+ await f.observe('test-host', [f.harness.worker])
+ f.clock.now += 3 * MINUTE
+ await store(f, lostIds(f).lead, 'Stored for the Lead', { source: { reason: 'its machine Worker Mac has been offline for 2 minutes' } })
+ expect((await f.leadInbox()).map(m => m.text)).toContain('Stored for the Lead')
+ expect(await f.assignment()).toMatchObject({ status: 'lost' })
+ })
+
+ it('gets no second delivery when its delivery is stored too', async () => {
+ const f = await swarm()
+ f.clock.now += MINUTE
+ const ids = lostIds(f)
+ await store(f, ids.lead, 'Stored for the Lead')
+ await db.superTabDelivery.create({ data: { id: stableId(ids.lead, f.lead), tabId: f.tab, conversationId: f.group, messageId: ids.lead, agentId: f.lead,
+ machineId: 'lead-host', machineOwnerId: host.sub, assignmentId: null, membershipGeneration: 'g', authorKind: 'agent', authorId: f.lead, authorGeneration: 'g' } })
+ await f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })
+ expect(await f.assignment()).toMatchObject({ status: 'lost' })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: ids.lead } })).toBe(1)
+ })
+
+ it('still refuses a stored message that is not this notice', async () => {
+ const f = await swarm()
+ f.clock.now += MINUTE
+ await store(f, lostIds(f).lead, 'Another message', { conversationId: 'lead' })
+ await expect(f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })).rejects.toThrow('Unique constraint failed')
+ expect(await f.assignment()).toMatchObject({ status: 'working' })
+ })
+
+ // Review of #2034: a loss notice of another task, or of another worker, is not this loss; kept, it would be delivered as it.
+ it.each([
+ ['another task', { assignmentId: 'another-assignment' }],
+ ['another worker', { agentId: 'another-agent' }],
+ ['another reason', { reason: 'it hit a usage limit until 12:00 UTC' }],
+ ])('still refuses a stored loss notice of %s, and delivers nothing', async (_, source) => {
+ const f = await swarm()
+ f.clock.now += MINUTE
+ const ids = lostIds(f)
+ await store(f, ids.lead, 'Another loss', { source })
+ await expect(f.observe('test-host', [], { stoppedHarnessIds: [f.harness.worker] })).rejects.toThrow('Unique constraint failed')
+ expect(await f.assignment()).toMatchObject({ status: 'working' })
+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, messageId: { in: [ids.lead, ids.agent] } } })).toBe(0)
+ })
+ })
+
// #1757 review, 2: a receipt replays the first answer, so it never says who holds the task now; the host's assignment
// rows do (cli superTabs/limitResume.ts reads them before typing).
it('replays a resume whose answer was lost even after a takeover, while its host\'s assignment rows no longer list it', async () => {
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 91f476e28..01f1e4e26 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -552,6 +552,8 @@ model ProductUsageTotal {
@@unique([dayUtc, metric])
@@map("product_usage_totals")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Random report receipt, used only to prevent retries counting twice. No identity or report body.
@@ -560,6 +562,8 @@ model ProductUsageReceipt {
expiresAt DateTime
@@map("product_usage_receipts")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([expiresAt], map: "product_usage_expiry")
}
/// One UTC day a person used Harness while sharing product usage, under a keyed pseudonym
@@ -577,6 +581,8 @@ model ProductUsageActivity {
@@unique([subject, dayUtc])
@@map("product_usage_activity")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([expiresAt], map: "product_usage_expiry")
}
/// Legacy individual counters. New ingestion is disabled; dayUtc TTL removes these after 35 days.
@@ -605,6 +611,8 @@ model AnalyticsDailyBucket {
@@unique([userId, machineId, dayUtc, engine, mode, origin, schemaVersion])
@@index([userId, dayUtc])
@@map("analytics_daily_buckets")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Legacy, no longer written. Retained only until the 35-day dayUtc expiry.
@@ -626,6 +634,8 @@ model AnalyticsDailyMachine {
@@unique([userId, machineId, dayUtc])
@@index([userId, dayUtc])
@@map("analytics_daily_machines")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Harness Analytics — per-machine collector control and coverage state. Backs the Coverage panel
@@ -689,6 +699,8 @@ model UserDailyPresence {
@@unique([userId, machineId, dayUtc])
@@index([userId, dayUtc])
@@map("user_daily_presence")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Per-day record of a user on a surface other than the desktop app — `UserDailyPresence` stays the
@@ -714,6 +726,8 @@ model UserDailyClientPresence {
@@unique([userId, surface, dayUtc])
@@index([surface, dayUtc])
@@map("user_daily_client_presence")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Per-day record of whether a user actually established a remote p2p connection to stream a
@@ -732,6 +746,8 @@ model UserDailyRemoteUsage {
@@unique([userId, machineId, dayUtc])
@@index([userId, dayUtc])
@@map("user_daily_remote_usage")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Per-day record of whether a user's device was connected to the device-ws relay
@@ -757,6 +773,8 @@ model UserDailyDevicePresence {
@@unique([userId, deviceId, dayUtc])
@@index([userId, dayUtc])
@@map("user_daily_device_presence")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Per-day record of whether a MACHINE's `harness` daemon was connected to the adapter-ws relay
@@ -783,6 +801,8 @@ model MachineDailyPresence {
@@unique([machineId, dayUtc])
@@index([userId, dayUtc])
@@map("machine_daily_presence")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// Per-day record of an AGENT being driven: one row per (machine, agent, UTC day), created and
@@ -806,6 +826,8 @@ model AgentDailyPresence {
@@index([machineId, dayUtc])
@@index([userId, dayUtc])
@@map("agent_daily_presence")
+ /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
+ @@index([dayUtc], map: "product_usage_expiry")
}
/// One person's review of one harness in the Harness Store — a star rating and, optionally, a title
@@ -1085,6 +1107,8 @@ model SuperTabMention {
@@index([tabId, personId, createdAt])
@@index([tabId, conversationId, personId])
+ /// A tag goes 30 days on (superTabs/mentions.ts ensureMentionExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([createdAt], map: "mention_expiry")
}
/// One reactor's emoji on one message (superTabs/reactions.ts). The id is derived from all four, so adding the same
@@ -1340,6 +1364,8 @@ model SuperTabTerminalRequest {
@@index([machineId, status])
@@index([tabId, createdAt])
+ /// An unread answer goes after two minutes (superTabs/terminal.ts ensureTerminalExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([createdAt], map: "terminal_request_expiry")
}
// Swarm state by parts (docs/design/2026-10-26-swarm-state-parts.md). Each part is one record of a Swarm, written only
@@ -1359,6 +1385,9 @@ model SwarmWorkspace {
createdAt DateTime @default(now())
deletedAt DateTime?
purgeAt DateTime?
+
+ /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([purgeAt], map: "workspace_purge")
}
/// One person of a Workspace. A removal keeps the row with `removedAt` until it is purged; a rejoin writes a new generation.
@@ -1379,6 +1408,8 @@ model SwarmWorkspaceMember {
@@index([workspaceId, removedAt])
@@index([userId, removedAt])
+ /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([purgeAt], map: "workspace_purge")
}
/// One removal of one Workspace membership, open until the person has left every Swarm of the Workspace. While one is open the
@@ -1398,6 +1429,8 @@ model SwarmWorkspaceRemoval {
@@index([finishedAt, id])
@@index([workspaceId, userId, finishedAt])
+ /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([purgeAt], map: "workspace_purge")
}
/// An invitation to a Workspace, by email; deleted when accepted or revoked, purged when it expires.
@@ -1412,6 +1445,8 @@ model SwarmWorkspaceInvitation {
@@index([email, expiresAt])
@@index([workspaceId])
+ /// An invitation goes when it expires (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([expiresAt], map: "workspace_invitation_expiry")
}
model SwarmHead {
@@ -1433,6 +1468,8 @@ model SwarmHead {
@@unique([tabId, key])
@@index([tabId, 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")
}
/// One person in the Swarm. Every command of theirs touches it, so removing them and their in-flight action cannot both win.
@@ -1496,6 +1533,8 @@ model SwarmGroup {
@@index([tabId, executionMachineId])
/// The host signature (read/host.ts inputs) reads every conversation's digest and dormancy from this index alone.
@@index([tabId, deleted, key, hostDigest, dormant])
+ /// 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")
}
model SwarmAgent {
@@ -1570,6 +1609,8 @@ model SwarmStart {
@@index([tabId, finishedAt])
@@index([machineId, finishedAt])
@@index([tabId, agentId])
+ /// 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")
}
/// One project's report watermark, and the fence a Lead's worker decisions serialize on.
@@ -1586,6 +1627,8 @@ model SwarmProgress {
@@unique([tabId, key])
@@index([tabId, 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")
}
model ExperimentalSettings {
@@ -1686,6 +1729,8 @@ model HarnessSession {
@@index([userId])
@@map("harness_sessions")
+ /// Ended and idle-expired sessions go 30 days on (lib/ssoSession.ts ensureHarnessSessionExpiry). Declared so db push keeps the index; the worker sets its expiry.
+ @@index([expiresAt], map: "harness_session_expiry")
}
/// One entry of an account's device key log (lib/deviceKeyLog.ts): the identity keys its machines and
diff --git a/backend/scripts/schema-release/measure.ts b/backend/scripts/schema-release/measure.ts
new file mode 100644
index 000000000..d4185bbb2
--- /dev/null
+++ b/backend/scripts/schema-release/measure.ts
@@ -0,0 +1,193 @@
+/**
+ * What a release's schema step does to Swarm reads, on a local Mongo only (a loopback replica set created here; it never reads
+ * DATABASE_URL). Each scenario starts from a database shaped like production before the release: `--from` pushed and every
+ * expiry index made by hand, as the worker always has, with `--groups` Swarm groups and `--starts` starts. While the step
+ * runs, `--readers` loops read groups and starts in transactions, as a Swarm read does on a cache miss; Mongo lets a
+ * transaction wait at most 5 ms for a lock. Reports each scenario's reads, failures and latency, and every index change with
+ * the exclusive lock it took.
+ *
+ * NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=<any 32-byte base64> DATABASE_URL=mongodb://127.0.0.1:1/unused \
+ * npx tsx scripts/schema-release/measure.ts --from OLD.prisma --to NEW.prisma [--groups 50000] [--starts 50000] [--readers 16] \
+ * [--retry] [--lock-wait-ms N] [--out REPORT.md]
+ *
+ * The environment only satisfies the backend's config check. `--retry`: reads retry transient failures as the store's
+ * transaction() does. `--lock-wait-ms`: how long Mongo lets a transaction wait for a lock (its default is 5).
+ *
+ * Scenarios: the step as it was (db push of --to without the expiry indexes, then every expiry index built again), this
+ * step's first release (--to with them declared), and the release after it with nothing changed.
+ */
+import { randomUUID } from 'node:crypto'
+import { readFile, writeFile, mkdtemp, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { parseArgs } from 'node:util'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import { ensureSchema } from '../../src/lib/db/migrate.js'
+import { releaseSchema } from '../../src/lib/db/schemaRelease.js'
+
+const { values } = parseArgs({ options: { from: { type: 'string' }, to: { type: 'string' }, groups: { type: 'string', default: '50000' },
+ starts: { type: 'string', default: '50000' }, readers: { type: 'string', default: '16' }, swarms: { type: 'string', default: '200' },
+ retry: { type: 'boolean', default: false }, 'lock-wait-ms': { type: 'string' }, out: { type: 'string' } } })
+if (!values.from || !values.to) throw new Error('--from and --to name the schemas before and after the release')
+const GROUPS = Number(values.groups), STARTS = Number(values.starts), READERS = Number(values.readers), SWARMS = Number(values.swarms)
+const DAY = 86_400
+
+/** The worker's hand-made indexes, as it made them before this change. */
+const HAND_MADE: Array<[string, Record<string, unknown>]> = [
+ ['product_usage_preferences', { key: { userId: 1 }, name: 'product_usage_preferences_userId_key', unique: true }],
+ ['product_usage_totals', { key: { dayUtc: 1, metric: 1 }, name: 'product_usage_totals_dayUtc_metric_key', unique: true }],
+ ['product_usage_receipts', { key: { expiresAt: 1 }, name: 'product_usage_expiry', expireAfterSeconds: 0 }],
+ ['product_usage_totals', { key: { dayUtc: 1 }, name: 'product_usage_expiry', expireAfterSeconds: 396 * DAY }],
+ ...['user_daily_presence', 'user_daily_client_presence', 'user_daily_remote_usage', 'user_daily_device_presence', 'machine_daily_presence',
+ 'agent_daily_presence', 'analytics_daily_buckets', 'analytics_daily_machines']
+ .map(c => [c, { key: { dayUtc: 1 }, name: 'product_usage_expiry', expireAfterSeconds: 35 * DAY }] as [string, Record<string, unknown>]),
+ ['product_usage_activity', { key: { expiresAt: 1 }, name: 'product_usage_expiry', expireAfterSeconds: 0 }],
+ ['product_usage_activity', { key: { subject: 1, dayUtc: 1 }, name: 'product_usage_activity_subject_dayUtc_key', unique: true }],
+ ['harness_sessions', { key: { expiresAt: 1 }, name: 'harness_session_expiry', expireAfterSeconds: 30 * DAY }],
+ ['SuperTabTerminalRequest', { key: { createdAt: 1 }, name: 'terminal_request_expiry', expireAfterSeconds: 120 }],
+ ['SuperTabMention', { key: { createdAt: 1 }, name: 'mention_expiry', expireAfterSeconds: 30 * DAY }],
+ ...['SwarmHead', 'SwarmGroup', 'SwarmStart', 'SwarmProgress'].map(c => [c, { key: { purgeAt: 1 }, name: 'part_purge', expireAfterSeconds: 0 }] as [string, Record<string, unknown>]),
+ ...['SwarmWorkspace', 'SwarmWorkspaceMember', 'SwarmWorkspaceRemoval']
+ .map(c => [c, { key: { purgeAt: 1 }, name: 'workspace_purge', expireAfterSeconds: 0 }] as [string, Record<string, unknown>]),
+ ['SwarmWorkspaceInvitation', { key: { expiresAt: 1 }, name: 'workspace_invitation_expiry', expireAfterSeconds: 0 }],
+]
+
+async function buildHandMade(db: PrismaClient): Promise<void> {
+ for (const [collection, index] of HAND_MADE) await db.$runCommandRaw({ createIndexes: collection, indexes: [index as never] })
+}
+
+/** The step before this change: push, then build every hand-made index again (the push has just dropped them). */
+async function oldStep(db: PrismaClient, schema: string, databaseUrl: string): Promise<void> {
+ await ensureSchema({ schema, databaseUrl })
+ await buildHandMade(db)
+}
+
+const payload = 'x'.repeat(1200)
+async function seed(db: PrismaClient): Promise<void> {
+ const at = new Date('2026-10-28T08:00:00Z')
+ for (let i = 0; i < GROUPS; i += 5000) {
+ const rows = Array.from({ length: Math.min(5000, GROUPS - i) }, (_, j) => {
+ const n = i + j, tabId = `tab-${n % SWARMS}`
+ return { _id: `${tabId}:g${n}`, tabId, key: `g${n}`, version: 1, changedAt: { $date: at.toISOString() }, deleted: false, ordinal: n, projectId: `p${n % 7}`,
+ kind: null, archived: false, dormant: n % 3 === 0, agentIds: [`a${n % 50}`], messageSeq: n % 100, reportSeq: 0, workFinished: n % 2 === 0,
+ lastActivityAt: { $date: new Date(at.getTime() - n * 1000).toISOString() }, hostMachineIds: [], data: { title: `Group ${n}`, brief: payload } }
+ })
+ await db.$runCommandRaw({ insert: 'SwarmGroup', documents: rows as never })
+ }
+ for (let i = 0; i < STARTS; i += 5000) {
+ const rows = Array.from({ length: Math.min(5000, STARTS - i) }, (_, j) => {
+ const n = i + j, tabId = `tab-${n % SWARMS}`
+ return { _id: `${tabId}:s${n}`, tabId, key: `s${n}`, version: 1, changedAt: { $date: at.toISOString() }, deleted: false, ordinal: n,
+ machineId: `m${n % 20}`, agentId: `a${n % 50}`, data: { request: payload } }
+ })
+ await db.$runCommandRaw({ insert: 'SwarmStart', documents: rows as never })
+ }
+}
+
+interface Reads { ok: number; failed: Record<string, number>; latencies: number[] }
+/** Swarm reads on a cache miss: one transaction reads a Swarm's groups and starts. */
+function startReaders(db: PrismaClient): { stop(): Promise<Reads> } {
+ const reads: Reads = { ok: 0, failed: {}, latencies: [] }
+ let running = true
+ const loops = Array.from({ length: READERS }, async (_, reader) => {
+ for (let n = 0; running; n++) {
+ const tabId = `tab-${(reader * 31 + n) % SWARMS}`, began = performance.now()
+ try {
+ // With --retry, as the store's transaction() does: a transient failure is tried again, up to 8 times, after a jittered backoff.
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await db.$transaction(async tx => {
+ await tx.swarmGroup.findMany({ where: { tabId, dormant: false }, select: { id: true, version: true }, take: 200 })
+ await tx.swarmStart.findMany({ where: { tabId }, select: { id: true, version: true }, take: 200 })
+ })
+ break
+ } catch (error) {
+ if (!values.retry || attempt >= 8 || !String((error as Error).message).includes('TransientTransactionError')) throw error
+ await new Promise(resolve => setTimeout(resolve, Math.random() * Math.min(1000, 50 * 2 ** (attempt - 1))))
+ }
+ }
+ reads.ok++
+ } catch (error) {
+ const text = error instanceof Error ? error.message : String(error)
+ const kind = /LockTimeout|Unable to acquire/i.test(text) ? 'lock timeout' : text.split('\n').find(line => line.trim())?.slice(0, 120) ?? 'unknown'
+ reads.failed[kind] = (reads.failed[kind] ?? 0) + 1
+ }
+ reads.latencies.push(performance.now() - began)
+ }
+ })
+ return { async stop() { running = false; await Promise.all(loops); return reads } }
+}
+
+const percentile = (sorted: number[], p: number) => sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))] : 0
+
+const INDEX_CHANGES = { $or: [{ 'command.createIndexes': { $exists: true } }, { 'command.dropIndexes': { $exists: true } }, { 'command.collMod': { $exists: true } }] }
+type Profiled = { command?: Record<string, unknown>; millis?: number; errCode?: number; locks?: Record<string, { acquireCount?: Record<string, number>; timeAcquiringMicros?: Record<string, number> }> }
+async function indexChanges(db: PrismaClient): Promise<string[]> {
+ const answer = await db.$runCommandRaw({ find: 'system.profile', filter: INDEX_CHANGES, batchSize: 10_000, singleBatch: true }) as { cursor: { firstBatch: Profiled[] } }
+ return answer.cursor.firstBatch.filter(entry => entry.errCode === undefined).map(entry => {
+ const command = entry.command!, name = Object.keys(command)[0]
+ const index = name === 'createIndexes' ? (command.indexes as Array<{ name: string }>).map(i => i.name).join(',') : name === 'dropIndexes' ? command.index : (command.index as { name?: string })?.name
+ const exclusive = entry.locks?.Collection?.acquireCount?.W ? `, exclusive lock, waited ${((entry.locks.Collection.timeAcquiringMicros?.W ?? 0) / 1000).toFixed(1)} ms for it` : ''
+ return `${name} ${command[name]} ${index}: ${entry.millis} ms${exclusive}`
+ })
+}
+
+async function scenario(replica: MongoMemoryReplSet, label: string, from: string, step: (db: PrismaClient, databaseUrl: string) => Promise<void>,
+ before?: (db: PrismaClient, databaseUrl: string) => Promise<void>) {
+ const databaseUrl = replica.getUri(`schema_release_measure_${randomUUID().replaceAll('-', '_')}`)
+ const db = new PrismaClient({ datasources: { db: { url: databaseUrl } } })
+ await ensureSchema({ schema: from, databaseUrl })
+ await buildHandMade(db)
+ await seed(db)
+ if (before) await before(db, databaseUrl)
+ // Only index changes: Prisma's reads are commands too, and would push them out of the profiler's capped collection.
+ await db.$runCommandRaw({ profile: 1, filter: INDEX_CHANGES })
+ const readers = startReaders(db)
+ await new Promise(resolve => setTimeout(resolve, 2000))
+ const began = performance.now()
+ await step(db, databaseUrl)
+ const took = performance.now() - began
+ await new Promise(resolve => setTimeout(resolve, 1000))
+ const reads = await readers.stop()
+ await db.$runCommandRaw({ profile: 0 })
+ const changes = await indexChanges(db)
+ const sorted = [...reads.latencies].sort((a, b) => a - b)
+ await db.$disconnect()
+ return [`## ${label}`, '', `Step: ${(took / 1000).toFixed(1)} s. Reads: ${reads.ok} ok, ${Object.values(reads.failed).reduce((a, b) => a + b, 0)} failed` +
+ `${Object.keys(reads.failed).length ? ` (${Object.entries(reads.failed).map(([k, v]) => `${v} ${k}`).join('; ')})` : ''}. ` +
+ `Latency p50 ${percentile(sorted, 0.5).toFixed(1)} ms, p99 ${percentile(sorted, 0.99).toFixed(1)} ms, max ${(sorted.at(-1) ?? 0).toFixed(1)} ms.`, '',
+ `Index changes (${changes.length}):`, ...changes.map(c => `- ${c}`), ''].join('\n')
+}
+
+const folder = await mkdtemp(join(tmpdir(), 'schema-release-measure-'))
+const replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ instanceOpts: [{ launchTimeout: 60_000 }], replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+const LOCK_WAIT_MS = values['lock-wait-ms'] === undefined ? null : Number(values['lock-wait-ms'])
+if (LOCK_WAIT_MS !== null) {
+ const admin = new PrismaClient({ datasources: { db: { url: replica.getUri('admin') } } })
+ await admin.$runCommandRaw({ setParameter: 1, maxTransactionLockRequestTimeoutMillis: LOCK_WAIT_MS })
+ await admin.$disconnect()
+}
+try {
+ // The step as it was carries the schema without the declared expiry indexes, as the code before this change did.
+ const undeclared = join(folder, 'undeclared.prisma')
+ const declared = /^ *\/\/\/[^\n]*Declared so db push keeps[^\n]*\n *@@index\(\[\w+\], map: "\w+"\)\n/gm
+ const target = await readFile(values.to, 'utf8')
+ if ((target.match(declared) ?? []).length !== 22) throw new Error(`--to declares ${(target.match(declared) ?? []).length} expiry indexes, not 22`)
+ await writeFile(undeclared, target.replace(declared, ''))
+ const reports = [
+ `# Schema step under Swarm reads: ${GROUPS} groups, ${STARTS} starts in ${SWARMS} Swarms, ${READERS} readers` +
+ `${values.retry ? ', reads retry transient failures' : ''}, transactions wait ${LOCK_WAIT_MS ?? 5} ms for a lock`, '',
+ await scenario(replica, 'Before this change: a release carrying the new indexes', values.from, (db, url) => oldStep(db, undeclared, url)),
+ await scenario(replica, 'This change, first release: the new indexes, expiry indexes declared', values.from, (db, url) => releaseSchema(db, { schema: values.to, databaseUrl: url })),
+ await scenario(replica, 'This change, next release with nothing changed', values.from, (db, url) => releaseSchema(db, { schema: values.to, databaseUrl: url }),
+ (db, url) => releaseSchema(db, { schema: values.to, databaseUrl: url })),
+ ]
+ // Prisma's own output goes to stdout as it pushes; --out keeps the report apart from it.
+ if (values.out) await writeFile(values.out, reports.join('\n'))
+ else process.stdout.write(reports.join('\n'))
+} finally {
+ await replica.stop()
+ await rm(folder, { recursive: true, force: true })
+}
diff --git a/backend/src/lib/db/indexes.ts b/backend/src/lib/db/indexes.ts
new file mode 100644
index 000000000..22c5028c3
--- /dev/null
+++ b/backend/src/lib/db/indexes.ts
@@ -0,0 +1,34 @@
+import type { PrismaClient } from '@prisma/client'
+
+/** One index as `createIndexes` takes it. */
+export type IndexSpec = { name: string; key: Record<string, number>; unique?: boolean; expireAfterSeconds?: number }
+
+async function listIndexes(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string): Promise<IndexSpec[]> {
+ try {
+ const answer = await db.$runCommandRaw({ listIndexes: collection, cursor: {} }) as { cursor?: { firstBatch?: IndexSpec[] } }
+ return answer.cursor?.firstBatch ?? []
+ } catch {
+ // A collection that does not exist yet has no indexes; createIndexes creates it, and reports any real failure.
+ return []
+ }
+}
+
+const sameKey = (a: Record<string, number>, b: Record<string, number>) => JSON.stringify(Object.entries(a)) === JSON.stringify(Object.entries(b))
+
+/**
+ * Makes sure `collection` has `index`, and changes nothing when it already does. A build, a drop or an option change locks
+ * the collection exclusively for a moment, and a Swarm read's transaction waits at most 5 ms for its lock (the 10-28 release);
+ * listing the indexes takes no lock that reads or writes wait for. An index Prisma declares without expiry (db push builds it
+ * so on a new database) gets its expiry with collMod, without a rebuild. Any other difference fails in createIndexes, as before.
+ */
+export async function ensureIndex(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string, index: IndexSpec): Promise<void> {
+ const found = (await listIndexes(db, collection)).find(existing => existing.name === index.name)
+ if (found && sameKey(found.key, index.key) && !!found.unique === !!index.unique) {
+ if (found.expireAfterSeconds === index.expireAfterSeconds) return
+ if (index.expireAfterSeconds !== undefined) {
+ await db.$runCommandRaw({ collMod: collection, index: { name: index.name, expireAfterSeconds: index.expireAfterSeconds } })
+ return
+ }
+ }
+ await db.$runCommandRaw({ createIndexes: collection, indexes: [index] })
+}
diff --git a/backend/src/lib/db/migrate.ts b/backend/src/lib/db/migrate.ts
index 785ecf019..525c9a01f 100644
--- a/backend/src/lib/db/migrate.ts
+++ b/backend/src/lib/db/migrate.ts
@@ -1,4 +1,4 @@
-import { execFileSync } from 'child_process'
+import { spawn } from 'child_process'
import { existsSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
@@ -10,14 +10,26 @@ const __dirname = dirname(fileURLToPath(import.meta.url))
// src/lib/db or dist/lib/db → package root
const root = join(__dirname, '..', '..', '..')
+/** Where the schema step pushes from and to: the package's schema and the process's database unless a test names others. */
+export interface SchemaTarget { schema?: string; databaseUrl?: string }
+
+/** The Prisma CLI as a child process, its output on ours. Async, so a caller's event loop keeps serving while it runs. */
+function runPrisma(prismaCli: string, args: string[], databaseUrl: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [prismaCli, ...args], { stdio: 'inherit', env: { ...process.env, DATABASE_URL: databaseUrl } })
+ child.once('error', reject)
+ child.once('exit', (code, signal) => code === 0 ? resolve() : reject(new Error(`prisma ${args.join(' ')} exited with ${signal ?? code}`)))
+ })
+}
+
/**
* Push the Prisma schema to MongoDB before serving. No migration files — `prisma db
* push` creates the `users` + `agent_bindings` collections + indexes; idempotent. It
* does NOT touch the manager-owned `agent_nodes`/`managers` collections (they aren't in
* this schema), so the shared DB is safe.
*/
-export function ensureSchema(): void {
- process.env.DATABASE_URL ??= env.DATABASE_URL
+export async function ensureSchema(target: SchemaTarget = {}): Promise<void> {
+ const databaseUrl = target.databaseUrl ?? env.DATABASE_URL
const prismaCli = join(root, 'node_modules', 'prisma', 'build', 'index.js')
if (!existsSync(prismaCli)) {
@@ -25,12 +37,9 @@ export function ensureSchema(): void {
return
}
- const schema = join(root, 'prisma', 'schema.prisma')
+ const schema = target.schema ?? join(root, 'prisma', 'schema.prisma')
try {
- execFileSync(process.execPath, [prismaCli, 'db', 'push', '--schema', schema, '--skip-generate'], {
- stdio: 'inherit',
- env: process.env,
- })
+ await runPrisma(prismaCli, ['db', 'push', '--schema', schema, '--skip-generate'], databaseUrl)
logger.info('Prisma db push ok (backend schema)')
} catch (err) {
logger.error('Prisma db push failed — continuing (collections may already exist)', err)
diff --git a/backend/src/lib/db/schemaRelease.ts b/backend/src/lib/db/schemaRelease.ts
new file mode 100644
index 000000000..e89554612
--- /dev/null
+++ b/backend/src/lib/db/schemaRelease.ts
@@ -0,0 +1,19 @@
+import type { PrismaClient } from '@prisma/client'
+import { prisma } from '../prisma.js'
+import { ensureProductUsageExpiry } from '../productUsage.js'
+import { ensureHarnessSessionExpiry } from '../ssoSession.js'
+import { ensureTerminalExpiry } from '../../superTabs/terminal.js'
+import { ensureMentionExpiry } from '../../superTabs/mentions.js'
+import { ensurePartExpiry } from '../../superTabs/sweeps.js'
+import { ensureSchema, type SchemaTarget } from './migrate.js'
+
+/** The index work of a release, run by the singleton worker at startup once the legacy unique indexes are gone: the
+ * Prisma schema, then the indexes Prisma cannot describe (expiry, and the keys that must hold before the push). */
+export async function releaseSchema(db: PrismaClient = prisma, target: SchemaTarget = {}): Promise<void> {
+ await ensureSchema(target)
+ await ensureProductUsageExpiry(db)
+ await ensureHarnessSessionExpiry(db)
+ await ensureTerminalExpiry(db)
+ await ensureMentionExpiry(db)
+ await ensurePartExpiry(db)
+}
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index 02a8739e9..a7da115d0 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -340,20 +340,32 @@ it('the legacy delete path erases all six linked activity collections', async ()
expect(db.productUsageActivity.deleteMany).toHaveBeenCalledWith({ where: { subject: activitySubject('account', 'k'.repeat(32)) } })
})
+/** The index builds `ensureProductUsageExpiry` sends, in order: each lists its collection first, which finds no index here. */
+const builds = (): Array<Record<string, unknown>> => db.$runCommandRaw.mock.calls.map(([command]) => command).filter(command => 'createIndexes' in command)
+/** Each build in turn takes the next answer (a value, or `{ fails }` to throw); once they run out, every build takes `rest`. */
+function answerBuilds(answers: unknown[], rest: unknown = {}): void {
+ db.$runCommandRaw.mockImplementation(async command => {
+ if (!('createIndexes' in command)) return { ok: 1 }
+ const answer = answers.length ? answers.shift() : rest
+ if (answer && typeof answer === 'object' && 'fails' in answer) throw (answer as { fails: unknown }).fails
+ return answer
+ })
+}
+
it('installs required unique keys independently of schema push, then expiry for all histories', async () => {
await ensureProductUsageExpiry()
- expect(db.$runCommandRaw).toHaveBeenCalledTimes(14)
- expect(db.$runCommandRaw.mock.calls[12][0]).toMatchObject({ createIndexes: 'product_usage_activity', indexes: [{ key: { expiresAt: 1 }, expireAfterSeconds: 0 }] })
- expect(db.$runCommandRaw.mock.calls[13][0]).toMatchObject({ createIndexes: 'product_usage_activity', indexes: [{ key: { subject: 1, dayUtc: 1 }, unique: true }] })
- expect(db.$runCommandRaw.mock.calls[0][0]).toMatchObject({ createIndexes: 'product_usage_preferences', indexes: [{ key: { userId: 1 }, unique: true }] })
- expect(db.$runCommandRaw.mock.calls[1][0]).toMatchObject({ createIndexes: 'product_usage_totals', indexes: [{ key: { dayUtc: 1, metric: 1 }, unique: true }] })
- expect(db.$runCommandRaw.mock.calls[2][0]).toMatchObject({ createIndexes: 'product_usage_receipts', indexes: [{ expireAfterSeconds: 0 }] })
- expect(db.$runCommandRaw.mock.calls[4][0]).toMatchObject({ createIndexes: 'user_daily_presence', indexes: [{ expireAfterSeconds: 35 * 86400 }] })
+ expect(builds()).toHaveLength(14)
+ expect(builds()[12]).toMatchObject({ createIndexes: 'product_usage_activity', indexes: [{ key: { expiresAt: 1 }, expireAfterSeconds: 0 }] })
+ expect(builds()[13]).toMatchObject({ createIndexes: 'product_usage_activity', indexes: [{ key: { subject: 1, dayUtc: 1 }, unique: true }] })
+ expect(builds()[0]).toMatchObject({ createIndexes: 'product_usage_preferences', indexes: [{ key: { userId: 1 }, unique: true }] })
+ expect(builds()[1]).toMatchObject({ createIndexes: 'product_usage_totals', indexes: [{ key: { dayUtc: 1, metric: 1 }, unique: true }] })
+ expect(builds()[2]).toMatchObject({ createIndexes: 'product_usage_receipts', indexes: [{ expireAfterSeconds: 0 }] })
+ expect(builds()[4]).toMatchObject({ createIndexes: 'user_daily_presence', indexes: [{ expireAfterSeconds: 35 * 86400 }] })
expect(db.productUsageTotal.groupBy).not.toHaveBeenCalled()
})
it('merges duplicate counters transactionally before installing their unique key', async () => {
- db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValueOnce({ meta: { message: 'E11000 duplicate key' } })
+ answerBuilds([{}, { fails: { meta: { message: 'E11000 duplicate key' } } }])
db.productUsageTotal.groupBy.mockResolvedValue([{ dayUtc: now, metric: 'relay_turns_started' }])
db.productUsageTotal.findMany.mockResolvedValue([{ id: 'keep', value: 2 }, { id: 'duplicate', value: 5 }])
await ensureProductUsageExpiry()
@@ -363,15 +375,15 @@ it('merges duplicate counters transactionally before installing their unique key
})
it('retries a conflicting repair but fails startup for unrelated database failures', async () => {
- db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValueOnce({ meta: { code: 11000 } })
+ answerBuilds([{}, { fails: { meta: { code: 11000 } } }])
db.$transaction.mockRejectedValueOnce({ code: 'P2034' })
await expect(ensureProductUsageExpiry()).resolves.toBeUndefined()
- db.$runCommandRaw.mockRejectedValueOnce(new Error('permission denied'))
+ answerBuilds([{ fails: new Error('permission denied') }])
await expect(ensureProductUsageExpiry()).rejects.toThrow('permission denied')
})
it('bounds duplicate repair work and refuses to claim readiness without a unique key', async () => {
- db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValue({ meta: { code: 11000 } })
+ answerBuilds([{}], { fails: { meta: { code: 11000 } } })
db.productUsageTotal.groupBy.mockResolvedValue([])
await expect(ensureProductUsageExpiry()).rejects.toThrow('aggregate key is not ready')
expect(db.$transaction).toHaveBeenCalledTimes(10)
diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.ts
index 152479064..cd666aec4 100644
--- a/backend/src/lib/productUsage.ts
+++ b/backend/src/lib/productUsage.ts
@@ -2,9 +2,10 @@ import { healthBreakdowns } from '../analytics/productHealth.js'
import type { ProductUsageContext } from '../types/productHealthContract.js'
import { createHmac } from 'node:crypto'
import { setTimeout as delay } from 'node:timers/promises'
-import type { Prisma } from '@prisma/client'
+import type { Prisma, PrismaClient } from '@prisma/client'
import { env } from '../config/env.js'
import { prisma } from './prisma.js'
+import { ensureIndex } from './db/indexes.js'
import { PRODUCT_USAGE_DAYS, type ProductUsageChoice, type ProductUsageReport } from '../types/productUsage.js'
import { ACTIVITY_DAYS, type ActivitySurface } from '../types/productUsageActivity.js'
import { incrementUsageTotals, type UsageIncrement } from './productUsageWrite.js'
@@ -276,14 +277,12 @@ export async function deleteLegacyProductUsage(userId: string): Promise<void> {
])
}
-async function ensureProductUsageTotalKey(): Promise<void> {
+async function ensureProductUsageTotalKey(db: PrismaClient): Promise<void> {
// The API can receive relay counts before the singleton's general schema push. That push may
// also decline unrelated changes. Install this correctness boundary explicitly; do not rely on it.
for (let attempt = 0; attempt < 10; attempt++) {
try {
- await prisma.$runCommandRaw({ createIndexes: 'product_usage_totals', indexes: [{
- key: { dayUtc: 1, metric: 1 }, name: 'product_usage_totals_dayUtc_metric_key', unique: true,
- }] })
+ await ensureIndex(db, 'product_usage_totals', { key: { dayUtc: 1, metric: 1 }, name: 'product_usage_totals_dayUtc_metric_key', unique: true })
return
} catch (error) {
const failure = error as { meta?: { code?: string | number; message?: string } }
@@ -293,7 +292,7 @@ async function ensureProductUsageTotalKey(): Promise<void> {
// from concurrent writers: a changed/deleted row conflicts and retries instead of losing counts.
// Bound each pass; a large backlog fails worker startup and resumes safely on its next start.
try {
- await prisma.$transaction(async tx => {
+ await db.$transaction(async tx => {
const [group] = await tx.productUsageTotal.groupBy({
by: ['dayUtc', 'metric'], having: { id: { _count: { gt: 1 } } },
orderBy: [{ dayUtc: 'asc' }, { metric: 'asc' }], take: 1,
@@ -317,11 +316,9 @@ async function ensureProductUsageTotalKey(): Promise<void> {
}
/** Run only in the singleton worker. Required keys and expiry must survive a declined schema push. */
-export async function ensureProductUsageExpiry(): Promise<void> {
- await prisma.$runCommandRaw({ createIndexes: 'product_usage_preferences', indexes: [{
- key: { userId: 1 }, name: 'product_usage_preferences_userId_key', unique: true,
- }] })
- await ensureProductUsageTotalKey()
+export async function ensureProductUsageExpiry(db: PrismaClient = prisma): Promise<void> {
+ await ensureIndex(db, 'product_usage_preferences', { key: { userId: 1 }, name: 'product_usage_preferences_userId_key', unique: true })
+ await ensureProductUsageTotalKey(db)
for (const [collection, field, seconds] of [
['product_usage_receipts', 'expiresAt', 0],
['product_usage_totals', 'dayUtc', 396 * DAY / 1000],
@@ -330,9 +327,7 @@ export async function ensureProductUsageExpiry(): Promise<void> {
.map(name => [name, 'dayUtc', PRODUCT_USAGE_DAYS * DAY / 1000]),
['product_usage_activity', 'expiresAt', 0],
] as [string, string, number][]) {
- await prisma.$runCommandRaw({ createIndexes: collection, indexes: [{ key: { [field]: 1 }, name: 'product_usage_expiry', expireAfterSeconds: seconds }] })
+ await ensureIndex(db, collection, { key: { [field]: 1 }, name: 'product_usage_expiry', expireAfterSeconds: seconds })
}
- await prisma.$runCommandRaw({ createIndexes: 'product_usage_activity', indexes: [{
- key: { subject: 1, dayUtc: 1 }, name: 'product_usage_activity_subject_dayUtc_key', unique: true,
- }] })
+ await ensureIndex(db, 'product_usage_activity', { key: { subject: 1, dayUtc: 1 }, name: 'product_usage_activity_subject_dayUtc_key', unique: true })
}
diff --git a/backend/src/lib/ssoSession.ts b/backend/src/lib/ssoSession.ts
index 9a333c3ac..171f5edbe 100644
--- a/backend/src/lib/ssoSession.ts
+++ b/backend/src/lib/ssoSession.ts
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'
import type { HarnessSession, Prisma, PrismaClient } from '@prisma/client'
import { pub } from './bus.js'
import { prisma } from './prisma.js'
+import { ensureIndex } from './db/indexes.js'
import { decryptMachineCredential, encryptMachineCredential } from './machineCredential.js'
import { normalizeSsoClientId, refreshAccessToken, SsoTokenError, type SsoClientId } from './sso.js'
import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'
@@ -237,9 +238,8 @@ export async function ssoAccessTokenFor(sessionId: string, userId: string): Prom
/**
* Sessions are deleted [ENDED_SESSION_KEEP_MS] after they expire: idle past their lifetime, or ended
- * ([endedSessionData] expires them). Nothing else deletes them. Run by the worker at start (worker.ts).
+ * ([endedSessionData] expires them). Nothing else deletes them. Run by the worker at start (lib/db/schemaRelease.ts).
*/
export async function ensureHarnessSessionExpiry(db: Pick<PrismaClient, '$runCommandRaw'>): Promise<void> {
- await db.$runCommandRaw({ createIndexes: 'harness_sessions', indexes: [{ key: { expiresAt: 1 }, name: 'harness_session_expiry',
- expireAfterSeconds: ENDED_SESSION_KEEP_MS / 1000 }] })
+ await ensureIndex(db, 'harness_sessions', { key: { expiresAt: 1 }, name: 'harness_session_expiry', expireAfterSeconds: ENDED_SESSION_KEEP_MS / 1000 })
}
diff --git a/backend/src/middlewares/errorHandler.test.ts b/backend/src/middlewares/errorHandler.test.ts
index ed174e168..ecd307b24 100644
--- a/backend/src/middlewares/errorHandler.test.ts
+++ b/backend/src/middlewares/errorHandler.test.ts
@@ -70,6 +70,19 @@ describe('the shared error handler', () => {
expect(res.json().error).toEqual({ code: 'DUPLICATE', message: 'This already exists, so nothing new was saved.' })
})
+ // In the cluster the log line is JSON whose own `message` is the event's (utils/logger.ts): a context field of that name was
+ // dropped, so prod's duplicate-key lines never said which index (2026-10-28).
+ it('logs the database\'s own words, naming the index, under a field the log line keeps', async () => {
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
+ for (const [code, message] of [['P2002', 'Unique constraint failed on the constraint: `_id_`'], ['P2028', 'Transaction already closed']]) {
+ thrown = prismaError(code!, message!)
+ await app.inject({ method: 'GET', url: '/fails' })
+ const context = warn.mock.calls.at(-1)![1] as Record<string, unknown>
+ expect(context).toMatchObject({ path: '/fails', method: 'GET', error: message })
+ expect(context).not.toHaveProperty('message')
+ }
+ })
+
it('keeps anything else a 500 and logs its stack', async () => {
const error = vi.spyOn(logger, 'error').mockImplementation(() => {})
thrown = new TypeError("Cannot read properties of null (reading 'sendDown')")
diff --git a/backend/src/middlewares/errorHandler.ts b/backend/src/middlewares/errorHandler.ts
index ce5ef80bc..a404ee698 100644
--- a/backend/src/middlewares/errorHandler.ts
+++ b/backend/src/middlewares/errorHandler.ts
@@ -53,11 +53,11 @@ export async function errorHandler(
// A unique key still taken after the retries (P2002) is a genuine duplicate: a conflict, never a 500.
const prisma = prismaCode(error)
if (prisma === 'P2028') {
- logger.warn('Database transaction expired or could not start', { path: request.url, method: request.method, message: error.message })
+ logger.warn('Database transaction expired or could not start', { path: request.url, method: request.method, error: error.message })
return sendBusy(reply, 'The server is busy. Try again in a moment.', 'BUSY')
}
if (prisma === 'P2002') {
- logger.warn('Duplicate key', { path: request.url, method: request.method, message: error.message })
+ logger.warn('Duplicate key', { path: request.url, method: request.method, error: error.message })
return sendError(reply, 'This already exists, so nothing new was saved.', 'DUPLICATE', 409)
}
diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.ts
new file mode 100644
index 000000000..7c7ac307e
--- /dev/null
+++ b/backend/src/superTabs/buddies.test.ts
@@ -0,0 +1,622 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, visibleState, type Actor, type Conversation } from './model.js'
+import { canReadGroup, canWatchAgent, isConfidential } from './projects.js'
+import { sweepLiveness } from './liveness.js'
+import { hostTab } from './read/hostRows.js'
+import { groupView } from './read/views.js'
+import { reassemble, split } from './parts/index.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+
+/** A Swarm of two public projects, each with its Lead, and peer's Buddy in the first, stored as buddy.create and its start
+ * leave them (buddies.ts): a Buddy agent and its owner-only chat. */
+function setup() {
+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: owner.email }, 'test')
+ state.people.push({ id: 'peer', email: peer.email, role: 'collaborator', generation: 'first' })
+ let next = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { operationId: `op${next++}`, now: 1000,
+ contribution: { machineOwnerId: 'host', contributorId: actor.kind === 'person' ? actor.userId : 'owner' }, ...context })
+ state = effects.state
+ return effects
+ }
+ const app = run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const web = run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const lead = (conversationId: string, harnessId: string) => run({ type: 'agent.add', conversationId, harnessId, machineId: 'machine',
+ name: harnessId, configuration, lead: true }).result.agentId as string
+ const pm = lead(app.conversationId, 'app-pm')
+ lead(web.conversationId, 'web-pm')
+ const group = run({ type: 'conversation.create', projectId: app.projectId, title: 'Offline', brief: 'Save edits.', checks: [] }).result.conversationId as string
+ const pmChat = run({ type: 'conversation.create', projectId: app.projectId, title: 'peer', brief: '', checks: [],
+ audience: { personIds: ['peer'] } }, peer).result.conversationId as string
+ state.agents.push({ id: 'buddy', projectId: app.projectId, machineId: 'machine', harnessId: 'buddy-harness', machineOwnerId: 'host',
+ contributorId: 'peer', membershipGeneration: 'first', name: 'Buddy', configuration, buddyOf: { personId: 'peer', generation: 'first' } })
+ const chat: Conversation = { id: 'peer-buddy', kind: 'buddy', projectId: app.projectId, title: 'Buddy', leadId: null, agentIds: ['buddy'],
+ archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0, audience: { people: [{ id: 'peer', generation: 'first' }] } }
+ state.conversations.push(chat)
+ return { run, app, web, pm, group, pmChat, chat: chat.id, get state() { return state } }
+}
+const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host' })
+const group = (f: ReturnType<typeof setup>, id: string) => f.state.conversations.find(c => c.id === id)!
+
+describe('who reads a Buddy chat', () => {
+ it('is its owner and its Buddy: never the PM, the project or Swarm owner, or another person', () => {
+ const f = setup(), chat = group(f, f.chat)
+ expect(canReadGroup(f.state, peer, chat)).toBe(true)
+ expect(canReadGroup(f.state, agentActor('buddy'), chat)).toBe(true)
+ expect(canReadGroup(f.state, agentActor(f.pm), chat)).toBe(false)
+ expect(canReadGroup(f.state, owner, chat)).toBe(false)
+ })
+
+ it('stops being its owner\'s once they rejoin at a new membership', () => {
+ const f = setup()
+ f.state.people.find(p => p.id === 'peer')!.generation = 'second'
+ expect(canReadGroup(f.state, peer, group(f, f.chat))).toBe(false)
+ })
+
+ it('is left out of everyone else\'s Swarm read, the PM\'s included', () => {
+ const f = setup()
+ expect(visibleState(f.state, peer).conversations.map(c => c.id)).toContain(f.chat)
+ for (const reader of [owner, agentActor(f.pm)]) expect(visibleState(f.state, reader).conversations.map(c => c.id)).not.toContain(f.chat)
+ })
+})
+
+describe('what a Buddy reads', () => {
+ it('is its project\'s chat and its own chat: no workgroup, no Chat with PM, no other project, no Leads conversation', () => {
+ const f = setup(), buddy = agentActor('buddy')
+ expect(canReadGroup(f.state, buddy, group(f, f.app.conversationId))).toBe(true)
+ expect(canReadGroup(f.state, buddy, group(f, f.group))).toBe(false)
+ expect(canReadGroup(f.state, buddy, group(f, f.pmChat))).toBe(false)
+ expect(canReadGroup(f.state, buddy, group(f, f.web.conversationId))).toBe(false)
+ expect(visibleState(f.state, buddy).conversations.map(c => c.id).sort()).toEqual([f.app.conversationId, f.chat].sort())
+ })
+
+ it('shows no machines, starts or rules in its Swarm read: only names in the roster', () => {
+ const f = setup()
+ machine(f, 'peer-mac', 'peer')
+ f.run({ type: 'rule.set', projectId: f.app.projectId, rule: { kind: 'preferIdle' }, text: 'Idle first.' })
+ const seen = visibleState(f.state, agentActor('buddy'))
+ expect(seen.machines ?? []).toEqual([])
+ expect(seen.rules ?? []).toEqual([])
+ expect(seen.agents.map(a => a.id)).toContain(f.pm)
+ expect(visibleState(f.state, agentActor(f.pm)).machines).toHaveLength(1)
+ })
+
+ it('is no other person\'s Buddy chat in the same project', () => {
+ const f = setup()
+ f.state.conversations.push({ ...group(f, f.chat), id: 'owner-buddy', agentIds: ['other-buddy'], audience: { people: [{ id: 'owner', generation: f.state.people[0]!.generation }] } })
+ expect(canReadGroup(f.state, agentActor('buddy'), group(f, 'owner-buddy'))).toBe(false)
+ })
+
+ it('is a confidential session: only the person whose machine runs it watches its terminal', () => {
+ const f = setup(), buddy = f.state.agents.find(a => a.id === 'buddy')!
+ f.state.people.push({ id: 'host', email: '[email protected]', role: 'collaborator', generation: 'first' })
+ expect(isConfidential(f.state, buddy)).toBe(true)
+ expect(canWatchAgent(f.state, peer, buddy)).toBe(false)
+ expect(canWatchAgent(f.state, { kind: 'person', userId: 'host', email: '[email protected]' }, buddy)).toBe(true)
+ })
+})
+
+describe('the Swarm\'s Buddies setting', () => {
+ it('is off in a new Swarm, and only its owner turns it on', () => {
+ const f = setup()
+ expect(f.state.buddies).toBeUndefined()
+ expect(() => f.run({ type: 'tab.buddies', enabled: true }, peer)).toThrow('Only the Swarm owner')
+ expect(() => f.run({ type: 'tab.buddies', enabled: true }, agentActor(f.pm))).toThrow('Only the Swarm owner')
+ f.run({ type: 'tab.buddies', enabled: true })
+ expect(f.state.buddies).toBe(true)
+ expect(visibleState(f.state, peer).buddies).toBe(true)
+ })
+
+ it('may be turned on by a Lead passing on the owner\'s own chat message from the last day', () => {
+ const f = setup(), askedIn = { conversationId: f.app.conversationId, messageId: 'owner-message' }
+ const asked = (author: { kind: 'person' | 'agent'; id: string }, createdAt = 1000) =>
+ ({ askedIn: { author: { ...author, name: author.id, membershipGeneration: 'g' }, source: false, createdAt } })
+ expect(() => f.run({ type: 'tab.buddies', enabled: true, askedIn }, agentActor(f.pm), asked({ kind: 'person', id: 'peer' }))).toThrow('Only the Swarm owner')
+ f.run({ type: 'tab.buddies', enabled: true, askedIn }, agentActor(f.pm), asked({ kind: 'person', id: 'owner' }))
+ expect(f.state.buddies).toBe(true)
+ })
+
+ it('removes every Buddy when turned off, closing its session, and keeps their chats for their owners', () => {
+ const f = setup()
+ f.run({ type: 'tab.buddies', enabled: true })
+ const off = f.run({ type: 'tab.buddies', enabled: false })
+ expect(f.state.buddies).toBeUndefined()
+ expect(f.state.agents.map(a => a.id)).not.toContain('buddy')
+ expect(off.cancelledAgents).toEqual(['buddy'])
+ expect(f.state.closingSessions).toEqual([{ agentId: 'buddy', machineId: 'machine', harnessId: 'buddy-harness', machineOwnerId: 'host' }])
+ expect(group(f, f.chat)).toMatchObject({ agentIds: [], archived: false })
+ expect(canReadGroup(f.state, peer, group(f, f.chat))).toBe(true)
+ })
+})
+
+/** [contributorId]'s machine in the Swarm's Machines list, reporting now, for any project (`scope: swarm`). */
+function machine(f: ReturnType<typeof setup>, machineId: string, contributorId: string) {
+ f.state.machines = [...(f.state.machines ?? []), { machineId, name: `${contributorId}'s Mac`, contributorId, generation: 'g1', cwd: '/swarm', scope: 'swarm',
+ membershipGeneration: f.state.people.find(p => p.id === contributorId)!.generation, engines: ['claude', 'codex'], maxAgents: 3, paused: false,
+ observation: { generation: 'g1', receivedAt: 1000, sessionKind: 'computer',
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] } }]
+}
+/** A person adding a Buddy on [machineId], with the grant the store reads for it: a Swarm machine is run by its contributor. */
+const addBuddy = (f: ReturnType<typeof setup>, actor: Actor, projectId: string, machineId = 'peer-mac', engine: 'claude' | 'codex' = 'claude') =>
+ f.run({ type: 'buddy.create', projectId, machineId, engine }, actor,
+ { contribution: { machineOwnerId: f.state.machines?.find(m => m.machineId === machineId)?.contributorId ?? 'nobody',
+ contributorId: f.state.machines?.find(m => m.machineId === machineId)?.contributorId ?? 'nobody' } })
+/** The Buddy setup() stored by hand is someone else's: here peer has none yet. */
+function fresh() {
+ const f = setup()
+ f.state.agents = f.state.agents.filter(a => a.id !== 'buddy')
+ f.state.conversations = f.state.conversations.filter(c => c.id !== f.chat)
+ machine(f, 'peer-mac', 'peer')
+ f.run({ type: 'tab.buddies', enabled: true })
+ return f
+}
+
+describe('adding a Buddy', () => {
+ it('is refused while Buddies are off', () => {
+ const f = fresh()
+ f.run({ type: 'tab.buddies', enabled: false })
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('Buddies are off')
+ })
+
+ it('opens the person\'s Buddy chat, read by them alone, and starts the Buddy on the machine they chose', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId, 'peer-mac', 'codex')
+ const chat = group(f, added.result.conversationId as string)
+ expect(chat).toMatchObject({ kind: 'buddy', projectId: f.app.projectId, leadId: null, agentIds: [], archived: false,
+ audience: { people: [{ id: 'peer', generation: 'first' }] } })
+ expect(added.messages).toEqual([])
+ const start = f.state.starts!.find(s => s.id === added.result.startId)!
+ expect(start).toMatchObject({ contributorId: 'peer', machineOwnerId: 'peer', poolGeneration: 'g1', dispatched: false, error: null })
+ expect(start.request).toMatchObject({ conversationId: chat.id, machineId: 'peer-mac', engine: 'codex', cwd: `/swarm/${f.app.projectId}`,
+ worktree: true, name: 'peer\'s Buddy', buddyOf: { personId: 'peer', generation: 'first' } })
+ expect(start.request.role).toBeUndefined()
+ })
+
+ it('makes the started agent a Buddy in its owner\'s chat, and says it is ready there', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }
+ const joined = f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'native', configuration }, peer, host)
+ const buddy = f.state.agents.find(a => a.id === joined.result.agentId)!
+ expect(buddy.buddyOf).toEqual({ personId: 'peer', generation: 'first' })
+ expect(group(f, added.result.conversationId as string).agentIds).toEqual([buddy.id])
+ expect(joined.messages).toEqual([])
+ const settled = f.run({ type: 'agent.startSettled', startId: added.result.startId as string, warning: null }, peer, host)
+ expect(settled.messages.map(m => [m.conversationId, m.text, m.recipients])).toEqual([[added.result.conversationId, 'peer\'s Buddy is ready. Tell it what you have in mind.', []]])
+ })
+
+ it('is one per person and project, while it starts or runs; another project or person may have their own', () => {
+ const f = fresh()
+ machine(f, 'owner-mac', 'owner')
+ const added = addBuddy(f, peer, f.app.projectId)
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('already have a Buddy')
+ f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'native', configuration }, peer,
+ { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } })
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('already have a Buddy')
+ expect(addBuddy(f, peer, f.web.projectId).result.startId).toBeTruthy()
+ expect(addBuddy(f, owner, f.app.projectId, 'owner-mac').result.startId).toBeTruthy()
+ })
+
+ it('reopens the same chat when added again after its Buddy was removed', () => {
+ const f = fresh()
+ const first = addBuddy(f, peer, f.app.projectId)
+ f.state.starts!.find(s => s.id === first.result.startId)!.error = 'Stopped.'
+ expect(addBuddy(f, peer, f.app.projectId).result.conversationId).toBe(first.result.conversationId)
+ expect(f.state.conversations.filter(c => c.kind === 'buddy')).toHaveLength(1)
+ })
+
+ it('is refused to an agent, a viewer, and on a machine that is not in the Swarm', () => {
+ const f = fresh()
+ expect(() => addBuddy(f, agentActor(f.pm), f.app.projectId)).toThrow('A person adds their own Buddy')
+ f.state.people.find(p => p.id === 'peer')!.role = 'viewer'
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow()
+ f.state.people.find(p => p.id === 'peer')!.role = 'collaborator'
+ expect(() => addBuddy(f, peer, f.app.projectId, 'elsewhere')).toThrow('Add this machine to the Swarm first')
+ })
+})
+
+describe('a Buddy\'s start on its machine', () => {
+ const lookups = { people: [], confidential: new Set<string>(), agentGrant: async () => {}, teams: [], githubApp: false }
+ const user = { sub: 'peer', email: peer.email, role: 'user', autonomousEnv: 'test' } as never
+
+ it('is listed to its host apart from other starts, with its chat authorized for the project folder, so an older host never launches it', async () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ const pool = (await hostTab('swarm', f.state, 'peer-mac', user, null, lookups)).pool!
+ expect(pool.starts).toEqual([])
+ expect(pool.buddyStarts!.map(s => s.id)).toEqual([added.result.startId])
+ expect(pool.projects!.find(p => p.id === f.app.projectId)!.conversationIds).toContain(added.result.conversationId)
+ })
+
+ it('fails when its machine, still reporting, has not taken it in 5 minutes, and tells its owner in their chat to update Harness there', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ const fresh4 = 1000 + 4 * 60_000
+ f.state.machines![0]!.observation!.receivedAt = fresh4
+ expect(sweepLiveness(f.state, fresh4)).toEqual([])
+ const late = 1000 + 5 * 60_000 + 1
+ f.state.machines![0]!.observation!.receivedAt = late
+ const notices = sweepLiveness(f.state, late)
+ const start = f.state.starts!.find(s => s.id === added.result.startId)!
+ expect(start.error).toBe('peer\'s Mac did not start this Buddy. Update Harness on it, then add the Buddy again.')
+ expect(notices).toEqual([expect.objectContaining({ conversationId: added.result.conversationId, recipients: [], text: expect.stringContaining('Update Harness'),
+ author: expect.objectContaining({ kind: 'person', id: 'peer' }), source: { kind: 'start-timeout', startId: start.id } })])
+ })
+
+ it('keeps waiting while its machine is not reporting', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ expect(sweepLiveness(f.state, 1000 + 10 * 60_000)).toEqual([])
+ expect(f.state.starts!.find(s => s.id === added.result.startId)!.error).toBeNull()
+ })
+})
+
+describe('what a Buddy may do', () => {
+ /** setup()'s Buddy, with Buddies on. */
+ const on = () => { const f = setup(); f.run({ type: 'tab.buddies', enabled: true }); return f }
+ const buddy = agentActor('buddy')
+
+ it('is post in its own chat; its owner\'s message there reaches it, and nobody else posts there', () => {
+ const f = on()
+ expect(f.run({ type: 'message.send', conversationId: f.chat, text: 'What outcome do you want?', replyTo: null, recipientIds: [] }, buddy).messages[0])
+ .toMatchObject({ conversationId: f.chat, recipients: [] })
+ expect(f.run({ type: 'message.send', conversationId: f.chat, text: 'Faster sync.', replyTo: null, recipientIds: [] }, peer).messages[0])
+ .toMatchObject({ recipients: ['buddy'] })
+ expect(() => f.run({ type: 'message.send', conversationId: f.chat, text: 'Hi', replyTo: null, recipientIds: [] })).toThrow('unavailable')
+ expect(() => f.run({ type: 'message.send', conversationId: f.chat, text: 'Hi', replyTo: null, recipientIds: [] }, agentActor(f.pm))).toThrow('unavailable')
+ })
+
+ it('never posts in the project chat or anywhere else but its chat: proposals go through the proposal command', () => {
+ const f = on()
+ for (const conversationId of [f.app.conversationId, f.group, f.pmChat, f.web.conversationId, f.state.leadsConversationId!]) {
+ expect(() => f.run({ type: 'message.send', conversationId, text: 'Hello PM', replyTo: null, recipientIds: [] }, buddy)).toThrow()
+ }
+ expect(() => f.run({ type: 'message.send', conversationId: f.app.conversationId, text: 'Hello PM', replyTo: null, recipientIds: [] }, buddy))
+ .toThrow('A Buddy posts only in its own chat')
+ })
+
+ it('never assigns, starts agents, opens groups, asks decisions, sets rules or reacts outside its chat', () => {
+ const f = on()
+ const refused: Command[] = [
+ { type: 'work.assign', conversationId: f.group, agentId: 'buddy' },
+ { type: 'work.define', conversationId: f.group, brief: 'Do it', checks: [{ description: 'Done', independent: false }] },
+ { type: 'conversation.create', projectId: f.app.projectId, title: 'New', brief: 'Brief', checks: [{ description: 'Done', independent: false }] },
+ { type: 'agent.start', request: { conversationId: f.group, machineId: 'machine', engine: 'claude', name: 'Helper', cwd: '/repo', worktree: true,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }, routeDecisionId: 'route' },
+ { type: 'decision.ask', conversationId: f.chat, personId: 'peer', questions: [{ question: 'Which?', options: ['A', 'B'], recommended: 0, unblocks: 'Work' }] },
+ { type: 'rule.set', rule: { kind: 'preferIdle' }, text: 'Idle first.' },
+ { type: 'conversation.agent', conversationId: f.app.conversationId, agentId: 'buddy', present: true, lead: false },
+ { type: 'message.react', conversationId: f.app.conversationId, messageId: 'm', emoji: 'thumbs_up', on: true },
+ { type: 'agent.remove', agentId: f.pm },
+ { type: 'tab.buddies', enabled: false },
+ ]
+ for (const command of refused) expect(() => f.run(command, buddy), command.type).toThrow('A Buddy')
+ })
+
+ it('reports its own configuration and its own stop, as its machine does for every agent', () => {
+ const f = on()
+ f.run({ type: 'agent.configuration', previousVersion: null, configuration: { ...configuration, model: 'opus' } }, buddy)
+ expect(f.state.agents.find(a => a.id === 'buddy')!.configuration.model).toBe('opus')
+ })
+})
+
+describe('a Buddy\'s proposal to the PM', () => {
+ const buddy = agentActor('buddy')
+ const proposal = { goal: 'Sync edits made offline', scope: 'Desktop drafts only; no phone yet', priority: 'high' as const }
+ /** setup()'s Buddy with Buddies on, and the message its owner asked with, as the store reads it. */
+ function asked(author: { kind: 'person' | 'agent'; id: string; generation?: string } = { kind: 'person', id: 'peer' }, extra: Record<string, unknown> = {}) {
+ const f = setup()
+ f.run({ type: 'tab.buddies', enabled: true })
+ const ask = { conversationId: f.chat, source: false, createdAt: 900,
+ author: { kind: author.kind, id: author.id, name: author.id, membershipGeneration: author.generation ?? 'first' }, ...extra }
+ const propose = (ownerMessageId = 'ask', context: Record<string, unknown> = { proposalAsk: { id: ownerMessageId, ...ask } }) =>
+ f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId, ...proposal }, buddy, context)
+ return { f, propose }
+ }
+
+ it('posts one message in the project chat, to the PM, written by the server as on its owner\'s behalf', () => {
+ const { f, propose } = asked()
+ const posted = propose().messages
+ expect(posted).toEqual([expect.objectContaining({ conversationId: f.app.conversationId, recipients: [f.pm],
+ author: expect.objectContaining({ kind: 'agent', id: 'buddy' }), source: { kind: 'buddy-proposal', personId: 'peer', ownerMessageId: 'ask' },
+ text: 'Proposal from peer\'s Buddy, on peer\'s behalf.\n\nGoal: Sync edits made offline\nScope: Desktop drafts only; no phone yet\nPriority: high' })])
+ })
+
+ it('is one per ask: the same message never asks twice', () => {
+ const { propose } = asked()
+ propose()
+ expect(() => propose()).toThrow('already sent')
+ })
+
+ it('is refused without its owner\'s own message in its chat asking for it', () => {
+ expect(() => asked().propose('ask', {})).toThrow('your owner\'s message')
+ expect(() => asked({ kind: 'agent', id: 'buddy' }).propose()).toThrow('your owner\'s message')
+ expect(() => asked({ kind: 'person', id: 'owner' }).propose()).toThrow('your owner\'s message')
+ expect(() => asked({ kind: 'person', id: 'peer', generation: 'old' }).propose()).toThrow('your owner\'s message')
+ expect(() => asked(undefined, { source: true }).propose()).toThrow('your owner\'s message')
+ expect(() => asked(undefined, { conversationId: 'elsewhere' }).propose()).toThrow('your owner\'s message')
+ const { f } = asked()
+ expect(() => f.run({ type: 'buddy.propose', conversationId: f.app.conversationId, ownerMessageId: 'ask', ...proposal }, buddy)).toThrow('A Buddy posts only in its own chat')
+ })
+
+ it('names only its owner\'s newest message in the chat, or one from the last hour (privacy review of #1992)', () => {
+ const { f } = asked()
+ const send = (newestOwnerMessageId: string, createdAt: number) => f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal }, buddy,
+ { now: 2 * 3_600_000, proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt, newestOwnerMessageId,
+ author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } })
+ expect(() => send('later', 900)).toThrow('your owner\'s newest message')
+ expect(send('ask', 900).messages).toHaveLength(1)
+ const { f: g } = asked()
+ expect(g.run({ type: 'buddy.propose', conversationId: g.chat, ownerMessageId: 'ask', ...proposal }, buddy,
+ { now: 2 * 3_600_000, proposalAsk: { id: 'ask', conversationId: g.chat, source: false, createdAt: 2 * 3_600_000 - 59 * 60_000, newestOwnerMessageId: 'later',
+ author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } }).messages).toHaveLength(1)
+ })
+
+ it('is a Buddy\'s alone, and only while Buddies are on', () => {
+ const { f, propose } = asked()
+ expect(() => f.run({ type: 'buddy.propose', conversationId: f.app.conversationId, ownerMessageId: 'ask', ...proposal }, agentActor(f.pm))).toThrow('Only a Buddy')
+ expect(() => f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal }, peer)).toThrow('Only a Buddy')
+ f.state.buddies = undefined
+ expect(() => propose()).toThrow('Buddies are off')
+ })
+})
+
+describe('removing a Buddy', () => {
+ /** fresh() with peer's Buddy started on peer's Mac. */
+ function running() {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }
+ const agentId = f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'native', configuration }, peer, host).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: added.result.startId as string, warning: null }, peer, host)
+ return { f, chat: added.result.conversationId as string, agentId }
+ }
+
+ it('is its owner\'s: its session closes and its chat stays for them', () => {
+ const { f, chat, agentId } = running()
+ expect(() => f.run({ type: 'buddy.remove', projectId: f.app.projectId })).toThrow('no Buddy')
+ const removed = f.run({ type: 'buddy.remove', projectId: f.app.projectId }, peer)
+ expect(removed.cancelledAgents).toEqual([agentId])
+ expect(f.state.closingSessions).toEqual([{ agentId, machineId: 'peer-mac', harnessId: 'native', machineOwnerId: 'peer' }])
+ expect(group(f, chat)).toMatchObject({ agentIds: [], archived: false })
+ expect(addBuddy(f, peer, f.app.projectId).result.conversationId).toBe(chat)
+ })
+
+ it('cancels one still starting', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ f.run({ type: 'buddy.remove', projectId: f.app.projectId }, peer)
+ expect(f.state.starts!.find(s => s.id === added.result.startId)!.error).toBe('Removed by its owner before it started.')
+ })
+
+ it('happens when its owner leaves the Swarm, whoever\'s machine it runs on', () => {
+ const { f, agentId } = running()
+ f.state.machines![0]!.contributorId = 'owner'
+ f.state.agents.find(a => a.id === agentId)!.contributorId = 'owner'
+ f.run({ type: 'member.remove', userId: 'peer' })
+ expect(f.state.agents.map(a => a.id)).not.toContain(agentId)
+ })
+
+ it('happens with its project', () => {
+ const { f, agentId } = running()
+ f.run({ type: 'project.delete', projectId: f.app.projectId })
+ expect(f.state.agents.map(a => a.id)).not.toContain(agentId)
+ })
+})
+
+describe('a Buddy is never a worker', () => {
+ it('is never assigned work nor added to a group', () => {
+ const f = setup()
+ f.run({ type: 'tab.buddies', enabled: true })
+ expect(() => f.run({ type: 'work.define', conversationId: f.group, brief: 'Do it', checks: [{ description: 'Done', independent: false }] })).not.toThrow()
+ expect(() => f.run({ type: 'work.assign', conversationId: f.group, agentId: 'buddy' })).toThrow('A Buddy is never assigned work')
+ expect(() => f.run({ type: 'conversation.agent', conversationId: f.group, agentId: 'buddy', present: true, lead: false })).toThrow('A Buddy stays in its own chat')
+ })
+
+ it('is left alone by the idle tidy-up: it waits for its owner', async () => {
+ const { stopIdleWorkers } = await import('./tidy.js')
+ const f = setup(), now = 10 * 3_600_000
+ machine(f, 'machine', 'owner')
+ const buddy = f.state.agents.find(a => a.id === 'buddy')!
+ buddy.startedSession = { creationId: 'c', sessionId: 's', createdAt: new Date(0).toISOString() }
+ // An Engineer just like it, in the same chat, idle as long and reported clean, is stopped: the Buddy is not.
+ f.state.agents.push({ ...structuredClone(buddy), id: 'builder', harnessId: 'builder-harness', buddyOf: undefined })
+ group(f, f.chat).agentIds.push('builder')
+ Object.assign(f.state.machines![0]!.observation!, { receivedAt: now, runningHarnessIds: ['buddy-harness', 'builder-harness'],
+ harnessUncommitted: { 'buddy-harness': false, 'builder-harness': false } })
+ expect(stopIdleWorkers(f.state, f.app.projectId, now, new Set()).map(row => row.source)).toEqual([{ kind: 'idle-stop', agentId: 'builder' }])
+ expect(buddy.workDecision).toBeUndefined()
+ })
+})
+
+describe('Chat with PM while Buddies are on', () => {
+ const on = () => { const f = setup(); f.run({ type: 'tab.buddies', enabled: true }); return f }
+ const say = (conversationId: string) => ({ type: 'message.send' as const, conversationId, text: 'Hi', replyTo: null, recipientIds: [] })
+
+ it('is read-only: no new one, and nobody posts in an old one, the PM included; its history stays readable', () => {
+ const f = on()
+ expect(() => f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'owner', brief: '', checks: [],
+ audience: { personIds: ['owner'] } })).toThrow('Chat with PM is read-only')
+ expect(() => f.run(say(f.pmChat), peer)).toThrow('Chat with PM is read-only')
+ expect(() => f.run(say(f.pmChat), agentActor(f.pm))).toThrow('Chat with PM is read-only')
+ expect(canReadGroup(f.state, peer, group(f, f.pmChat))).toBe(true)
+ })
+
+ it('takes no new decisions: the PM asks in the project chat or a workgroup', () => {
+ const f = on()
+ const ask = (conversationId: string) => f.run({ type: 'decision.ask', conversationId, personId: 'peer',
+ questions: [{ question: 'Which?', options: ['A', 'B'], recommended: 0, unblocks: 'Work' }] }, agentActor(f.pm))
+ expect(() => ask(f.pmChat)).toThrow('Chat with PM is read-only')
+ expect(ask(f.app.conversationId).result.decisionIds).toHaveLength(1)
+ })
+
+ it('works as before while Buddies are off', () => {
+ const f = setup()
+ expect(f.run(say(f.pmChat), peer).messages).toHaveLength(1)
+ })
+})
+
+describe('a Buddy chat as readers get it', () => {
+ it('names its kind and owner and carries no audience, so an app from before Buddies never takes it for Chat with PM', () => {
+ const f = setup()
+ group(f, f.chat).proposals = ['ask']
+ const view = groupView(group(f, f.chat), new Set()) as unknown as Record<string, unknown>
+ expect(view).toMatchObject({ id: f.chat, kind: 'buddy', buddyOwnerId: 'peer', agentIds: ['buddy'] })
+ expect(view).not.toHaveProperty('audience')
+ expect(view).not.toHaveProperty('proposals')
+ expect(groupView(group(f, f.pmChat), new Set())).toHaveProperty('audience')
+ })
+})
+
+describe('a Buddy chat stored in parts', () => {
+ it('comes back as a conversation, never set aside as a kind this release does not know', () => {
+ const f = setup()
+ const back = reassemble(split(f.state, { tabId: 'swarm', version: 1, now: 1000 }))
+ expect(back.conversations.map(c => c.id)).toContain(f.chat)
+ expect(back.parkedConversations).toBeUndefined()
+ })
+})
+
+describe('a Buddy\'s terminal alert', () => {
+ it('tells its owner in their chat, never the PM in the project chat', () => {
+ const f = setup()
+ f.run({ type: 'tab.buddies', enabled: true })
+ const rows = f.run({ type: 'agent.alert', agentId: 'buddy', alert: 'prompt', active: true }, agentActor('buddy')).messages
+ expect(rows.map(r => [r.conversationId, r.recipients])).toEqual([[f.chat, []]])
+ })
+})
+
+describe('a decision left to the PM while Buddies are on', () => {
+ it('puts the PM\'s line in the person\'s Buddy chat, to no one, not in their read-only Chat with PM', () => {
+ const f = setup()
+ const decision = { id: 'decision-1', personId: 'peer', conversationId: f.group, projectId: f.app.projectId, askerAgentId: f.pm,
+ question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 1, answeredAt: null, createdAt: 0, assignmentId: null }
+ const delegate = () => f.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, peer, { decision }).messages
+ .filter(m => (m.source as { kind?: string } | undefined)?.kind === 'decision-delegated')
+ expect(delegate().map(m => m.conversationId)).toEqual([f.pmChat])
+ f.run({ type: 'tab.buddies', enabled: true })
+ expect(delegate()).toEqual([expect.objectContaining({ conversationId: f.chat, recipients: [], text: 'PM decided: To everyone — Ship how?' })])
+ })
+})
+
+describe('starting a down Buddy again', () => {
+ /** fresh() with peer's Buddy started and settled on peer's Mac. */
+ function running() {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }
+ const agentId = f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'native', configuration }, peer, host).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId: added.result.startId as string, warning: null }, peer, host)
+ return { f, chat: added.result.conversationId as string, agentId }
+ }
+
+ it('replaces the person\'s own down Buddy in one step, closing its session and keeping the same chat', () => {
+ const { f, chat, agentId } = running()
+ f.state.agents.find(a => a.id === agentId)!.downSince = new Date(500).toISOString()
+ const again = addBuddy(f, peer, f.app.projectId)
+ expect(again.result.conversationId).toBe(chat)
+ expect(again.cancelledAgents).toEqual([agentId])
+ expect(f.state.agents.map(a => a.id)).not.toContain(agentId)
+ expect(f.state.closingSessions).toEqual([{ agentId, machineId: 'peer-mac', harnessId: 'native', machineOwnerId: 'peer' }])
+ expect(f.state.starts!.find(s => s.id === again.result.startId)!.request).toMatchObject({ conversationId: chat, buddyOf: { personId: 'peer' } })
+ expect(group(f, chat).agentIds).toEqual([])
+ })
+
+ it('counts a Buddy as down when its machine stopped reporting', () => {
+ const { f, agentId } = running()
+ const late = 1000 + 10 * 60_000
+ expect(() => f.run({ type: 'buddy.create', projectId: f.app.projectId, machineId: 'peer-mac', engine: 'claude' }, peer,
+ { now: late, contribution: { machineOwnerId: 'peer', contributorId: 'peer' } })).toThrow()
+ expect(f.state.agents.map(a => a.id)).toContain(agentId)
+ f.state.machines!.push({ ...structuredClone(f.state.machines![0]!), machineId: 'spare-mac', observation: { ...structuredClone(f.state.machines![0]!.observation!), receivedAt: late } })
+ const again = f.run({ type: 'buddy.create', projectId: f.app.projectId, machineId: 'spare-mac', engine: 'claude' }, peer,
+ { now: late, contribution: { machineOwnerId: 'peer', contributorId: 'peer' } })
+ expect(again.cancelledAgents).toEqual([agentId])
+ })
+
+ it('still refuses while the Buddy runs', () => {
+ const { f, agentId } = running()
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('You already have a Buddy in this project')
+ expect(f.state.agents.map(a => a.id)).toContain(agentId)
+ })
+})
+
+describe('a Buddy chat\'s readers are fixed (privacy review of #1992)', () => {
+ it('refuses adding people or agents to it, the Swarm owner and the PM included', () => {
+ const f = setup()
+ f.run({ type: 'tab.buddies', enabled: true })
+ expect(() => f.run({ type: 'conversation.audience', conversationId: f.chat, personIds: ['peer', 'owner'] }, peer)).toThrow('A Buddy chat stays its owner\'s')
+ expect(() => f.run({ type: 'conversation.agent', conversationId: f.chat, agentId: f.pm, present: true, lead: false }, peer)).toThrow('A Buddy chat stays its owner\'s')
+ expect(group(f, f.chat)).toMatchObject({ agentIds: ['buddy'], audience: { people: [{ id: 'peer', generation: 'first' }] } })
+ })
+})
+
+describe('turning Buddies off while one starts (privacy review of #1992)', () => {
+ it('fails its pending start, refuses its join, and refuses a Buddy\'s posts', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ f.run({ type: 'tab.buddies', enabled: false })
+ expect(f.state.starts!.find(s => s.id === added.result.startId)!.error).toBe('Buddies were turned off in this Swarm.')
+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }
+ expect(() => f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'late', configuration }, peer, host)).toThrow()
+ expect(f.state.agents.some(a => a.harnessId === 'late')).toBe(false)
+ // One that joined before the switch and is still listed cannot post.
+ const g = setup()
+ expect(() => g.run({ type: 'message.send', conversationId: g.chat, text: 'Still here', replyTo: null, recipientIds: [] }, agentActor('buddy'))).toThrow('Buddies are off')
+ })
+
+ it('refuses a dispatched Buddy start joining once Buddies are off, even if its start record has no error', () => {
+ const f = fresh()
+ const added = addBuddy(f, peer, f.app.projectId)
+ delete f.state.buddies
+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }
+ expect(() => f.run({ type: 'agent.started', startId: added.result.startId as string, harnessId: 'late', configuration }, peer, host)).toThrow('Buddies are off')
+ expect(() => f.run({ type: 'agent.startDispatch', startId: added.result.startId as string }, peer, host)).toThrow('Buddies are off')
+ })
+})
+
+describe('where a Buddy runs (Ken\'s ruling, 10-28)', () => {
+ const contribution = (f: ReturnType<typeof setup>, machineId: string, owner: string) =>
+ ({ contribution: { machineOwnerId: owner, contributorId: f.state.machines!.find(m => m.machineId === machineId)!.contributorId } })
+ const add = (f: ReturnType<typeof setup>, machineId: string, owner: string, engine: 'claude' | 'codex' = 'claude', projectId = f.app.projectId) =>
+ f.run({ type: 'buddy.create', projectId, machineId, engine }, peer, contribution(f, machineId, owner))
+
+ it('is only its owner\'s own machine, for Claude and Codex alike: never one shared with them', () => {
+ const f = fresh()
+ machine(f, 'owner-mac', 'owner')
+ for (const engine of ['claude', 'codex'] as const) {
+ expect(() => add(f, 'owner-mac', 'owner', engine)).toThrow('A Buddy runs only on your own machine')
+ }
+ expect(add(f, 'peer-mac', 'peer', 'codex').result.startId).toBeTruthy()
+ })
+
+ it('is never a Harness Team account, not even the one on its owner\'s own Mac', () => {
+ const f = fresh()
+ machine(f, 'peer-team', 'peer')
+ Object.assign(f.state.machines!.find(m => m.machineId === 'peer-team')!, { hostMachineId: 'peer-mac' })
+ f.state.machines!.find(m => m.machineId === 'peer-team')!.observation!.sessionKind = 'team'
+ expect(() => add(f, 'peer-team', 'peer')).toThrow('A Buddy runs only on your own machine')
+ })
+
+ it('stays in its owner\'s own account for a teammate\'s project, even where teammates\' work needs a Team account', () => {
+ const f = fresh()
+ const saved = { required: process.env.SWARM_TEAM_ACCOUNT_REQUIRED, owners: process.env.SWARM_TEAM_ACCOUNT_OWNERS }
+ process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1'
+ delete process.env.SWARM_TEAM_ACCOUNT_OWNERS
+ try {
+ machine(f, 'peer-team', 'peer')
+ Object.assign(f.state.machines!.find(m => m.machineId === 'peer-team')!, { hostMachineId: 'peer-mac' })
+ // A Builder for the owner's project would be refused here, or moved to the Mac's Team account.
+ const start = add(f, 'peer-mac', 'peer').result.startId
+ expect(f.state.starts!.find(s => s.id === start)!.request.machineId).toBe('peer-mac')
+ } finally {
+ if (saved.required === undefined) delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED; else process.env.SWARM_TEAM_ACCOUNT_REQUIRED = saved.required
+ if (saved.owners !== undefined) process.env.SWARM_TEAM_ACCOUNT_OWNERS = saved.owners
+ }
+ })
+})
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
new file mode 100644
index 000000000..04a855c59
--- /dev/null
+++ b/backend/src/superTabs/buddies.ts
@@ -0,0 +1,56 @@
+/** Buddies (Ken's spec, 10-28): each person may add their own agent per project and brainstorm with it in a chat only they
+ * read. When they ask, it posts one proposal in the project chat on their behalf; the PM assigns the work as usual. A Buddy
+ * reads only its project's chat and its own chat, and does nothing but post in its chat and propose. Behind the Swarm's
+ * `buddies` setting, off by default. */
+import { fail, stableId, type Agent, type AgentStartRequest, type Conversation, type Person } from './model.js'
+
+export const isBuddy = (target: Pick<Agent, 'buddyOf'>): boolean => !!target.buddyOf
+export const isBuddyChat = (group: Pick<Conversation, 'kind'>): boolean => group.kind === 'buddy'
+
+/** Whether a Buddy reads [group] of its own project: the project chat, and its own owner's chat it is in. */
+export function buddyReads(buddy: Agent, group: Conversation, leadConversationId: string): boolean {
+ if (group.id === leadConversationId) return true
+ return isBuddyChat(group) && group.agentIds.includes(buddy.id) && group.audience?.people.some(p => p.id === buddy.buddyOf!.personId) === true
+}
+
+/** A person's Buddy chat in a project, the same each time they add a Buddy there; a new membership opens a new one, as a
+ * private conversation's audience is held at the membership it was opened in. */
+export const buddyChatId = (projectId: string, owner: Pick<Person, 'id' | 'generation'>): string => stableId('buddy', projectId, owner.id, owner.generation)
+
+/** What a Buddy asks of its machine: it reads and talks, so the usual agent's share with git to read the project. */
+export const BUDDY_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 85,
+ tools: ['git'], devices: [], quotaRequired: false }
+
+/** The line a Buddy's chat shows once its session joined. */
+export const buddyReady = (name: string): string => `${name} is ready. Tell it what you have in mind.`
+
+/** What a Buddy may send: posts in its own chat, its owner's proposals, and what its machine reports for every agent (its
+ * model, a terminal alert, its own stop). Every other command is refused, so it can never assign, start, route, ask
+ * decisions or change anything for its owner (spec constraint: PRIVACY-CRITICAL). */
+const SPEAKS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'buddy.propose'])
+const BUDDY_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'buddy.propose', 'agent.configuration', 'agent.alert',
+ 'agent.stopLease', 'agent.stopRefused', 'agent.remove'])
+
+export function requireBuddyCommand(buddy: Agent, command: { type: string; conversationId?: unknown; agentId?: unknown }, groups: readonly Conversation[],
+ on: boolean): void {
+ if (!BUDDY_COMMANDS.has(command.type)) fail('BUDDY_FORBIDDEN', 'A Buddy only talks with its owner and sends the proposals they ask for.', 403)
+ // Its host's reports and its own stop still go through, so a Buddy left over from before the switch winds down.
+ if (!on && SPEAKS.has(command.type)) fail('BUDDIES_OFF', 'Buddies are off in this Swarm.', 403)
+ if ('agentId' in command && command.agentId !== buddy.id) fail('BUDDY_FORBIDDEN', 'A Buddy acts only for itself.', 403)
+ if (command.type === 'message.send' || command.type === 'message.react' || command.type === 'buddy.propose') {
+ const group = groups.find(g => g.id === command.conversationId)
+ if (!group || !isBuddyChat(group) || !group.agentIds.includes(buddy.id)) {
+ fail('BUDDY_FORBIDDEN', 'A Buddy posts only in its own chat. Send a proposal to reach the PM.', 403)
+ }
+ }
+}
+
+/** The asks a Buddy chat remembers having proposed for, newest last: an older one could be named again only after 200 more. */
+export const MAX_PROPOSAL_ASKS = 200
+/** How long an owner's message, other than their newest in the chat, may still be named as asking for a proposal. */
+export const PROPOSAL_ASK_MS = 60 * 60_000
+
+/** Written by the server, never the Buddy: who it is for and on whose behalf, then the three parts the PM needs. */
+export function proposalText(owner: string, proposal: { goal: string; scope: string; priority: string }): string {
+ return `Proposal from ${owner}'s Buddy, on ${owner}'s behalf.\n\nGoal: ${proposal.goal}\nScope: ${proposal.scope}\nPriority: ${proposal.priority}`
+}
diff --git a/backend/src/superTabs/cachedReads.ts b/backend/src/superTabs/cachedReads.ts
index 43454f0b8..b480010f5 100644
--- a/backend/src/superTabs/cachedReads.ts
+++ b/backend/src/superTabs/cachedReads.ts
@@ -10,6 +10,7 @@ import { CacheView } from './cache.js'
import * as store from './parts/index.js'
import type { GroupData, Part, SwarmParts } from './parts/index.js'
import { startFinished } from './parts/write.js'
+import { retryTransient } from './retry.js'
import { retryStaleIndex } from './parts/indexed.js'
type Db = Pick<PrismaClient, '$transaction'> & Prisma.TransactionClient
@@ -29,9 +30,10 @@ const FEED_SLACK_MS = 15_000
export const readMachines = (db: Prisma.TransactionClient, view: CacheView, tabId: string) =>
view.get(tabId, 'machines', 'all', () => store.loadMachines(db, tabId))
-/** The active parts, then the machines: one read of the base in a transaction, so its parts are one snapshot. */
+/** The active parts, then the machines: one read of the base in a transaction, so its parts are one snapshot. A transaction
+ * that meets a lock it cannot get in 5 ms (an index build, a release) is tried again as a write's would be (retry.ts). */
const base = (db: Db, view: CacheView, tabId: string) => Promise.all([
- view.get(tabId, 'parts', 'main', () => retryStaleIndex(() => db.$transaction(tx => store.loadReadBase(tx, tabId)))),
+ view.get(tabId, 'parts', 'main', () => retryTransient(() => retryStaleIndex(() => db.$transaction(tx => store.loadReadBase(tx, tabId))))),
readMachines(db, view, tabId),
])
@@ -62,7 +64,7 @@ export async function readLight(db: Db, view: CacheView, tabId: string, opts: Om
const name = `light:${JSON.stringify([opts.groups ?? 'active', !!opts.includeRecentStarts, ...(['groupIds', 'agentIds', 'projectIds'] as const)
.map(key => [...opts[key] ?? []].sort())])}`
const [light, machines] = await Promise.all([
- view.get(tabId, name, 'main', () => retryStaleIndex(() => db.$transaction(tx => store.loadLight(tx, tabId, { ...opts, machines: false })))),
+ view.get(tabId, name, 'main', () => retryTransient(() => retryStaleIndex(() => db.$transaction(tx => store.loadLight(tx, tabId, { ...opts, machines: false }))))),
readMachines(db, view, tabId),
])
return { ...light, machines }
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 267de0c49..d6b8c14eb 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,10 +1,10 @@
-import { admitMachineStart, cleanupOverdue, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, ownedMachine, requireTeamWork, teamMachineFor, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
+import { admitMachineStart, cleanupOverdue, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, ownedMachine, projectFolder, requireTeamWork, teamMachineFor, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
activeWork, actorKey, agent, agentRole, appendPullRequestUrls, author, conversation, crossProjectActive, fail, isLeads, person, stableId, syncLeads, numberConversations, nextConversationNumber, renderWorkTask,
finishWorker, requireWorkerDecisions, reviewing, seenMachineIds, swarmGridName, visibleState, AGENT_ONLY,
- type Actor, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,
+ type Actor, type AgentStartRequest, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,
} from './model.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSchema } from './routingPolicy.js'
@@ -26,6 +26,7 @@ import { shipNotice, shippedAt } from './ship.js'
import { openReview, openReviewOf, projectPullRequest, verdictPending } from './autoReview.js'
import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'
import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
+import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -91,6 +92,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),
z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),
z.object({ type: z.literal('tab.tidy'), enabled: z.boolean(), askedIn: askedInSchema.optional() }).strict(),
+ z.object({ type: z.literal('tab.buddies'), enabled: z.boolean(), askedIn: askedInSchema.optional() }).strict(),
z.object({ type: z.literal('rule.set'), projectId: id.optional(), rule: ruleSchema, text: ruleTextSchema, askedIn: askedInSchema.optional() }).strict(),
z.object({ type: z.literal('rule.remove'), projectId: id.optional(), ruleId: id, askedIn: askedInSchema.optional() }).strict(),
z.object({ type: z.literal('project.create'), name: title, visibility: z.enum(['public', 'private']), brief: z.string().trim().max(8000).default('') }).strict(),
@@ -125,6 +127,13 @@ export const commandSchema = z.discriminatedUnion('type', [
mergedAt: z.iso.datetime().optional() }).strict(),
z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), roleId: roleId.optional(), initialMessage: text.optional() }).strict(),
z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),
+ // A Buddy's proposal for its owner, posted in its project's chat: `conversationId` is its own chat, and `ownerMessageId` its
+ // owner's message there asking for it.
+ z.object({ type: z.literal('buddy.propose'), conversationId: id, ownerMessageId: id, goal: z.string().trim().min(1).max(2000),
+ scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']) }).strict(),
+ z.object({ type: z.literal('buddy.remove'), projectId: id }).strict(),
+ // A person's own Buddy in a project, on a machine of the Swarm (buddies.ts).
+ z.object({ type: z.literal('buddy.create'), projectId: id, machineId: id, engine: swarmEngine, model: z.string().trim().min(1).max(200).optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration,
startedSession: z.object({ sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
@@ -189,6 +198,7 @@ export const operationSchema = z.object({ operationId: id, command: commandSchem
* chat row is redacted (terminal.ts). Not a role's skill text, which only its project's owner, Lead and hosts read. */
const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'message.send': ['text'],
+ 'buddy.propose': ['goal', 'scope'],
'member.status': ['status.text'],
'agent.add': ['name', 'initialMessage'],
'agent.start': ['request.name', 'overrideReason'],
@@ -254,6 +264,10 @@ export interface CommandContext {
reply?: { id: string; conversationId: string; author: Author; createdAt: number }
/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */
openTags?: Array<{ messageId: string; createdAt: number }>
+ /** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. */
+ proposalAsk?: { id: string; conversationId: string; author: Author; source: boolean; createdAt: number
+ /** The owner's newest message in that chat, which may always be named. */
+ newestOwnerMessageId?: string }
/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */
askedIn?: { author: Author; source: boolean; createdAt: number }
/** The newest messages of this conversation before the one being sent, newest first, loaded by the store for `message.send`. */
@@ -315,6 +329,7 @@ function leadWorkerBounced(recent: CommandContext['recent'] = [], leadId: string
/** A Reviewer is assigned only review groups, and a review group only a Reviewer. */
function assignable(group: Conversation, worker: Agent): void {
+ if (isBuddy(worker)) fail('BUDDY_NOT_ASSIGNABLE', 'A Buddy is never assigned work: it brainstorms with its owner. Assign an Engineer.')
const reviewer = agentRole(worker) === 'reviewer'
if (reviewer && !group.reviewOf) fail('REVIEWER_NOT_ASSIGNABLE', 'A Reviewer is assigned only review groups. Assign a Builder.')
if (!reviewer && group.reviewOf) fail('REVIEW_GROUP', 'A review group is assigned only to a Reviewer.')
@@ -407,6 +422,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if (command.type === 'mention.done' || command.type === 'decision.answer') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
+ const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
+ if (buddy) requireBuddyCommand(buddy, command, state.conversations, !!state.buddies)
// An invitation's group is only where the person lands, and invite.create replaces a deleted one (inviteLanding).
if ('conversationId' in command && command.type !== 'invite.create') {
const group = readConversation(state, actor, command.conversationId)
@@ -415,7 +432,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if ('projectId' in command && command.projectId) readProject(state, actor, command.projectId)
if ('agentId' in command) readAgent(state, actor, command.agentId)
if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)
- if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {
+ if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
+ || command.type === 'tab.buddies') && command.askedIn) {
readConversation(state, actor, command.askedIn.conversationId)
}
if ('startId' in command && command.type !== 'route.modelResult') {
@@ -605,6 +623,21 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
return project
}
+ /** No private channel to the PM while Buddies are on (Ken's spec, 10-28): a Chat with PM keeps its history, read only. */
+ const pmChatClosed = (pmChat: boolean) => {
+ if (state.buddies && pmChat) {
+ fail('PM_CHAT_READ_ONLY', 'Chat with PM is read-only while Buddies are on. Talk to the PM in the project chat, or brainstorm with your Buddy.', 403)
+ }
+ }
+ /** A Swarm-wide switch is the Swarm owner's, or a Lead's passing on a chat message the Swarm owner wrote in the last day,
+ * as rules are. */
+ const swarmOwnerAsked = (askedIn: { conversationId: string; messageId: string } | undefined, what: string) => {
+ if (actor.kind === 'person' && actor.userId === state.ownerId) return
+ const asked = actor.kind === 'agent' && ledProject(state, actor.agentId) && askedIn && context.askedIn
+ if (!asked || asked.author.kind !== 'person' || asked.author.id !== state.ownerId || asked.source || context.now - asked.createdAt > RULE_MESSAGE_MS) {
+ fail('OWNER_REQUIRED', `Only the Swarm owner, or a Lead passing on a chat message the owner wrote in the last day, ${what}.`, 403)
+ }
+ }
const openDecision = (): RouteDecision => {
const decision = context.routeDecision ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
if (decision.outcome) fail('ROUTE_CLOSED', 'This routing decision is no longer open. Route the task again.')
@@ -1038,17 +1071,23 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
state.paused = command.paused
break
case 'tab.tidy': {
- // The Swarm owner's, or a Lead's passing on a chat message the Swarm owner wrote in the last day, as rules are.
- if (!(actor.kind === 'person' && actor.userId === state.ownerId)) {
- const asked = actor.kind === 'agent' && ledProject(state, actor.agentId) && command.askedIn && context.askedIn
- if (!asked || asked.author.kind !== 'person' || asked.author.id !== state.ownerId || asked.source || context.now - asked.createdAt > RULE_MESSAGE_MS) {
- fail('OWNER_REQUIRED', 'Only the Swarm owner, or a Lead passing on a chat message the owner wrote in the last day, turns tidying on or off.', 403)
- }
- }
+ swarmOwnerAsked(command.askedIn, 'turns tidying on or off')
if (command.enabled) delete state.tidy
else state.tidy = false
break
}
+ case 'tab.buddies': {
+ swarmOwnerAsked(command.askedIn, 'turns Buddies on or off')
+ if (command.enabled) state.buddies = true
+ else {
+ delete state.buddies
+ // Off means no Buddy runs: each one's session closes, one still starting never joins, and its chat stays for its
+ // owner to read (privacy review of #1992).
+ for (const target of state.agents.filter(isBuddy)) removeAgent(target)
+ for (const start of state.starts ?? []) if (start.request.buddyOf && !start.harnessId && !start.error) start.error = 'Buddies were turned off in this Swarm.'
+ }
+ break
+ }
case 'tab.routingPolicy':
if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can change its routing policy.', 403)
if (command.policy && Object.keys(command.policy).length) state.routingPolicy = command.policy
@@ -1082,6 +1121,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
requirable(command.task)
if (command.audience) {
+ pmChatClosed(true)
// A private conversation is chat only: no task, checks or review, so private work never reaches other Leads.
if (command.task || command.checks.length || command.reviewOf || command.requesterId) fail('AUDIENCE_CHAT_ONLY', 'A private conversation is chat only.', 400)
if (actor.kind === 'person' && !command.audience.personIds.includes(actor.userId)) {
@@ -1120,6 +1160,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
case 'decision.ask': {
const group = open(state, command.conversationId)
+ pmChatClosed(!!group.audience && !isBuddyChat(group))
effects.decisions = askDecisions(state, group, command.personId, command.questions,
{ operationId, askerAgentId: checkAsker(state, actor, group), assignmentId: null })
result.decisionIds = effects.decisions.map(d => d.id)
@@ -1171,6 +1212,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'conversation.audience': {
// Who may read it already passed (readConversation): only its listed people and the project's Lead get here.
const group = open(state, command.conversationId)
+ if (isBuddyChat(group)) fail('BUDDY_CHAT_FIXED', 'A Buddy chat stays its owner\'s and their Buddy\'s: nobody else is added to it.', 403)
if (!group.audience) fail('AUDIENCE_FIXED', 'A shared conversation stays shared. Open a private conversation instead.', 400)
group.audience = audienceOf(state, groupProject(state, group), command.personIds)
break
@@ -1296,12 +1338,96 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
ruled(startTarget(request), request.conversationId, `${who} started ${request.name}`, personChose)
break
}
+ case 'buddy.propose': {
+ const self = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
+ if (!self) fail('BUDDY_ONLY', 'Only a Buddy sends a proposal, for its owner.', 403)
+ if (!state.buddies) fail('BUDDIES_OFF', 'Buddies are off in this Swarm. Its owner can turn them on.', 403)
+ const owner = state.people.find(p => p.id === self.buddyOf!.personId && p.generation === self.buddyOf!.generation)
+ ?? fail('BUDDY_OWNER_GONE', 'Your owner left this Swarm.', 403)
+ const chat = conversation(state, command.conversationId)
+ if (!isBuddyChat(chat) || !chat.agentIds.includes(self.id)) fail('BUDDY_FORBIDDEN', 'Name your own chat: a proposal comes from there.', 403)
+ // Its owner said to send it: their own message in its chat, never a row the system wrote, and each one asks once.
+ const ask = context.proposalAsk
+ if (!ask || ask.id !== command.ownerMessageId || ask.conversationId !== chat.id || ask.source || ask.author.kind !== 'person'
+ || ask.author.id !== owner.id || ask.author.membershipGeneration !== owner.generation) {
+ fail('PROPOSAL_UNASKED', 'Send a proposal only when your owner asks for it: name your owner\'s message in your chat that asked.', 403)
+ }
+ // Its newest message there, or one from the last hour: an old ask is not a standing order (privacy review of #1992).
+ if (ask.newestOwnerMessageId !== ask.id && context.now - ask.createdAt > PROPOSAL_ASK_MS) {
+ fail('PROPOSAL_STALE', 'Send a proposal for your owner\'s newest message in your chat, or one from the last hour. Ask them again.', 403)
+ }
+ if (chat.proposals?.includes(command.ownerMessageId)) fail('PROPOSAL_SENT', 'A proposal was already sent for that message. Ask your owner before sending another.')
+ chat.proposals = [...chat.proposals ?? [], command.ownerMessageId].slice(-MAX_PROPOSAL_ASKS)
+ const project = projectOf(state, agentProjectId(state, self)), home = conversation(state, project.leadConversationId)
+ const name = owner.email.split('@')[0]!
+ message(home.id, proposalText(name, command), home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [], null,
+ { kind: 'buddy-proposal', personId: owner.id, ownerMessageId: command.ownerMessageId })
+ break
+ }
+ case 'buddy.remove': {
+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person removes their own Buddy.', 403)
+ const project = readProject(state, actor, command.projectId), me = person(state, actor.userId)
+ const chatId = buddyChatId(project.id, me)
+ const target = state.agents.find(a => a.buddyOf?.personId === me.id && agentProjectId(state, a) === project.id)
+ const starting = state.starts?.filter(s => s.request.conversationId === chatId && !s.harnessId && !s.error) ?? []
+ if (!target && !starting.length) fail('NOT_FOUND', 'You have no Buddy in this project.', 404)
+ for (const start of starting) start.error = 'Removed by its owner before it started.'
+ // Its session closes; its chat stays, and adding a Buddy again reopens it.
+ if (target) removeAgent(target)
+ break
+ }
+ case 'buddy.create': {
+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person adds their own Buddy.', 403)
+ if (!state.buddies) fail('BUDDIES_OFF', 'Buddies are off in this Swarm. Its owner can turn them on.', 403)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ const project = readProject(state, actor, command.projectId), me = person(state, actor.userId)
+ const chatId = buddyChatId(project.id, me)
+ // A down Buddy is replaced (Desktop's Start again, review of #1992): its session closes in this same command, so a
+ // start refused below leaves it as it was. A running or starting one is kept.
+ const existing = state.agents.find(a => a.buddyOf?.personId === me.id && agentProjectId(state, a) === project.id)
+ if ((existing && !downSince(state, existing, context.now)) || state.starts?.some(s => s.request.conversationId === chatId && !s.harnessId && !s.error)) {
+ fail('BUDDY_EXISTS', 'You already have a Buddy in this project. Remove it to add another.')
+ }
+ if (existing) removeAgent(existing)
+ // A Buddy runs where the Swarm's agents run, under that machine's own rules: its Machines list.
+ const pool = machineContribution(state, command.machineId) ?? fail('BUDDY_MACHINE', 'Add this machine to the Swarm first: a Buddy runs on one of its machines.', 403)
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'Choose a machine shared with the contributor.', 403)
+ // Like a Lead, a Buddy runs only on its owner's own machine, in their own account, for Claude and Codex alike: never a
+ // machine shared with them, and never a Harness Team account (Ken's ruling, 10-28).
+ if (pool.contributorId !== me.id || grant.machineOwnerId !== me.id || pool.hostMachineId || pool.observation?.sessionKind === 'team') {
+ fail('BUDDY_OWN_MACHINE', 'A Buddy runs only on your own machine. Pick one of yours from the Swarm\'s Machines list.', 403)
+ }
+ const contributor = person(state, grant.contributorId)
+ let chat = state.conversations.find(c => c.id === chatId)
+ if (!chat) {
+ const number = nextConversationNumber(state)
+ state.groupCounter = number
+ chat = { id: chatId, kind: 'buddy', ...(state.projects ? { projectId: project.id } : {}), number, title: `${who}'s Buddy`, leadId: null, agentIds: [],
+ archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0, audience: audienceOf(state, project, [me.id]) }
+ state.conversations.push(chat)
+ }
+ chat.archived = false
+ // Never moved to the Mac's Team account, as a teammate's project otherwise is (machines.ts teamStartRequest).
+ const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,
+ ...(command.model ? { model: command.model } : {}), name: `${who}'s Buddy`, cwd: projectFolder(pool, project), worktree: true,
+ requirements: BUDDY_REQUIREMENTS, buddyOf: { personId: me.id, generation: me.generation } }
+ const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!
+ state.starts ??= []
+ if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
+ state.starts.push({ poolGeneration: admitted.generation, id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
+ contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,
+ hostGrant: grant.hostGrant ?? null, request, harnessId: null, dispatched: false, error: null, requestedAt: context.now })
+ result.startId = operationId
+ result.conversationId = chatId
+ break
+ }
case 'agent.startDispatch':
case 'agent.started':
case 'agent.startSettled':
case 'agent.startFailed': {
const start = state.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
if (start.actorKey !== actorKey(actor)) fail('FORBIDDEN', 'Only the initiating lead can complete this start.', 403)
+ if (start.request.buddyOf && !state.buddies && command.type !== 'agent.startFailed') fail('BUDDIES_OFF', 'Buddies are off in this Swarm. Its owner can turn them on.', 403)
if (person(state, start.contributorId).generation !== start.membershipGeneration) fail('FORBIDDEN', 'This contribution was withdrawn.', 403)
controls(state, actor, start.request.conversationId)
if (command.type === 'agent.startDispatch') {
@@ -1327,7 +1453,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!start.poolGeneration || !start.harnessId || start.error) fail('START_PENDING', 'This contributed start is not ready to settle.')
if (!start.poolSettled) message(start.request.conversationId, command.warning
? `${start.request.name}: ${command.warning}`
- : `${start.request.name} is ready for an assignment.`, [], null, SYSTEM_ROW)
+ : start.request.buddyOf ? buddyReady(start.request.name) : `${start.request.name} is ready for an assignment.`, [], null, SYSTEM_ROW)
start.poolSettled = true
break
}
@@ -1356,11 +1482,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,
...(start.request.role ? { role: start.request.role } : {}), ...(start.request.roleId ? { roleId: start.request.roleId } : {}),
...(start.request.gridModel ? { gridModel: start.request.gridModel } : {}),
+ ...(start.request.buddyOf ? { buddyOf: start.request.buddyOf } : {}),
...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })
group.agentIds.push(agentId)
start.harnessId = command.harnessId
result.agentId = agentId
- message(group.id, start.poolGeneration
+ // A Buddy always starts on a Swarm machine: its chat hears once it settles, as the Lead does for a worker.
+ if (!start.request.buddyOf) message(group.id, start.poolGeneration
? `${start.request.name} joined. Preparing its model.`
: `${start.request.name} joined. Ready for an assignment.`, [], null, SYSTEM_ROW)
break
@@ -1496,7 +1624,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'conversation.agent': {
controls(state, actor, command.conversationId)
const group = open(state, command.conversationId)
+ if (isBuddyChat(group)) fail('BUDDY_CHAT_FIXED', 'A Buddy chat stays its owner\'s and their Buddy\'s: nobody else is added to it.', 403)
const member = agent(state, command.agentId)
+ if (isBuddy(member)) fail('BUDDY_CHAT_ONLY', 'A Buddy stays in its own chat: its owner\'s alone.', 403)
sameProject(state, group, member)
if (member.workDecision === 'stop' && command.lead) fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
const reviewer = agentRole(member) === 'reviewer'
@@ -1564,7 +1694,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
for (const pool of state.machines?.filter(m => m.contributorId === member.id && !m.removal) ?? []) {
removeMachine(pool.machineId, pool, state.agents.filter(a => a.machineId === pool.machineId), machine => `${machine} left the Swarm with its owner`)
}
- for (const target of state.agents.filter(a => a.contributorId === member.id)) removeAgent(target)
+ // Their Buddies go with them, on whosever machine they run.
+ for (const target of state.agents.filter(a => a.contributorId === member.id || a.buddyOf?.personId === member.id)) removeAgent(target)
state.people = state.people.filter(p => p.id !== member.id)
state.invitations = state.invitations.filter(i => i.email !== member.email)
result.removedUserId = member.id
@@ -1572,6 +1703,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
case 'message.send': {
const group = postable(state, actor, command.conversationId)
+ pmChatClosed(!!group.audience && !isBuddyChat(group))
const ids = [...new Set(command.attachmentIds ?? [])]
const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))
if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)
@@ -1591,7 +1723,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const workerToLead = actor.kind === 'agent' && activeWork(group) && group.assignment?.agentId === actor.agentId
&& group.leadId && group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? group.leadId : null
const agentRecipient = leadToWorker ?? workerToLead
- const automatic = actor.kind === 'person' ? (replyAgent && group.agentIds.includes(replyAgent) ? replyAgent : group.leadId) : agentRecipient
+ // A Buddy chat has no Lead: its owner talks to its Buddy.
+ const automatic = actor.kind === 'person' ? (replyAgent && group.agentIds.includes(replyAgent) ? replyAgent
+ : isBuddyChat(group) ? group.agentIds[0] ?? null : group.leadId) : agentRecipient
// In the Leads conversation everything posted reaches every other Lead; naming some only adds emphasis.
const everyLead = isLeads(group) ? group.agentIds.filter(id => actor.kind !== 'agent' || id !== actor.agentId) : []
const recipients = [...new Set([...command.recipientIds, ...everyLead,
diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.ts
index e288642ff..192ead00f 100644
--- a/backend/src/superTabs/decisions.ts
+++ b/backend/src/superTabs/decisions.ts
@@ -3,6 +3,7 @@
* with one tap, and the answer reaches the asking agent and the Lead in the conversation it came from. Decisions live in
* SuperTabDecision, never in the tab state, as mentions do. A decision is not a private channel: anything private goes
* through Chat with PM. Called inside SuperTabStore's transactions. */
+import { isBuddyChat } from './buddies.js'
import { createHash } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { z } from 'zod'
@@ -104,11 +105,13 @@ export function answerDecision(state: SuperTabState, actor: Actor, decision: Dec
}
/** The Lead's one line saying what it chose, in the person's own Chat with PM of that project: only they read it, and they
- * were asked the question. None when they have no open one with the Lead in it. */
+ * were asked the question. None when they have no open one with the Lead in it. While Buddies are on, Chat with PM is
+ * read-only and decisions live with the Buddy (Ken's spec, 10-28): the line goes to their Buddy chat instead, or nowhere. */
function delegatedLine(state: SuperTabState, actor: Actor, projectId: string, leadId: string, asked: DecisionTarget, choice: number) {
const lead = state.agents.find(a => a.id === leadId)
- const chat = state.conversations.find(c => !c.archived && c.audience?.people.length === 1 && c.audience.people[0]!.id === asked.personId
- && groupProject(state, c).id === projectId && c.agentIds.includes(leadId) && canReadGroup(state, actor, c))
+ const theirs = (c: Conversation) => !c.archived && c.audience?.people.length === 1 && c.audience.people[0]!.id === asked.personId
+ && groupProject(state, c).id === projectId && canReadGroup(state, actor, c)
+ const chat = state.conversations.find(c => theirs(c) && (state.buddies ? isBuddyChat(c) : !isBuddyChat(c) && c.agentIds.includes(leadId)))
if (!lead || !chat) return null
const author: Author = { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration }
const question = asked.question.replace(/\s+/g, ' ')
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 161489d16..2c8ee62d9 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -1,4 +1,4 @@
-import { activeWork, stableId, type Agent, type Assignment, type Author, type Conversation, type MessageDraft,
+import { activeWork, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,
type SuperTabState } from './model.js'
import { agentDisplayName } from './agentNames.js'
import { failureNotice, STILL_PREPARING_SUFFIX, STOPPED_REPORTING_SUFFIX, TIMED_OUT_SUFFIX } from './startFailure.js'
@@ -164,14 +164,35 @@ export function judgedMachines(before: SuperTabState, state: SuperTabState, rows
return [...machines].filter(id => state.machines?.some(m => m.machineId === id)).map(key => ({ kind: 'machine' as const, key }))
}
+/** A Buddy chat has no Lead: its owner reads why their Buddy did not start, written as theirs and sent to no one. */
+function buddyNotice(state: SuperTabState, start: AgentStart): MessageDraft[] {
+ const owner = state.people.find(p => p.id === start.request.buddyOf!.personId && p.generation === start.request.buddyOf!.generation)
+ if (!owner || !state.conversations.some(c => c.id === start.request.conversationId)) return []
+ return [{ id: stableId('start-timeout', start.id), conversationId: start.request.conversationId, replyTo: null, recipients: [],
+ author: { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation },
+ // Their own Buddy on a machine of the Swarm: the reason names only that machine, so its owner reads it whole.
+ text: `Could not start ${start.request.name}: ${start.error!}`, source: { kind: 'start-timeout', startId: start.id } }]
+}
+
/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and
* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */
export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {
return [...loseTasks(state, now), ...failStalledStarts(state, now)]
}
+/** A Buddy's start its machine has not taken this long after it was asked for, while that machine reports, has failed: a
+ * host from before Buddies never sees one (read/hostRows.ts). */
+export const BUDDY_PICKUP_MS = 5 * 60_000
+
function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {
return (state.starts ?? []).flatMap(start => {
+ if (start.request.buddyOf && !start.dispatched && !start.harnessId && !start.error && start.requestedAt !== undefined
+ && now - start.requestedAt > BUDDY_PICKUP_MS) {
+ const report = state.machines?.find(m => m.machineId === start.request.machineId)?.observation
+ if (!report || now - report.receivedAt > MACHINE_FRESH_MS) return []
+ start.error = `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`
+ return buddyNotice(state, start)
+ }
if (!start.dispatched || start.harnessId || start.error || start.dispatchedAt === undefined || now - start.dispatchedAt <= START_RUN_MS) return []
// Only its own machine's report can say it is preparing; one before preparingStartIds never does, so its starts get 3 minutes.
const report = state.machines?.find(m => m.machineId === start.request.machineId)?.observation
@@ -181,6 +202,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {
const machine = machineName(state, start.request.machineId)
start.error = `${machine}${!named ? TIMED_OUT_SUFFIX : silent ? STOPPED_REPORTING_SUFFIX : STILL_PREPARING_SUFFIX}`
// Never a lookup that throws: these checks run inside every machine's report.
+ if (start.request.buddyOf) return buddyNotice(state, start)
const group = state.conversations.find(c => c.id === start.request.conversationId)
const lead = group?.leadId ? state.agents.find(a => a.id === group.leadId) : undefined
if (!group || !lead) return []
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 64c6615af..5bef0232b 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -501,8 +501,9 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
if (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')
const project = groupProject(state, conversation(state, request.conversationId))
if (!pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
- // Before the request's own fields: a machine that takes none of this project's work says so first.
- requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)
+ // Before the request's own fields: a machine that takes none of this project's work says so first. A Buddy is its owner's
+ // own agent on their own machine (commands.ts buddy.create), as a Lead is: teammates' work rules do not apply to it.
+ if (!request.buddyOf) requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)
const cwd = projectFolder(pool, project)
// Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
// setting can be a path or a name of the caller's own.
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index f0877b130..20c56fae0 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -2,6 +2,7 @@
* conversation or mark it done. Tags live in SuperTabMention, never in the tab state, so an older backend still
* reads and writes a tab that has them. Called inside SuperTabStore's transactions. */
import type { Prisma, PrismaClient } from '@prisma/client'
+import { ensureIndex } from '../lib/db/indexes.js'
import { fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
import { canReadGroup, groupProject, ledProject, projectOf } from './projects.js'
import { groupsBy } from './parts/indexed.js'
@@ -17,8 +18,7 @@ const waiting: Prisma.SuperTabMentionWhereInput = { OR: [{ resolvedAt: null }, {
/** Run by the singleton worker at startup, like the terminal answer expiry. */
export async function ensureMentionExpiry(db: PrismaClient): Promise<void> {
- await db.$runCommandRaw({ createIndexes: 'SuperTabMention', indexes: [{ key: { createdAt: 1 }, name: 'mention_expiry',
- expireAfterSeconds: MENTION_EXPIRY_MS / 1000 }] })
+ await ensureIndex(db, 'SuperTabMention', { key: { createdAt: 1 }, name: 'mention_expiry', expireAfterSeconds: MENTION_EXPIRY_MS / 1000 })
}
/** Only the project's Lead tags, only in that project's conversations, and only people who can read the conversation. */
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index ca1a3dc18..82032a7df 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -74,6 +74,9 @@ export interface Agent {
confidential?: true
/** Set by its contributor or its project's Lead (profile.ts); absent shows the pattern Desktop draws from its name. */
avatar?: import('./profile.js').Avatar
+ /** A Buddy (buddies.ts): the person it brainstorms with, at the membership they added it in. Its role stays a builder's
+ * for older readers; this is what makes it a Buddy, and what refuses it every command but its own chat and proposals. */
+ buddyOf?: { personId: string; generation: string }
}
export type AgentRole = 'builder' | 'reviewer'
export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'
@@ -94,6 +97,8 @@ export interface AgentStartRequest {
gridModel?: string
gridName?: string
requirements: { memoryBytes: number; diskBytes: number; maxCpuPercent: number; tools: string[]; devices: string[]; quotaRequired: boolean }
+ /** A Buddy's start (buddies.ts): written by buddy.create alone, never taken from an agent.start. */
+ buddyOf?: { personId: string; generation: string }
}
export interface AgentStart {
poolGeneration?: string
@@ -112,6 +117,8 @@ export interface AgentStart {
/** When its host was asked to launch it; a start not running 3 minutes later fails, or 15 minutes later while its machine
* reports it preparing (liveness.ts). */
dispatchedAt?: number
+ /** When a person asked for it: only a Buddy's start keeps it, which fails if its machine never takes it (liveness.ts). */
+ requestedAt?: number
/** On reads only, never stored: its machine's fresh report says it is preparing (machines.ts startPreparing). */
preparing?: true
error: string | null
@@ -176,8 +183,8 @@ export function renderWorkTask(task: WorkTask): string {
export interface Conversation {
id: string
- /** The Swarm-wide Leads conversation (syncLeads); absent on every project conversation. */
- kind?: 'leads'
+ /** The Swarm-wide Leads conversation (syncLeads), or a person's Buddy chat (buddies.ts); absent on every other conversation. */
+ kind?: 'leads' | 'buddy'
projectId?: string
/** Stable, tab-local workgroup reference. Lead has no number. */
number?: number
@@ -209,6 +216,8 @@ export interface Conversation {
lostAttempt?: { id: string; agentId: string; machineId?: string; engine?: string }
/** Counts reaction changes here (reactions.ts), so readers see a new reaction on an older message. */
reactionSeq?: number
+ /** A Buddy chat's owner messages its Buddy already proposed for (buddies.ts): each asks once. */
+ proposals?: string[]
/** The person who asked for this work: whoever opened it, or the person its Lead named (leaderboard/record.ts). */
requesterId?: string
/** What the leaderboard counts here (leaderboard/record.ts); bookkeeping readers never get whole. */
@@ -259,6 +268,8 @@ export interface SuperTabState {
paused: boolean
/** Idle workers stop and finished groups archive by themselves (tidy.ts); false once the owner turns it off. */
tidy?: false
+ /** Buddies (buddies.ts): on once the owner turns them on; absent is off. Turning them off removes every Buddy. */
+ buddies?: true
people: Person[]
agents: Agent[]
conversations: Conversation[]
@@ -401,12 +412,14 @@ export function conversation(state: SuperTabState, id: string): Conversation {
export const isLeads = (group: Conversation): boolean => group.kind === 'leads'
-const KNOWN_KINDS: Record<NonNullable<Conversation['kind']>, true> = { leads: true }
+const KNOWN_KINDS: Record<NonNullable<Conversation['kind']>, true> = { leads: true, buddy: true }
+/** Conversation kinds this release knows; one of another kind is kept aside unchanged (parkLaterConversations, parts/shape.ts). */
+export const knownKind = (group: Pick<Conversation, 'kind'>): boolean => group.kind == null || Object.hasOwn(KNOWN_KINDS, group.kind)
/** During a rolling deploy the previous release reads what the next one wrote. A conversation kind it does not know
* belongs to no project it can check, so it waits here unchanged, and the release that knows it puts it back. */
export function parkLaterConversations(state: SuperTabState): void {
const all = [...state.conversations, ...state.parkedConversations ?? []]
- const known = (c: Conversation) => c.kind == null || Object.hasOwn(KNOWN_KINDS, c.kind)
+ const known = knownKind
state.conversations = all.filter(known)
const parked = all.filter(c => !known(c))
if (parked.length) state.parkedConversations = parked
@@ -570,6 +583,12 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
for (const start of visible.starts ?? []) {
if (start.error && !readsRawReason(actor, start, state.conversations.find(c => c.id === start.request.conversationId))) start.error = publicReason(start.error)
}
+ // A Buddy brainstorms; where agents run and how work is routed are none of its business (buddies.ts).
+ if (actor.kind === 'agent' && state.agents.some(a => a.id === actor.agentId && a.buddyOf)) {
+ visible.machines = []
+ delete visible.rules
+ delete visible.routingPolicy
+ }
const seen = seenMachineIds(visible)
visible.conversations = visible.conversations.map(c => withSeenRequirement(c, seen))
return visible
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 084349b92..ba97de1e5 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -13,7 +13,7 @@ const conversation: Required<Conversation> = {
id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, pullRequestUrls: [],
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
- requesterId: 'p', ledger: {},
+ requesterId: 'p', ledger: {}, proposals: [],
}
describe('the light conversation projection (parts/light.ts)', () => {
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index bb0efa72d..70c0d69f5 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq',
+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt'],
} as const
const LIGHT_GROUP = {
diff --git a/backend/src/superTabs/parts/shape.ts b/backend/src/superTabs/parts/shape.ts
index 98f56902e..61d1bd0b0 100644
--- a/backend/src/superTabs/parts/shape.ts
+++ b/backend/src/superTabs/parts/shape.ts
@@ -1,5 +1,5 @@
import type { AgentStart, Conversation, SuperTabState } from '../model.js'
-import { isLeads, nextConversationNumber } from '../model.js'
+import { isLeads, knownKind, nextConversationNumber } from '../model.js'
import type { ContributedMachine, MachineCleanup } from '../machines.js'
import type { SwarmProject } from '../projects.js'
import type { HeadData, MachineData, Part, PartKind, ProgressData, SwarmParts } from './types.js'
@@ -7,8 +7,8 @@ import type { HeadData, MachineData, Part, PartKind, ProgressData, SwarmParts }
/** The legacy report progress (`SuperTab.state`), in tab revisions. */
interface LegacyProgress { dirtyRevision: number; summarizedRevision: number; requestedRevision: number; since: number; requestedAt?: number; requestMessageId?: string }
-/** Conversation kinds this release knows; a part of another kind is kept aside unchanged (model.ts parkLaterConversations). */
-export const knownKind = (group: Conversation) => group.kind == null || group.kind === 'leads'
+// The kinds this release knows are listed once (model.ts knownKind): a second list here once set Buddy chats aside, so no host or change read saw them.
+export { knownKind }
const PART_ONLY_GROUP_FIELDS = ['messageSeq', 'reportSeq', 'dormant', 'lastActivityAt'] as const
/** Optional lists of `SuperTab.state` an empty one of which differs from an absent one (`[]` after the last machine left). */
const LISTS = ['parkedConversations', 'starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'machineCleanups'] as const
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index ff311b8de..663627054 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto'
import { activeWork, agent, agentRole, author, conversation, fail, isLeads, nextConversationNumber, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'
import type { SwarmRule } from './rules.js'
+import { buddyReads, isBuddy, isBuddyChat } from './buddies.js'
export type ProjectVisibility = 'public' | 'private'
/** Which built-in skill texts the project's agents get: Default (the team process only) or today's Harness orchestration. */
@@ -117,13 +118,17 @@ export function readConversation(state: SuperTabState, actor: Actor, conversatio
export const PRIVATE_VISIBLE_TO_OWNERS = false
/** Who reads a conversation: the Leads conversation's people and Leads; a project conversation's readers; and a private
- * conversation's listed people (at the generation they were listed with) and the project's Lead, nobody else. */
+ * conversation's listed people (at the generation they were listed with) and the project's Lead, nobody else. A Buddy
+ * chat leaves out the Lead too, and a Buddy reads only its project's chat and its own chat (buddies.ts). */
export function canReadGroup(state: SuperTabState, actor: Actor, group: Conversation): boolean {
if (isLeads(group)) return actor.kind === 'person' ? state.people.some(p => p.id === actor.userId) : !!ledProject(state, actor.agentId)
const project = groupProject(state, group)
if (!canReadProject(state, actor, project)) return false
+ const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
+ if (buddy) return buddyReads(buddy, group, project.leadConversationId)
if (!group.audience) return true
- if (actor.kind === 'agent') return ledProject(state, actor.agentId)?.id === project.id
+ // A Buddy chat has no private channel to the PM: only its owner and its Buddy read it (buddies.ts).
+ if (actor.kind === 'agent') return !isBuddyChat(group) && ledProject(state, actor.agentId)?.id === project.id
const member = state.people.find(p => p.id === actor.userId)
return !!member && (group.audience.people.some(p => p.id === member.id && p.generation === member.generation)
|| (PRIVATE_VISIBLE_TO_OWNERS && (member.id === project.ownerId || member.id === state.ownerId)))
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 821f33515..9e9568a5c 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -24,7 +24,7 @@ export type GroupChange = LivePart<GroupView> | Tombstone | DormantStub
/** The head as a reader sees it: no sharing, overlap alerts, retired number or parked groups; projects, rules and
* invitations filtered (invitations only for the Swarm owner). */
export type HeadView = Pick<SuperTabState, 'version' | 'id' | 'name' | 'project' | 'projects' | 'leadsConversationId' | 'ownerId'
- | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility'>
+ | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility' | 'buddies'>
/** A member's avatar says only `{ kind: 'upload' }` for an upload: its link comes signed in `derived.avatars`. */
export type MemberView = Omit<Person, 'avatar'> & { avatar?: import('../profile.js').AvatarView }
/** The stored agent. Time-based and cross-part values (`downSince`, `limitedUntil`, an awaiting decision, the custom
@@ -34,8 +34,10 @@ export type AgentView = Omit<Agent, 'downNamed' | 'downSince' | 'limitedUntil' |
export interface Audience { people: Array<{ id: string; generation: string }> }
/** A conversation with its own message counter (`lastMessageSequence` and message sequences compare within one group).
* `dormant` is set only on a dormant group fetched on demand; `audience` only on a private conversation. */
-export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger'>
- & { messageSeq: number; dormant?: true; audience?: Audience }
+export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger' | 'proposals'>
+ & { messageSeq: number; dormant?: true; audience?: Audience
+ /** A Buddy chat's owner, in place of its audience (read/views.ts groupView). */
+ buddyOwnerId?: string }
/** A contribution as `state.machines[]` has it, privacy detail only for its contributor, harness ids cut to what the
* reader can see. Machines without a contribution are never sent. */
export type MachineView = ContributedMachine
@@ -223,6 +225,8 @@ export interface HostPool {
paused: boolean
machine: ContributedMachine
starts: AgentStart[]
+ /** Buddies' starts (buddies.ts), apart from `starts`: a host from before Buddies would launch one as a Builder. */
+ buddyStarts?: AgentStart[]
projects?: Array<{ id: string; leadConversationId: string; repository?: unknown; conversationIds: string[] }>
localGrid?: string
reservations: Array<{ harnessId: string; generation: string }>
diff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.ts
index 120bd3fb7..ce4dd9346 100644
--- a/backend/src/superTabs/read/host.ts
+++ b/backend/src/superTabs/read/host.ts
@@ -13,6 +13,7 @@ import { fail, type AgentStart, type SuperTabState } from '../model.js'
import { GrantReads, type SuperTabStore } from '../store.js'
import type { CacheView } from '../cache.js'
import { readLastChangedAt, readMachines } from '../cachedReads.js'
+import { retryTransient } from '../retry.js'
import * as parts from '../parts/index.js'
import type { MachineData, Part } from '../parts/index.js'
import { groupsBy, retryStaleIndex } from '../parts/indexed.js'
@@ -117,8 +118,8 @@ export class HostReads {
* host still settles a queued start whose group went quiet). */
private async tabState(tx: Transaction, cached: CacheView, tabId: string, machineId: string): Promise<SuperTabState> {
const [light, machines] = await Promise.all([cached.get(tabId, `host:state:${machineId}`, 'main',
- // On a miss, one snapshot of what the host's rows are built from.
- () => retryStaleIndex(() => this.db.$transaction(t => this.hostParts(t, tabId, machineId)))),
+ // On a miss, one snapshot of what the host's rows are built from, tried again when a lock it waits for is held (retry.ts).
+ () => retryTransient(() => retryStaleIndex(() => this.db.$transaction(t => this.hostParts(t, tabId, machineId))))),
readMachines(tx, cached, tabId)])
return parts.reassemble({ ...light, machines }, { share: true })
}
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 155105d46..a0214c4e0 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -95,15 +95,19 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Auth
let contribution
try { contribution = machineContribution(state, machineId) } catch (error) { if (error instanceof SuperTabError) return null; throw error }
if (!contribution || contribution.contributorId !== user.sub) return null
- const starts = (state.starts ?? []).filter(s => s.request.machineId === machineId && s.poolGeneration === contribution.generation
+ const pending = (state.starts ?? []).filter(s => s.request.machineId === machineId && s.poolGeneration === contribution.generation
&& (!s.harnessId || !s.poolSettled) && !s.error)
+ // A host from before Buddies reads only `starts`, and would launch a Buddy as a Builder: it never sees one.
+ const starts = pending.filter(s => !s.request.buddyOf), buddyStarts = pending.filter(s => s.request.buddyOf)
+ const buddyChats = new Set(buddyStarts.map(s => s.request.conversationId))
const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === machineId)
- return { tabId, paused: state.paused, machine: contribution, starts,
- ...(contribution.scope === 'swarm' ? { projects: projectsOf(state).filter(p => starts.some(s =>
+ return { tabId, paused: state.paused, machine: contribution, starts, ...(buddyStarts.length ? { buddyStarts } : {}),
+ ...(contribution.scope === 'swarm' ? { projects: projectsOf(state).filter(p => pending.some(s =>
groupProject(state, conversation(state, s.request.conversationId)).id === p.id))
.map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,
- // A private conversation is chat only and never runs work here, so its id stays with its audience.
- conversationIds: state.conversations.filter(c => !isLeads(c) && !c.audience && groupProject(state, c).id === p.id).map(c => c.id) })) } : {}),
+ // A private conversation is chat only and never runs work here, so its id stays with its audience; a Buddy chat whose
+ // Buddy starts here is named, so the host may prepare the project's folder for it.
+ conversationIds: state.conversations.filter(c => !isLeads(c) && (!c.audience || buddyChats.has(c.id)) && groupProject(state, c).id === p.id).map(c => c.id) })) } : {}),
...hostLocalGrid(state),
reservations: reservations.map(({ harnessId, generation }) => ({ harnessId, generation })),
harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...reservations.map(r => r.harnessId),
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 8d6dd9450..a1e38a9fd 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -5,7 +5,7 @@
import type { PrismaClient } from '@prisma/client'
import type { AuthUser } from '../../lib/ssoAuth.js'
import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'
-import { author, fail, isLeads, seenMachineIds, visibleState, type Actor, type AgentStart } from '../model.js'
+import { author, fail, isLeads, seenMachineIds, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'
import { mentionsWaiting } from '../mentions.js'
import { decisionsWaiting } from '../decisions.js'
import type { SuperTabStore } from '../store.js'
@@ -32,6 +32,9 @@ import { decodeDormantPage, encodeDormantPage } from './dormantPage.js'
type LoadOptions = NonNullable<Parameters<typeof parts.loadActive>[2]> & Pick<NonNullable<Parameters<typeof parts.loadLight>[2]>, 'groups'>
type Loader = (view: CacheView, tabId: string, opts: LoadOptions) => Promise<SwarmParts>
interface Read { parts: SwarmParts; actor: Actor; view: ReaderView; lastChangedAt: number | null }
+/** How long one Swarm's machine lookups below are reused: machines report every 15 s anyway (Diego's review, item 5, 2026-10-28). */
+const MACHINE_READS_MS = 15_000
+type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[]]
export class SwarmReads {
private readonly db: PrismaClient
@@ -43,6 +46,8 @@ export class SwarmReads {
this.avatarLinks = store.avatars ? new AvatarLinks(store.avatars, store.avatarPrefix) : null
}
private readonly avatarLinks: AvatarLinks | null
+ /** The machine lookups of each Swarm read in the last MACHINE_READS_MS, oldest first, keyed by what they depend on. */
+ private readonly machineReads = new Map<string, { at: number; read: Promise<MachineReads> }>()
async firstLoad(user: AuthUser, tabId: string, asAgentId?: string): Promise<FirstLoad> {
const t0 = this.now()
@@ -165,9 +170,8 @@ export class SwarmReads {
const loaded = await loader(cached, tabId, opts)
const state = parts.reassemble(loaded, { share: true })
const actor = await this.store.actor(tx, user, state, asAgentId)
- const [teamMachines, otherWorkspaceMachines, counts, newest] = await Promise.all([
- state.machines?.length ? this.store.teamMachines(tx, state) : [],
- state.machines?.length ? this.store.otherWorkspaceMachines(tx, state) : [],
+ const [[teamMachines, otherWorkspaceMachines], counts, newest] = await Promise.all([
+ this.machineLookups(state),
actor.kind === 'person' ? Promise.all([mentionsWaiting(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor)]) : undefined,
readLastChangedAt(tx, cached, tabId),
])
@@ -175,4 +179,25 @@ export class SwarmReads {
view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines,
...(counts ? { mentionsWaiting: counts[0], decisionsWaiting: counts[1].count, decisionsDigest: counts[1].digest } : {}) }, state) }
}
+
+ /** Which of the Swarm's machines are signed in as a team account, and which serve another Workspace's Swarm too (store.ts): the
+ * same answer for every reader, whose view hides what it may not see, so one lookup serves every read of the Swarm for
+ * MACHINE_READS_MS. Commands that admit work still look up afresh (store.ts executeOnce). Outside any transaction, as every read is. */
+ private machineLookups(state: SuperTabState): Promise<MachineReads> {
+ if (!state.machines?.length) return Promise.resolve([[], []])
+ const now = this.now()
+ const key = JSON.stringify([state.id, state.environment, state.workspaceId ?? null, state.machines.map(m => m.machineId).sort()])
+ const kept = this.machineReads.get(key)
+ if (kept && now >= kept.at && now - kept.at < MACHINE_READS_MS) return kept.read
+ for (const [old, entry] of this.machineReads) {
+ if (now >= entry.at && now - entry.at < MACHINE_READS_MS) break
+ this.machineReads.delete(old)
+ }
+ const entry = { at: now, read: Promise.all([this.store.teamMachines(this.db, state), this.store.otherWorkspaceMachines(this.db, state)]) }
+ this.machineReads.delete(key)
+ this.machineReads.set(key, entry)
+ // A failed lookup is never reused.
+ entry.read.catch(() => { if (this.machineReads.get(key) === entry) this.machineReads.delete(key) })
+ return entry.read
+ }
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index c1c60e49e..bf0959b37 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -3,6 +3,7 @@
* plus the private-conversation check, each record sent in its part's envelope. Time-based and cross-part values go only
* in `derived`, so a part never changes without a new version (Lead's ruling).
*/
+import { isBuddyChat } from '../buddies.js'
import { isLeads, seenMachineIds, visibleState, withSeenRequirement, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'
import { machineSlots, machineTeamWork, teamAccountSwarm, type ContributedMachine } from '../machines.js'
import * as store from '../parts/index.js'
@@ -40,7 +41,7 @@ export interface ReadExtras {
}
const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',
- 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility'] as const
+ 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility', 'buddies'] as const
export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, data: T): LivePart<T> =>
({ key: part.key, version: part.version, changedAt: part.changedAt, data })
@@ -48,8 +49,11 @@ export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, d
/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping or the
* leaderboard's (the leaderboard read sums it). */
export function groupView(group: Conversation, seenMachines: ReadonlySet<string>): GroupView {
- const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger: _ledger, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
- return { ...rest, messageSeq: messageSeq ?? 0, ...(dormant ? { dormant: true as const } : {}), ...(audience ? { audience } : {}) }
+ const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger: _ledger, proposals: _proposals, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
+ // A Buddy chat names its owner instead of an audience: an app from before Buddies takes a private chat of the reader
+ // alone for their Chat with PM, and would send what they write for the PM to their Buddy instead (buddies.ts).
+ const readers = isBuddyChat(group) ? { buddyOwnerId: audience!.people[0]!.id } : audience ? { audience } : {}
+ return { ...rest, messageSeq: messageSeq ?? 0, ...(dormant ? { dormant: true as const } : {}), ...readers }
}
/** A conversation's whole data as the reader may see it: the Leads conversation lists only the agents the reader can see, and a
diff --git a/backend/src/superTabs/retry.ts b/backend/src/superTabs/retry.ts
new file mode 100644
index 000000000..bcf6682c9
--- /dev/null
+++ b/backend/src/superTabs/retry.ts
@@ -0,0 +1,37 @@
+import { fail } from './model.js'
+
+const TRANSACTION_ATTEMPTS = 8
+const EXPIRED_TRANSACTION_ATTEMPTS = 2
+const TRANSACTION_BACKOFF_MS = 50
+const TRANSACTION_BACKOFF_CAP_MS = 1_500
+const errorCode = (error: unknown): unknown => error && typeof error === 'object' && 'code' in error ? error.code : null
+function retryable(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false
+ return ['P2034', 'P2002', 'P2028'].includes(errorCode(error) as string) || (error instanceof Error && error.message.includes('TransientTransactionError'))
+}
+
+/**
+ * Runs one transaction `attempt` again while it fails transiently, the Swarm's one rule for it: a write conflict, a taken
+ * unique key or Mongo's own transient errors, up to 8 attempts after a growing, jittered wait, then the Swarm is busy (a 503
+ * every client retries). A Mongo transaction waits at most 5 ms for a lock, so a read that meets an index build's exclusive
+ * lock fails at once and is tried again here (the 10-28 release). Used by the store's writes and the cache's reads alike.
+ * `alsoRetry` names a caller's own failure to try again under the same limit (the store's read of a removed index).
+ */
+export async function retryTransient<T>(attempt: () => Promise<T>,
+ sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms)),
+ alsoRetry: (error: unknown) => boolean = () => false): Promise<T> {
+ for (let tries = 1; ; tries++) {
+ try {
+ return await attempt()
+ } catch (error) {
+ if (!retryable(error) && !alsoRetry(error)) throw error
+ // An expired or unstartable transaction (P2028) is load: one more try, then the client retries after Retry-After.
+ if (tries >= (errorCode(error) === 'P2028' ? EXPIRED_TRANSACTION_ATTEMPTS : TRANSACTION_ATTEMPTS)) {
+ // A unique key still taken after every retry is a real duplicate, not contention.
+ if (errorCode(error) === 'P2002') throw error
+ fail('SWARM_BUSY', 'This Swarm is busy. Try again in a moment.', 503)
+ }
+ await sleep(Math.random() * Math.min(TRANSACTION_BACKOFF_CAP_MS, TRANSACTION_BACKOFF_MS * 2 ** (tries - 1)))
+ }
+ }
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 4c99c79d6..79d453737 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,5 +1,6 @@
import { contributedEngines, expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, machineTeamWork, observedPrivacy, recordAgentPresence, removalPreview, startPreparing, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'
import { createHash } from 'node:crypto'
+import { isDeepStrictEqual } from 'node:util'
import type { Machine, Prisma, PrismaClient, SuperTabDelivery, SuperTabMessage } from '@prisma/client'
import type { AuthUser } from '../lib/ssoAuth.js'
import { machineAlive } from '../lib/prisma.js'
@@ -16,6 +17,7 @@ import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVA
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
+import { retryTransient } from './retry.js'
import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, watchingNarrowed, type ProjectVisibility } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'
@@ -145,8 +147,8 @@ export async function loadRow(tx: Transaction, row: SwarmRow, named: Named = {})
*/
export async function transaction<T>(db: Pick<PrismaClient, '$transaction'>, body: (tx: Transaction) => Promise<T>,
sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms))): Promise<T> {
- let hintless = false
- for (let attempt = 1; ; attempt++) {
+ let hintless = false, staleIndex: unknown = null
+ return retryTransient(async () => {
let committed: Array<() => void> = []
const drops = listingDrops()
try {
@@ -159,17 +161,10 @@ export async function transaction<T>(db: Pick<PrismaClient, '$transaction'>, bod
return result
} catch (error) {
// A read in this attempt named an index removed since the last listing (parts/indexed.ts): the next attempts name none.
- if (listingDrops() !== drops) hintless = true
- else if (!retryable(error)) throw error
- // An expired or unstartable transaction (P2028) is load: one more try, then the client retries after Retry-After.
- if (attempt >= (errorCode(error) === 'P2028' ? EXPIRED_TRANSACTION_ATTEMPTS : TRANSACTION_ATTEMPTS)) {
- // A unique key still taken after every retry is a real duplicate, not contention.
- if (errorCode(error) === 'P2002') throw error
- fail('SWARM_BUSY', 'This Swarm is busy. Try again in a moment.', 503)
- }
- await sleep(Math.random() * Math.min(TRANSACTION_BACKOFF_CAP_MS, TRANSACTION_BACKOFF_MS * 2 ** (attempt - 1)))
+ if (listingDrops() !== drops) { hintless = true; staleIndex = error }
+ throw error
}
- }
+ }, sleep, error => error === staleIndex)
}
const TRANSACTION_OPTIONS = { maxWait: 5_000, timeout: 15_000 }
/** Each attempt's after-commit work, by that attempt's client: a retried attempt's list is dropped with its client. */
@@ -194,16 +189,6 @@ const pollMemoryFailed = (error: unknown): void => {
const OPEN_DELIVERY = ['queued', 'claimed', 'uncertain'] as const
/** Callers kept for the quiet delivery poll before the stale ones are dropped. */
const POLLED_CAP = 5_000
-const TRANSACTION_ATTEMPTS = 8
-const EXPIRED_TRANSACTION_ATTEMPTS = 2
-const TRANSACTION_BACKOFF_MS = 50
-const TRANSACTION_BACKOFF_CAP_MS = 1_500
-const errorCode = (error: unknown): unknown => error && typeof error === 'object' && 'code' in error ? error.code : null
-function retryable(error: unknown): boolean {
- if (!error || typeof error !== 'object') return false
- return ['P2034', 'P2002', 'P2028'].includes(errorCode(error) as string) || (error instanceof Error && error.message.includes('TransientTransactionError'))
-
-}
/** A Lead's start dispatches within seconds of being recorded; one still undispatched after this long was given up. */
export const ABANDONED_START_MS = 15 * 60_000
@@ -966,6 +951,7 @@ export class SuperTabStore {
}
if (command.type === 'machine.contribute') context.abandonedStartIds = await abandonedStarts(tx, tabId, original, command.machineId, context.now)
if (command.type === 'agent.start') context.contribution = await this.contribution(tx, original, actor, command.request, true)
+ if (command.type === 'buddy.create') context.contribution = await this.contribution(tx, original, actor, command, true)
if (command.type === 'agent.started' || command.type === 'agent.startDispatch') {
const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
context.contribution = await this.contribution(tx, original, actor, start.request, true)
@@ -975,10 +961,21 @@ export class SuperTabStore {
if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime() }
}
if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)
- if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {
+ if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
+ || command.type === 'tab.buddies') && command.askedIn) {
const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })
if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }
}
+ if (command.type === 'buddy.propose') {
+ const asked = await tx.superTabMessage.findFirst({ where: { id: command.ownerMessageId, tabId, conversationId: command.conversationId } })
+ // The newest message its owner wrote there: the chat's newest rows, the Buddy's and the owner's in turn.
+ const recent = asked ? await tx.superTabMessage.findMany({ where: { tabId, conversationId: command.conversationId },
+ orderBy: { sequence: 'desc' }, take: 50, select: { id: true, author: true, source: true } }) : []
+ const ownerId = (asked?.author as unknown as Author | undefined)?.id
+ const newest = recent.find(m => !m.source && (m.author as unknown as Author).kind === 'person' && (m.author as unknown as Author).id === ownerId)
+ if (asked) context.proposalAsk = { id: asked.id, conversationId: asked.conversationId, author: asked.author as unknown as Author,
+ source: !!asked.source, createdAt: asked.createdAt.getTime(), ...(newest ? { newestOwnerMessageId: newest.id } : {}) }
+ }
if (command.type === 'message.send' && actor.kind === 'agent') {
const recent = await tx.superTabMessage.findMany({ where: { tabId, conversationId: command.conversationId },
orderBy: { sequence: 'desc' }, take: PAIR_CHAIN_LIMIT, select: { author: true, recipientIds: true } })
@@ -1651,12 +1648,22 @@ export class SuperTabStore {
return rows.map(r => r.assignmentId).filter(id => !id.startsWith('release-') && !active.has(id))
}
- /** Records committed messages, each at the sequence its conversation gave it, and one delivery per recipient. */
- private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], sequences: ReadonlyMap<string, number>) {
+ /** Records committed messages, each at the sequence its conversation gave it, and one delivery per recipient. The time
+ * checks of a machine's report and of a Lead's poll pass `keepStored`: a notice of theirs already stored as that same
+ * notice (its Swarm, its conversation and its whole source: the kind, and for a loss its worker, task and reason) is
+ * kept, and only its missing deliveries are written. One duplicate had stopped every later report and poll
+ * (2026-10-28); any other message under the id still fails, so another task's notice is never delivered as this one. */
+ private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], sequences: ReadonlyMap<string, number>,
+ keepStored = false) {
+ const stored = keepStored && messages.length ? await tx.superTabMessage.findMany({ where: { id: { in: messages.map(m => m.id) } },
+ select: { id: true, tabId: true, conversationId: true, source: true } }) : []
+ const kept = new Set(stored.filter(row => messages.some(m => m.id === row.id && row.tabId === tabId && row.conversationId === m.conversationId
+ && isDeepStrictEqual(row.source ?? undefined, m.source))).map(row => row.id))
+ if (kept.size) logger.warn('Kept Swarm notices already stored', { tabId, ids: [...kept] })
const rows: Prisma.SuperTabMessageCreateManyInput[] = []
- const deliveries: Prisma.SuperTabDeliveryCreateManyInput[] = []
+ let deliveries: Prisma.SuperTabDeliveryCreateManyInput[] = []
for (const message of messages) {
- rows.push({ id: message.id, tabId, conversationId: message.conversationId,
+ if (!kept.has(message.id)) rows.push({ id: message.id, tabId, conversationId: message.conversationId,
sequence: sequences.get(message.id)!, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),
...(message.attachments ? { attachments: json(message.attachments) } : {}),
text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [] })
@@ -1672,6 +1679,10 @@ export class SuperTabStore {
}
}
if (rows.length) await tx.superTabMessage.createMany({ data: rows })
+ if (kept.size) {
+ const have = new Set((await tx.superTabDelivery.findMany({ where: { messageId: { in: [...kept] } }, select: { id: true } })).map(d => d.id))
+ deliveries = deliveries.filter(d => !have.has(d.id))
+ }
if (deliveries.length) await tx.superTabDelivery.createMany({ data: deliveries })
for (const delivery of deliveries) this.announce(tx, { machineId: delivery.machineId, tabId, agentId: delivery.agentId })
}
@@ -1889,7 +1900,7 @@ export class SuperTabStore {
const touches = judgedMachines(loaded.state, state, rows).filter(t => t.key !== machineId)
await this.endRuns(tx, tabId, loaded.state, state)
const version = (await this.save(tx, loaded, state, stamp, touches)).versions.get(`machine:${machineId}`) ?? 0
- await this.writeMessages(tx, tabId, state, rows, sequences)
+ await this.writeMessages(tx, tabId, state, rows, sequences, true)
return { version }
}
if (!state.machines?.includes(pool)) return saved()
@@ -2071,7 +2082,7 @@ export class SuperTabStore {
// A loss, a start's failure or a stop was judged from a machine's report: a newer report makes this write retry.
await this.save(tx, loaded, state, clock.next(), [...judgedMachines(loaded.state, state, written), ...stoppedMachines(state, idle),
...woken ? [{ kind: 'agent' as const, key: agentId }] : []])
- await this.writeMessages(tx, tabId, state, written, sequences)
+ await this.writeMessages(tx, tabId, state, written, sequences, true)
const rows = await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } },
orderBy: { createdAt: 'asc' }, take: 100 })
const allowed: SuperTabDelivery[] = []
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index a513a240e..3e10e5ca8 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -3,6 +3,7 @@ import type { AgentStart, Conversation } from './model.js'
import { clock, guardedWrite, PartConflict, type HeadData, type ProgressData } from './parts/index.js'
import { DORMANT_AFTER_MS, RETENTION_MS } from './parts/types.js'
import { logger } from '../utils/logger.js'
+import { ensureIndex } from '../lib/db/indexes.js'
import { swarmTransaction } from './cache.js'
/** Parts whose key is never used twice (conversations, starts, projects' progress) lose their tombstone at `purgeAt`.
@@ -11,13 +12,13 @@ import { swarmTransaction } from './cache.js'
* startup, like the terminal and mention expiry indexes. */
export async function ensurePartExpiry(db: PrismaClient): Promise<void> {
for (const collection of ['SwarmHead', 'SwarmGroup', 'SwarmStart', 'SwarmProgress']) {
- await db.$runCommandRaw({ createIndexes: collection, indexes: [{ key: { purgeAt: 1 }, name: 'part_purge', expireAfterSeconds: 0 }] })
+ await ensureIndex(db, collection, { key: { purgeAt: 1 }, name: 'part_purge', expireAfterSeconds: 0 })
}
// Workspaces (workspaceStore.ts): a removed person's row, a finished removal and a deleted Workspace 30 days on, an invitation when it expires.
for (const collection of ['SwarmWorkspace', 'SwarmWorkspaceMember', 'SwarmWorkspaceRemoval']) {
- await db.$runCommandRaw({ createIndexes: collection, indexes: [{ key: { purgeAt: 1 }, name: 'workspace_purge', expireAfterSeconds: 0 }] })
+ await ensureIndex(db, collection, { key: { purgeAt: 1 }, name: 'workspace_purge', expireAfterSeconds: 0 })
}
- await db.$runCommandRaw({ createIndexes: 'SwarmWorkspaceInvitation', indexes: [{ key: { expiresAt: 1 }, name: 'workspace_invitation_expiry', expireAfterSeconds: 0 }] })
+ await ensureIndex(db, 'SwarmWorkspaceInvitation', { key: { expiresAt: 1 }, name: 'workspace_invitation_expiry', expireAfterSeconds: 0 })
}
/** A removed person, agent or machine keeps its tombstone after its 7 days, with its data dropped: the version it holds
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
index cbb94f275..b8160ddda 100644
--- a/backend/src/superTabs/terminal.ts
+++ b/backend/src/superTabs/terminal.ts
@@ -1,4 +1,6 @@
+import { isBuddy, isBuddyChat } from './buddies.js'
import type { PrismaClient } from '@prisma/client'
+import { ensureIndex } from '../lib/db/indexes.js'
import { activeWork, actorKey, agent, author, conversation, fail, isLeads, stableId, type Actor, type Agent, type Author, type Conversation, type MessageDraft,
type SuperTabState } from './model.js'
import { downSince } from './machines.js'
@@ -17,8 +19,7 @@ export const TERMINAL_RECHECK_MS = 5_000
export const TERMINAL_EXPIRY_MS = 120_000
/** Run by the singleton worker at startup, like the product-usage expiry indexes. */
export async function ensureTerminalExpiry(db: PrismaClient): Promise<void> {
- await db.$runCommandRaw({ createIndexes: 'SuperTabTerminalRequest', indexes: [{ key: { createdAt: 1 }, name: 'terminal_request_expiry',
- expireAfterSeconds: TERMINAL_EXPIRY_MS / 1000 }] })
+ await ensureIndex(db, 'SuperTabTerminalRequest', { key: { createdAt: 1 }, name: 'terminal_request_expiry', expireAfterSeconds: TERMINAL_EXPIRY_MS / 1000 })
}
/** A limited agent without a shown reset time is skipped by routing for this long. */
export const LIMIT_FALLBACK_MS = 3_600_000
@@ -122,6 +123,9 @@ export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author
// Its engine has been retrying its model for 10 minutes (2026-10-24: a Builder on a small local model retried for an
// hour while its Lead waited on it).
if (command.alert === 'model') text = `${nameOf(target)} can't get answers from its model: its requests keep failing. Stop it, or give the work to another model.`
+ // A Buddy's alert is its owner's alone, in their chat: the PM neither reads that chat nor runs the Buddy (buddies.ts).
+ const chat = isBuddy(target) ? state.conversations.find(c => isBuddyChat(c) && c.agentIds.includes(target.id)) : undefined
+ if (chat) return [{ id, conversationId: chat.id, author: sender, replyTo: null, recipients: [], text, source }]
return toLead(state, target, { id, conversationId: group.id, author: sender, replyTo: null, recipients: [], text, source })
}
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index e1c11af34..97cbb122e 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -1,3 +1,4 @@
+import { isBuddy } from './buddies.js'
import { agentDisplayName } from './agentNames.js'
import { verdictPending } from './autoReview.js'
import { activeWork, agentRole, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
@@ -70,6 +71,8 @@ export function stopIdleWorkers(state: SuperTabState, projectId: string, now: nu
const rows: MessageDraft[] = []
for (const worker of state.agents) {
if (!worker.startedSession || worker.workDecision === 'stop' || busy.has(worker.id) || agentProjectId(state, worker) !== projectId) continue
+ // A Buddy waits for its owner, however long; only they, or the Swarm's owner turning Buddies off, stop it (buddies.ts).
+ if (isBuddy(worker)) continue
if (state.conversations.some(c => c.leadId === worker.id || (activeWork(c) && c.assignment!.agentId === worker.id))) continue
if (waitingToResume(state, worker)) continue
const groups = groupsOf(state, worker, asleep)
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index 6d076a73e..8cf655a03 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -6,7 +6,6 @@ import { backfillMachineFreeEntitlements } from './lib/db/freeEntitlement.js'
import {
backfillMachineAuthMode,
backfillMachinePresenceTurnsStarted,
- ensureSchema,
migrateAutonomousEnvironment,
migrateMachineRename,
migrateUserIdentityByEmail,
@@ -15,11 +14,8 @@ import {
} from './lib/db/migrate.js'
import { ensurePlans } from './lib/db/seed.js'
import { prisma } from './lib/prisma.js'
-import { ensureProductUsageExpiry } from './lib/productUsage.js'
-import { ensureHarnessSessionExpiry } from './lib/ssoSession.js'
-import { ensureTerminalExpiry } from './superTabs/terminal.js'
-import { ensureMentionExpiry } from './superTabs/mentions.js'
-import { ensurePartExpiry, startSwarmSweeps } from './superTabs/sweeps.js'
+import { releaseSchema } from './lib/db/schemaRelease.js'
+import { startSwarmSweeps } from './superTabs/sweeps.js'
import { startDeliverySettle } from './superTabs/deliverySettle.js'
import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'
import { SuperTabStore } from './superTabs/store.js'
@@ -39,12 +35,7 @@ async function start(): Promise<void> {
await migrateUserIdentityByEmail()
// Same reason: the old (user, day) unique must be gone before the push installs its replacement.
await migrateUserPresencePerMachine()
- ensureSchema()
- await ensureProductUsageExpiry()
- await ensureHarnessSessionExpiry(prisma)
- await ensureTerminalExpiry(prisma)
- await ensureMentionExpiry(prisma)
- await ensurePartExpiry(prisma)
+ await releaseSchema()
// After the push, which adds the finished mark: parts written before it are marked once, so the archive pass finds them.
await markFinishedGroups(prisma)
// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 45f795a6c..388cfc0cc 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -3,5 +3,5 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
'integration/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',
'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts',
- 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],
+ 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/e2e/harness/socketMeter.ts b/cli/e2e/harness/socketMeter.ts
new file mode 100644
index 000000000..4ccbf639a
--- /dev/null
+++ b/cli/e2e/harness/socketMeter.ts
@@ -0,0 +1,332 @@
+/**
+ * A recording proxy in front of a local backend: every client in a socket scenario dials this instead
+ * of the backend, so what it records is what the backend was asked, whatever the backend logs.
+ *
+ * Per WebSocket it keeps the endpoint, the client kind and version the client declared on the URL, read as
+ * the backend reads them (`declaredKind`), when it opened and closed and with which code, and each
+ * `machine_select` it sent with the backend's answer (`connected` → accepted, `machine_select_error` →
+ * its code). An upgrade the backend refused is a refusal, never a socket. HTTP requests are counted by
+ * method and route, ids folded to `:id`.
+ *
+ * Written for the WebSocket roadmap (Ken, 2026-10-28): Phase 0 and Phase 1 are judged on connects a
+ * minute, socket lifetime, sockets that never selected, attribution and selects of deleted machines,
+ * and the backend's own Phase 0 logs cannot be the measure of whether Phase 0 worked.
+ */
+import { createServer, request, type IncomingMessage, type Server } from 'node:http'
+import { once } from 'node:events'
+import type { Duplex } from 'node:stream'
+import WebSocket, { WebSocketServer, type RawData } from 'ws'
+
+export interface SelectRecord { machineId: string; at: number; outcome: string | null }
+
+export interface SocketRecord {
+ endpoint: string
+ /** One of `CLIENT_KINDS`, or `unknown`. */
+ client: string
+ version: string | null
+ openedAt: number
+ closedAt: number | null
+ closeCode: number | null
+ closeReason: string
+ selects: SelectRecord[]
+}
+
+export interface RefusalRecord { endpoint: string; status: number; at: number }
+
+export interface MeterRecords {
+ startedAt: number
+ sockets: SocketRecord[]
+ refused: RefusalRecord[]
+ http: Record<string, number>
+}
+
+export interface EndpointReport {
+ connects: number
+ connectsPerMinute: number
+ refused: number
+ /** Over every socket; one still open counts its age at the report. */
+ medianLifetimeMs: number
+ livedUnder2s: number
+ closedWithoutSelect: number
+ /** The share of connects that named both a client kind and a version. */
+ attributed: number
+ /** The same share for each client kind seen, `unknown` included. */
+ attributedByClient: Record<string, number>
+ closeCodes: Record<string, number>
+ selectOutcomes: Record<string, number>
+ deletedMachineSelects: number
+ selectsByMachine: Record<string, number>
+ /** Sockets whose select was accepted and that closed within a minute: a healthy socket dropped. */
+ acceptedThenDiedUnder1m: number
+}
+
+export interface MeterReport {
+ durationMs: number
+ endpoints: Record<string, EndpointReport>
+ http: Record<string, number>
+}
+
+/** The kinds the backend tells apart (backend/src/lib/wsAttribution.ts `WS_CLIENT_KINDS`, #2029). */
+export const CLIENT_KINDS = ['web', 'mobile', 'desktop', 'relay', 'group-sync', 'link', 'daemon']
+const VERSION = /^[0-9A-Za-z.+-]{1,40}$/
+
+/**
+ * What a socket's query declares, by #2029's rule (wsAttribution.ts `declaredKind`): a kind it does not know is
+ * `unknown`; the version is `v=` (the phone's `release=`) when it is a short plain token. The adapter's socket is
+ * the daemon's whatever it declares, as the backend tracks it.
+ */
+export function declaredKind(endpoint: string, query: URLSearchParams): { client: string; version: string | null } {
+ const declared = endpoint === '/api/adapter-ws' ? 'daemon' : query.get('client') ?? ''
+ const version = query.get('v') ?? query.get('release')
+ return { client: CLIENT_KINDS.includes(declared) ? declared : 'unknown', version: version && VERSION.test(version) ? version : null }
+}
+
+/** Hex ids (machine ids, share ids), UUIDs and numbers in a path, folded so a route counts as one. */
+export function routeOf(method: string, url: string): string {
+ const path = url.split('?')[0]
+ .split('/')
+ .map((part) => /^[0-9a-f]{16,}$/i.test(part) || /^[0-9a-f-]{36}$/i.test(part) || /^\d+$/.test(part) ? ':id' : part)
+ .join('/')
+ return `${method} ${path}`
+}
+
+function median(values: number[]): number {
+ if (values.length === 0) return 0
+ const sorted = [...values].sort((a, b) => a - b)
+ const mid = sorted.length >> 1
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
+}
+
+const count = (into: Record<string, number>, key: string): void => { into[key] = (into[key] ?? 0) + 1 }
+
+/** Hop-by-hop headers, and the handshake's own, which the meter's dial to the backend makes afresh. */
+const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding',
+ 'upgrade', 'host', 'content-length', 'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-protocol'])
+
+/** Everything the client's upgrade carried but this hop's own, so the backend reads what the client sent. */
+function forwardedHeaders(req: IncomingMessage): Record<string, string | string[]> {
+ const out: Record<string, string | string[]> = {}
+ for (const [name, value] of Object.entries(req.headers)) {
+ if (value !== undefined && !HOP.has(name)) out[name] = value
+ }
+ return out
+}
+
+export class SocketMeter {
+ readonly sockets: SocketRecord[]
+ readonly refused: RefusalRecord[]
+ private readonly http: Record<string, number>
+ private startedAt: number
+ private server: Server | null = null
+ private readonly live = new Set<WebSocket>()
+ url = ''
+ wsUrl = ''
+
+ private constructor(records: MeterRecords) {
+ this.startedAt = records.startedAt
+ this.sockets = records.sockets
+ this.refused = records.refused
+ this.http = records.http
+ }
+
+ /** Start the report's window now: sockets opened before (the daemons' own start) are left out of it. */
+ startClock(): void {
+ this.startedAt = Date.now()
+ }
+
+ /** A meter over records already taken, for reporting alone. */
+ static fromRecords(records: MeterRecords): SocketMeter {
+ return new SocketMeter(records)
+ }
+
+ /** Listen on a free loopback port and forward everything to `target` (`http://127.0.0.1:PORT`). */
+ static async start(target: string): Promise<SocketMeter> {
+ const meter = new SocketMeter({ startedAt: Date.now(), sockets: [], refused: [], http: {} })
+ const upstream = new URL(target)
+ const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, handleProtocols: (set) => [...set][0] ?? false })
+ const server = createServer((req, res) => {
+ count(meter.http, routeOf(req.method ?? 'GET', req.url ?? '/'))
+ const forward = request({ host: upstream.hostname, port: upstream.port, method: req.method, path: req.url,
+ headers: { ...req.headers, host: upstream.host } }, (answer) => {
+ res.writeHead(answer.statusCode ?? 502, answer.headers)
+ answer.pipe(res)
+ })
+ forward.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end() })
+ req.pipe(forward)
+ })
+ server.on('upgrade', (req, socket, head) => meter.upgrade(req, socket, head, upstream, wss))
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const port = (server.address() as { port: number }).port
+ meter.server = server
+ meter.url = `http://127.0.0.1:${port}`
+ meter.wsUrl = `ws://127.0.0.1:${port}`
+ return meter
+ }
+
+ private upgrade(req: IncomingMessage, socket: Duplex, head: Buffer, upstream: URL, wss: WebSocketServer): void {
+ const query = new URL(req.url ?? '/', 'http://meter').searchParams
+ const endpoint = (req.url ?? '/').split('?')[0]
+ let attached = false
+ const protocols = String(req.headers['sec-websocket-protocol'] ?? '').split(',').map((p) => p.trim()).filter(Boolean)
+ const backend = new WebSocket(`ws://${upstream.host}${req.url ?? '/'}`, protocols, {
+ headers: forwardedHeaders(req), perMessageDeflate: false })
+ const refuse = (status: number): void => {
+ this.refused.push({ endpoint, status, at: Date.now() })
+ if (status > 0) socket.end(`HTTP/1.1 ${status} Refused\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
+ else socket.destroy()
+ }
+ let opened = false
+ backend.once('unexpected-response', (_r, res) => { opened = true; refuse(res.statusCode ?? 0); backend.terminate() })
+ backend.once('error', () => { if (!opened) { opened = true; refuse(0) } })
+ socket.once('error', () => backend.terminate())
+ // A client that gave up before the backend answered: the backend's side must not outlive it. The upgrade's
+ // socket is paused, so its end is only seen by reading it; a client sends nothing before the 101, and anything
+ // it did send goes back where `ws` finds it.
+ const quit = (): void => { if (!attached) backend.terminate() }
+ const watch = (): void => {
+ const early = socket.read()
+ if (early) { socket.off('readable', watch); socket.unshift(early) }
+ }
+ socket.on('readable', watch)
+ socket.once('end', quit)
+ socket.once('close', quit)
+ backend.once('open', () => {
+ opened = true
+ // Frames the backend sends before the client side is up wait here, in order.
+ const early: Array<[RawData, boolean]> = []
+ const hold = (data: RawData, binary: boolean): void => { early.push([data, binary]) }
+ backend.on('message', hold)
+ socket.off('readable', watch)
+ if (socket.destroyed || socket.readableEnded) { backend.terminate(); return }
+ attached = true
+ wss.handleUpgrade(req, socket, head, (client) => this.attach(client, backend, endpoint, query, early, hold))
+ })
+ }
+
+ private attach(client: WebSocket, backend: WebSocket, endpoint: string, query: URLSearchParams,
+ early: Array<[RawData, boolean]>, hold: (data: RawData, binary: boolean) => void): void {
+ const record: SocketRecord = { endpoint, ...declaredKind(endpoint, query), openedAt: Date.now(), closedAt: null, closeCode: null,
+ closeReason: '', selects: [] }
+ this.sockets.push(record)
+ this.live.add(client)
+ const pending = new Map<string, SelectRecord>()
+ const fromBackend = (data: RawData, binary: boolean): void => {
+ if (!binary) this.readAnswer(data, pending)
+ if (client.readyState === WebSocket.OPEN) client.send(data, { binary })
+ }
+ backend.off('message', hold)
+ for (const [data, binary] of early) fromBackend(data, binary)
+ backend.on('message', fromBackend)
+ client.on('message', (data, binary) => {
+ if (!binary) {
+ const frame = parse(data)
+ const machineId = frame?.type === 'machine_select' ? frame.payload?.machineId : undefined
+ if (typeof machineId === 'string') {
+ const select: SelectRecord = { machineId, at: Date.now(), outcome: null }
+ record.selects.push(select)
+ pending.set(machineId, select)
+ }
+ }
+ if (backend.readyState === WebSocket.OPEN) backend.send(data, { binary })
+ })
+ const finish = (code: number, reason: Buffer): void => {
+ if (record.closedAt !== null) return
+ record.closedAt = Date.now()
+ record.closeCode = code
+ record.closeReason = reason.toString()
+ this.live.delete(client)
+ }
+ backend.on('close', (code, reason) => {
+ finish(code, reason)
+ // 1005 (no code) and 1006 (abnormal) cannot be sent on the wire; they are what the client sees anyway.
+ if (code === 1005) client.close()
+ else if (code === 1006) client.terminate()
+ else client.close(code, reason)
+ })
+ client.on('close', (code, reason) => {
+ finish(code, reason)
+ if (code === 1005) backend.close()
+ else if (code === 1006) backend.terminate()
+ else backend.close(code, reason)
+ })
+ client.on('error', () => backend.terminate())
+ backend.on('error', () => client.terminate())
+ }
+
+ private readAnswer(data: RawData, pending: Map<string, SelectRecord>): void {
+ const frame = parse(data)
+ const machineId = frame?.payload?.machineId
+ if (!frame?.payload || typeof machineId !== 'string') return
+ const select = pending.get(machineId)
+ if (!select) return
+ if (frame.type === 'connected') select.outcome = 'accepted'
+ else if (frame.type === 'machine_select_error') select.outcome = String(frame.payload.error)
+ else return
+ pending.delete(machineId)
+ }
+
+ report(options: { now?: number; deletedMachineIds?: string[] } = {}): MeterReport {
+ const now = options.now ?? Date.now()
+ const deleted = new Set(options.deletedMachineIds ?? [])
+ const durationMs = now - this.startedAt
+ const endpoints: Record<string, EndpointReport> = {}
+ const inWindow = this.sockets.filter((s) => s.openedAt >= this.startedAt)
+ const refused = this.refused.filter((r) => r.at >= this.startedAt)
+ const names = new Set([...inWindow.map((s) => s.endpoint), ...refused.map((r) => r.endpoint)])
+ for (const name of names) {
+ const sockets = inWindow.filter((s) => s.endpoint === name)
+ const lifetimes = sockets.map((s) => (s.closedAt ?? now) - s.openedAt)
+ const closeCodes: Record<string, number> = {}
+ const selectOutcomes: Record<string, number> = {}
+ const selectsByMachine: Record<string, number> = {}
+ for (const s of sockets) {
+ if (s.closeCode !== null) count(closeCodes, String(s.closeCode))
+ for (const select of s.selects) {
+ count(selectOutcomes, select.outcome ?? 'unanswered')
+ count(selectsByMachine, select.machineId)
+ }
+ }
+ endpoints[name] = {
+ connects: sockets.length,
+ connectsPerMinute: durationMs > 0 ? sockets.length / (durationMs / 60_000) : 0,
+ refused: refused.filter((r) => r.endpoint === name).length,
+ medianLifetimeMs: median(lifetimes),
+ livedUnder2s: lifetimes.filter((ms) => ms < 2_000).length,
+ closedWithoutSelect: sockets.filter((s) => s.closedAt !== null && s.selects.length === 0).length,
+ attributed: attributedShare(sockets),
+ attributedByClient: Object.fromEntries([...new Set(sockets.map((s) => s.client))]
+ .map((kind) => [kind, attributedShare(sockets.filter((s) => s.client === kind))])),
+ closeCodes,
+ selectOutcomes,
+ deletedMachineSelects: sockets.reduce((n, s) => n + s.selects.filter((select) => deleted.has(select.machineId)).length, 0),
+ selectsByMachine,
+ acceptedThenDiedUnder1m: sockets.filter((s) => s.closedAt !== null && s.closedAt - s.openedAt < 60_000
+ && s.selects.some((select) => select.outcome === 'accepted')).length,
+ }
+ }
+ return { durationMs, endpoints, http: { ...this.http } }
+ }
+
+ async close(): Promise<void> {
+ for (const ws of this.live) ws.terminate()
+ const server = this.server
+ if (!server) return
+ server.closeAllConnections()
+ await new Promise((resolve) => server.close(resolve))
+ }
+}
+
+/** Attributed: a known kind and a version, as #2029 counts its 95%. */
+function attributedShare(sockets: SocketRecord[]): number {
+ return sockets.length ? sockets.filter((s) => s.client !== 'unknown' && s.version).length / sockets.length : 1
+}
+
+function parse(data: RawData): { type?: string; payload?: Record<string, any> } | null {
+ try {
+ const frame = JSON.parse(data.toString())
+ return frame && typeof frame === 'object' ? frame : null
+ } catch {
+ return null
+ }
+}
diff --git a/cli/e2e/harness/socketScenario.ts b/cli/e2e/harness/socketScenario.ts
new file mode 100644
index 000000000..a552da37e
--- /dev/null
+++ b/cli/e2e/harness/socketScenario.ts
@@ -0,0 +1,271 @@
+/**
+ * The WebSocket roadmap's scenario (Ken, 2026-10-28): what one account's clients do to the backend's
+ * sockets for a few minutes, measured by a recording proxy (socketMeter.ts) that every client dials
+ * instead of the backend. Nothing here reaches beyond this machine: a real backend on local Mongo and
+ * Redis with a fake sign-in (realBackend.ts), and every daemon in its own home on its own port.
+ *
+ * The account has four machines:
+ * - A and B, two signed-in daemons. A pinned B when it linked to it; B trusts A back.
+ * - X, deleted, still pinned on A: what a machine removed in the app leaves on a computer that linked it.
+ * - Y, never online, pinned on A: a computer that is off.
+ *
+ * Two clients, each a model of today's app, not of the fix:
+ * - A Desktop on A (`DesktopWindow`): a window per machine on A's local socket, redialling as
+ * desktop/lib/ws/ws_conn.dart does on a relayed machine, so every select of B, X and Y has A dial the
+ * backend's web-ws.
+ * - A browser tab (`WebTab`): its own web-ws with `client=web`, bound to B end to end, as the web build
+ * dials it.
+ *
+ * ⚠️ A Phase 0 or Phase 1 change to what the Desktop or the web build puts on the wire (a version on
+ * the URL, when it stops redialling) changes the model here in the same pull request: the model is what
+ * makes this scenario say anything about those clients.
+ */
+import { randomUUID } from 'node:crypto'
+import { writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import WebSocket from 'ws'
+import { b64e, newIdentity, type Identity } from '../../src/lib/e2ee/core.js'
+import { RelaySessionCrypto } from '../../src/lib/e2ee/relayClient.js'
+import { IsolatedDaemon, until } from './daemon.js'
+import { writeE2ee } from './fleet.js'
+import { account, startRealBackend, type Account, type RealBackend } from './realBackend.js'
+import { SocketMeter, type MeterReport, type SocketRecord } from './socketMeter.js'
+
+/** desktop/lib/ws/ws_conn.dart `reconnectDelay`: a window doubling from 1 s to 30 s, the wait in its second half. */
+export function reconnectDelay(attempt: number, random = Math.random): number {
+ const exponent = Math.min(Math.max(attempt - 1, 0), 5)
+ const window = Math.min(30_000, 1000 * (1 << exponent))
+ return Math.floor(window / 2) + Math.round(random() * (window / 2))
+}
+
+/** ws_conn.dart `connectionStableAfter`: a socket up this long starts its next backoff over. */
+const STABLE_AFTER_MS = 60_000
+
+/**
+ * One Desktop window on a relayed machine, as ws_conn.dart runs it over the local daemon: select on
+ * open, ready on the daemon's `connected`, and on any close but 4404 (the machine needs a link) redial
+ * after `reconnectDelay`.
+ */
+export class DesktopWindow {
+ dials = 0
+ /** The close codes the daemon ended this window's sockets with, in order. */
+ readonly closes: number[] = []
+ private attempt = 0
+ private ws: WebSocket | null = null
+ private retry: NodeJS.Timeout | null = null
+ private stable: NodeJS.Timeout | null = null
+ private closing = false
+ stoppedBy: number | null = null
+
+ constructor(private readonly daemon: IsolatedDaemon, readonly machineId: string) {}
+
+ open(): void {
+ if (this.closing) return
+ this.dials++
+ const ws = new WebSocket(`ws+unix://${this.daemon.socketPath}:/api/local-ws`)
+ this.ws = ws
+ ws.on('error', () => { /* 'close' follows */ })
+ ws.on('open', () => ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: this.machineId, localProtocolVersion: 1 } })))
+ ws.on('message', (raw, binary) => {
+ if (binary) return
+ let frame: { type?: string }
+ try { frame = JSON.parse(raw.toString()) } catch { return }
+ if (frame.type === 'connected') {
+ if (this.stable) clearTimeout(this.stable)
+ this.stable = setTimeout(() => { this.attempt = 0 }, STABLE_AFTER_MS)
+ }
+ })
+ ws.on('close', (code) => {
+ if (this.stable) clearTimeout(this.stable)
+ this.stable = null
+ if (this.closing) return
+ this.closes.push(code)
+ if (code === 4404) { this.stoppedBy = code; return }
+ this.attempt++
+ this.retry = setTimeout(() => this.open(), reconnectDelay(this.attempt))
+ })
+ }
+
+ close(): void {
+ this.closing = true
+ if (this.retry) clearTimeout(this.retry)
+ if (this.stable) clearTimeout(this.stable)
+ this.ws?.terminate()
+ }
+}
+
+/**
+ * A browser tab on machine `machineId`: web-ws with `client=web` (ws_conn.dart's query), select, then the
+ * end-to-end hello a paired browser sends. Redials like a window; 4403 stops it, as a sign-in for
+ * another environment does.
+ */
+export class WebTab {
+ dials = 0
+ sessions = 0
+ private attempt = 0
+ private ws: WebSocket | null = null
+ private retry: NodeJS.Timeout | null = null
+ private stable: NodeJS.Timeout | null = null
+ private closing = false
+
+ constructor(private readonly options: { wsUrl: string; token: string; machineId: string; identity: Identity; machinePub: Uint8Array }) {}
+
+ open(): void {
+ if (this.closing) return
+ this.dials++
+ const { wsUrl, token, machineId, identity, machinePub } = this.options
+ const ws = new WebSocket(`${wsUrl}/api/web-ws?autonomousEnv=prod&client=web`, [token])
+ this.ws = ws
+ const crypto = new RelaySessionCrypto({ machineId, selfIdentity: identity, peerPub: machinePub, groupSeen: new Map() })
+ ws.on('error', () => { /* 'close' follows */ })
+ ws.on('open', () => ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId } })))
+ ws.on('message', (raw, binary) => {
+ if (binary || crypto.ready) return
+ let frame: { type?: string; payload?: Record<string, any> }
+ try { frame = JSON.parse(raw.toString()) } catch { return }
+ if (frame.type === 'connected' && frame.payload?.machineId === machineId) ws.send(JSON.stringify(crypto.helloFrame()))
+ else if (frame.type === 'e2e_welcome' && crypto.handleWelcome(frame.payload ?? {})) {
+ this.sessions++
+ if (this.stable) clearTimeout(this.stable)
+ this.stable = setTimeout(() => { this.attempt = 0 }, STABLE_AFTER_MS)
+ }
+ })
+ ws.on('close', (code) => {
+ if (this.stable) clearTimeout(this.stable)
+ this.stable = null
+ if (this.closing || code === 4403) return
+ this.attempt++
+ this.retry = setTimeout(() => this.open(), reconnectDelay(this.attempt))
+ })
+ }
+
+ close(): void {
+ this.closing = true
+ if (this.retry) clearTimeout(this.retry)
+ if (this.stable) clearTimeout(this.stable)
+ this.ws?.terminate()
+ }
+}
+
+export interface ScenarioResult {
+ report: MeterReport
+ /** Every socket the meter saw, for checks the report does not sum up. */
+ sockets: SocketRecord[]
+ machines: { a: string; b: string; deleted: string; offline: string }
+ /** What the scenario's own clients saw: each Desktop window's dials and the close codes it was sent, the tab's sessions. */
+ clients: {
+ windows: Record<'b' | 'deleted' | 'offline', { dials: number; closes: number[] }>
+ web: { dials: number; sessions: number }
+ }
+ /** The backend's own log, for a failing test to point at. */
+ backendLog: string
+}
+
+/**
+ * What a run is missing to prove anything; empty when it did everything it should. Each check on the run also
+ * passes when nothing happened (no deleted-machine select, no quick redial), so a run that never reached a machine
+ * through A's relay, never opened the tab's session, was never refused X or selected Y once must fail, loudly.
+ */
+export function shortfalls(result: ScenarioResult): string[] {
+ const missing: string[] = []
+ const webWs = result.sockets.filter((s) => s.endpoint === '/api/web-ws')
+ if (!(result.report.endpoints['/api/web-ws']?.connects > 0)) missing.push('no web-ws connects')
+ const relayed = webWs.some((s) => s.client !== 'web'
+ && s.selects.some((select) => select.machineId === result.machines.b && select.outcome === 'accepted'))
+ if (!relayed) missing.push('machine B was never accepted through a daemon relay')
+ if (result.clients.web.sessions < 1) missing.push('the browser tab never opened a session')
+ if (result.clients.windows.deleted.closes.length < 1) missing.push('the window to the deleted machine was never refused')
+ const offline = webWs.reduce((n, s) => n + s.selects.filter((select) => select.machineId === result.machines.offline).length, 0)
+ if (offline < 2) missing.push(`the offline machine was selected ${offline} times, not at least twice`)
+ return missing
+}
+
+async function resolveMachine(backend: RealBackend, who: Account, label: string): Promise<{ machineId: string; computerId: string }> {
+ const computerId = randomUUID()
+ const r = await backend.api(who, '/api/machines/resolve-computer', 'POST', { computerId, label })
+ if (r.status !== 200) throw new Error(`resolve-computer ${label}: ${r.status}`)
+ return { machineId: r.body.data.machine.machineId as string, computerId }
+}
+
+/** A daemon signed in as `who` on machine `machine`, dialling the backend through the meter. */
+async function machineDaemon(meter: SocketMeter, who: Account, machine: { machineId: string; computerId: string },
+ e2ee: Record<string, unknown>, stops: Array<() => unknown>): Promise<IsolatedDaemon> {
+ const daemon = await IsolatedDaemon.create({ env: {
+ ADAPTER_COMPUTER_ID: machine.computerId, BACKEND_WS_URL: meter.wsUrl, WEB_URL: meter.url,
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200' } })
+ // Before anything else can throw: the daemon's tmux server and folders exist from here on.
+ stops.push(() => daemon.close())
+ writeFileSync(join(daemon.root, 'auth/session.json'), JSON.stringify({ version: 1, accessToken: who.token,
+ refreshToken: 'x', autonomousEnv: 'prod', computerId: machine.computerId, machineId: machine.machineId,
+ expiresAt: Date.now() + 3_600_000, updatedAt: Date.now() }), { mode: 0o600 })
+ await writeE2ee(daemon, e2ee)
+ return daemon
+}
+
+const seen = (window: DesktopWindow) => ({ dials: window.dials, closes: [...window.closes] })
+
+/** Run the scenario for `durationMs` once every client is up, and report what the meter saw over the whole run. */
+export async function runSocketScenario(options: { durationMs: number; log?: (line: string) => void }): Promise<ScenarioResult> {
+ const log = options.log ?? (() => {})
+ const alice = account('alice')
+ const stops: Array<() => unknown> = []
+ try {
+ const backend = await startRealBackend([alice], log)
+ stops.push(() => backend.stop())
+ const meter = await SocketMeter.start(backend.url)
+ stops.push(() => meter.close())
+
+ const [a, b, deleted, offline] = [await resolveMachine(backend, alice, 'machine-a'), await resolveMachine(backend, alice, 'machine-b'),
+ await resolveMachine(backend, alice, 'machine-x'), await resolveMachine(backend, alice, 'machine-y')]
+ const removed = await backend.api(alice, `/api/machines/${deleted.machineId}`, 'DELETE')
+ if (removed.status !== 200) throw new Error(`deleting machine-x: ${removed.status}`)
+
+ const idA = newIdentity(), idB = newIdentity(), tab = newIdentity()
+ const linkedAt = Date.now()
+ const daemonA = await machineDaemon(meter, alice, a, {
+ 'identity.json': { priv: b64e(idA.priv), pub: b64e(idA.pub) },
+ // Pins as `harness link connect` left them; X's and Y's keys are never used, their selects fail first.
+ 'machinePeers.json': [
+ { machineId: b.machineId, pub: b64e(idB.pub), label: 'machine-b', linkedAt },
+ { machineId: deleted.machineId, pub: b64e(newIdentity().pub), label: 'machine-x', linkedAt },
+ { machineId: offline.machineId, pub: b64e(newIdentity().pub), label: 'machine-y', linkedAt },
+ ],
+ }, stops)
+ const daemonB = await machineDaemon(meter, alice, b, {
+ 'identity.json': { priv: b64e(idB.priv), pub: b64e(idB.pub) },
+ 'paired.json': [
+ { identityPub: b64e(idA.pub), label: 'machine-a', pairedAt: linkedAt, role: 'web', machineId: a.machineId, kind: 'machine' },
+ { identityPub: b64e(tab.pub), label: 'browser', pairedAt: linkedAt, role: 'web' },
+ ],
+ }, stops)
+ await Promise.all([daemonA.start(), daemonB.start()])
+ for (const daemon of [daemonA, daemonB]) {
+ await until('daemon connected', async () => (await (await fetch(`http://127.0.0.1:${daemon.port}/api/status`,
+ { headers: daemon.localHeaders() })).json() as { connected?: boolean }).connected === true, 60_000, 200)
+ }
+ log('daemons connected')
+
+ const windows = [b, deleted, offline].map((m) => new DesktopWindow(daemonA, m.machineId))
+ const web = new WebTab({ wsUrl: meter.wsUrl, token: alice.token, machineId: b.machineId, identity: tab, machinePub: idB.pub })
+ // The rates are the clients' from here; the daemons' own start (their adapter sockets) is before the window.
+ meter.startClock()
+ for (const client of [...windows, web]) {
+ client.open()
+ stops.push(() => client.close())
+ }
+ await new Promise((resolve) => setTimeout(resolve, options.durationMs))
+ log(`windows dialled ${windows.map((w) => `${w.machineId.slice(0, 6)}:${w.dials}${w.stoppedBy ? `(stopped ${w.stoppedBy})` : ''}`).join(' ')}; web ${web.dials} dials, ${web.sessions} sessions`)
+ return {
+ report: meter.report({ deletedMachineIds: [deleted.machineId] }),
+ sockets: meter.sockets,
+ clients: {
+ windows: { b: seen(windows[0]), deleted: seen(windows[1]), offline: seen(windows[2]) },
+ web: { dials: web.dials, sessions: web.sessions },
+ },
+ machines: { a: a.machineId, b: b.machineId, deleted: deleted.machineId, offline: offline.machineId },
+ backendLog: backend.logPath,
+ }
+ } finally {
+ for (const stop of stops.reverse()) await Promise.resolve(stop()).catch(() => {})
+ }
+}
diff --git a/cli/e2e/socketChurn.e2e.ts b/cli/e2e/socketChurn.e2e.ts
new file mode 100644
index 000000000..50853d291
--- /dev/null
+++ b/cli/e2e/socketChurn.e2e.ts
@@ -0,0 +1,71 @@
+/**
+ * The WebSocket roadmap's Done criteria for Phase 0 and Phase 1 (Ken, 2026-10-28), judged on one
+ * account's sockets for a few minutes (harness/socketScenario.ts): two daemons, a deleted machine X and
+ * an offline machine Y pinned on one of them, a Desktop's windows and a browser tab, all on a local
+ * backend and measured by a recording proxy in front of it.
+ *
+ * The roadmap's population numbers (under 40 web-ws connects a minute, a median lifetime over a minute)
+ * are prod's, over every account. One account cannot reach them or miss them: on the main of 2026-10-28
+ * this scenario made 12.5 connects a minute, already under 40, while the window to the offline machine
+ * alone kept the median at a few milliseconds. So each churn cause the scenario holds is checked on its
+ * own, and the two numbers are printed with the report for the prod measurement after release.
+ *
+ * Every check here also passes when nothing happened, so a run that did not do what the scenario says (A's relay
+ * never reached B, the tab never opened a session, X was never refused, Y was selected under twice) fails every
+ * check with what it missed (socketScenarioRan.e2e.ts).
+ *
+ * Red on the main of 2026-10-28; each check turns green as the phase that owns it lands, and a phase ships
+ * only once its checks pass. Opt in with HARNESS_E2E_SERVICES_DIR, as the other real-backend suites do;
+ * scripts/socket-churn.sh runs it and keeps the report.
+ *
+ * SOCKET_SCENARIO_MINUTES sets the run (default 3). SOCKET_REPORT_FILE keeps the report as JSON.
+ */
+import { writeFileSync } from 'node:fs'
+import { beforeAll, describe, expect, it } from 'vitest'
+import { runSocketScenario, shortfalls, type ScenarioResult } from './harness/socketScenario.js'
+
+const minutes = Number(process.env.SOCKET_SCENARIO_MINUTES ?? 3)
+let result: ScenarioResult
+
+/** When each web-ws select of `machineId` was sent, in order. */
+const selectTimes = (machineId: string): number[] => result.sockets
+ .filter((s) => s.endpoint === '/api/web-ws')
+ .flatMap((s) => s.selects.filter((select) => select.machineId === machineId).map((select) => select.at))
+ .sort((a, b) => a - b)
+
+describe.skipIf(!process.env.HARNESS_E2E_SERVICES_DIR)('WebSocket phases 0 and 1: one account\'s sockets', () => {
+ beforeAll(async () => {
+ const lines: string[] = []
+ result = await runSocketScenario({ durationMs: minutes * 60_000, log: (line) => lines.push(line) })
+ console.log(`socket scenario: ${lines.join(' | ')}\n${JSON.stringify(result.report, null, 2)}`)
+ if (process.env.SOCKET_REPORT_FILE) writeFileSync(process.env.SOCKET_REPORT_FILE, JSON.stringify(result, null, 2))
+ const missing = shortfalls(result)
+ if (missing.length) throw new Error(`The scenario did not run as it says, so no check here means anything: ${missing.join('; ')}`)
+ }, minutes * 60_000 + 240_000)
+
+ const webWs = () => result.report.endpoints['/api/web-ws']
+
+ it('Phase 0: at least 95% of web-ws connects name their client kind and version', () => {
+ expect(webWs().attributed).toBeGreaterThanOrEqual(0.95)
+ })
+
+ it('Phase 0: so does each kind of client, so many relays cannot hide one kind that never does', () => {
+ const below = Object.entries(webWs().attributedByClient).filter(([, share]) => share < 0.95)
+ expect(below).toEqual([])
+ })
+
+ it('Phase 1: a deleted machine is selected once, by the socket that finds it gone, and never again', () => {
+ expect(selectTimes(result.machines.deleted).length).toBeLessThanOrEqual(1)
+ })
+
+ it('Phase 1: an offline machine is selected again only after the backend\'s retryAfterMs (30 s)', () => {
+ const times = selectTimes(result.machines.offline)
+ const gaps = times.slice(1).map((at, i) => at - times[i])
+ // A second of slack for the timers on both sides.
+ expect(Math.min(...gaps, Infinity)).toBeGreaterThanOrEqual(29_000)
+ })
+
+ it('Phase 1: no socket that selected a machine is dropped within a minute', () => {
+ expect(webWs().acceptedThenDiedUnder1m).toBe(0)
+ })
+})
diff --git a/cli/e2e/socketMeter.e2e.ts b/cli/e2e/socketMeter.e2e.ts
new file mode 100644
index 000000000..1974ace83
--- /dev/null
+++ b/cli/e2e/socketMeter.e2e.ts
@@ -0,0 +1,233 @@
+/**
+ * The socket meter (harness/socketMeter.ts) against a stand-in backend: what it records is what the
+ * WebSocket phases' Done criteria are judged on (socketChurn.e2e.ts), so it is checked here on its own,
+ * with no Mongo, Redis or daemon. The stand-in answers the way the real web-ws does: `connected` on
+ * open, then `connected {machineId}` or `machine_select_error {error}` for a `machine_select`, and it
+ * refuses a bad credential before the upgrade. `slow-token` holds the upgrade for a moment, long enough
+ * for a client to give up first.
+ */
+import { createServer, type Server } from 'node:http'
+import { once } from 'node:events'
+import { afterEach, describe, expect, it } from 'vitest'
+import WebSocket, { WebSocketServer } from 'ws'
+import { SocketMeter } from './harness/socketMeter.js'
+
+const KNOWN = 'aa'.repeat(16), DELETED = 'dd'.repeat(16)
+
+interface StandIn {
+ server: Server
+ url: string
+ protocols: string[]
+ /** Each upgrade's request headers, as the backend got them. */
+ headers: Array<Record<string, string | string[] | undefined>>
+ /** Upgraded sockets not closed yet. */
+ open: Set<WebSocket>
+}
+
+async function standIn(): Promise<StandIn> {
+ const protocols: string[] = []
+ const headers: StandIn['headers'] = []
+ const open = new Set<WebSocket>()
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (set) => [...set][0] ?? false })
+ const server = createServer((req, res) => {
+ res.setHeader('content-type', 'application/json')
+ res.end(JSON.stringify({ path: req.url, method: req.method }))
+ })
+ server.on('upgrade', (req, socket, head) => {
+ const token = String(req.headers['sec-websocket-protocol'] ?? '')
+ if (token !== 'good-token' && token !== 'slow-token') {
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
+ return
+ }
+ protocols.push(token)
+ headers.push(req.headers)
+ const upgrade = () => wss.handleUpgrade(req, socket, head, (ws) => {
+ open.add(ws)
+ ws.on('close', () => open.delete(ws))
+ ws.send(JSON.stringify({ type: 'connected', payload: { userId: 'u1' } }))
+ ws.on('message', (raw, binary) => {
+ if (binary) { ws.send(raw, { binary: true }); return }
+ const frame = JSON.parse(raw.toString())
+ if (frame.type !== 'machine_select') return
+ if (frame.payload.machineId === KNOWN) ws.send(JSON.stringify({ type: 'connected', payload: { machineId: KNOWN } }))
+ else {
+ ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: frame.payload.machineId, error: 'NOT_YOUR_MACHINE' } }))
+ ws.close(4404, 'gone')
+ }
+ })
+ })
+ if (token === 'slow-token') setTimeout(upgrade, 300)
+ else upgrade()
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ return { server, url: `http://127.0.0.1:${(server.address() as { port: number }).port}`, protocols, headers, open }
+}
+
+async function dial(url: string, protocol = 'good-token', headers: Record<string, string> = {}): Promise<{ ws: WebSocket; frames: any[]; closed: Promise<number> }> {
+ const ws = new WebSocket(url, [protocol], { headers })
+ const frames: any[] = []
+ ws.on('message', (raw, binary) => { if (!binary) frames.push(JSON.parse(raw.toString())) })
+ const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)))
+ await once(ws, 'open')
+ return { ws, frames, closed }
+}
+
+const until = async (what: string, probe: () => boolean, ms = 5_000): Promise<void> => {
+ const deadline = Date.now() + ms
+ while (!probe()) {
+ if (Date.now() > deadline) throw new Error(`Timed out: ${what}`)
+ await new Promise((r) => setTimeout(r, 20))
+ }
+}
+
+describe('socket meter', () => {
+ const stops: Array<() => unknown> = []
+ afterEach(async () => { for (const stop of stops.splice(0).reverse()) await stop() })
+
+ it('records each socket with its client, its selects and their answers, and how it closed', async () => {
+ const backend = await standIn()
+ stops.push(() => { backend.server.closeAllConnections(); backend.server.close() })
+ const meter = await SocketMeter.start(backend.url)
+ stops.push(() => meter.close())
+
+ const web = await dial(`${meter.wsUrl}/api/web-ws?autonomousEnv=prod&client=web`, 'good-token', { 'x-harness-probe': 'kept', cookie: 'c=1' })
+ await until('the backend hello', () => web.frames.length === 1)
+ web.ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: KNOWN } }))
+ await until('the select answer', () => web.frames.length === 2)
+ expect(web.frames[1]).toEqual({ type: 'connected', payload: { machineId: KNOWN } })
+ // Binary frames pass both ways untouched.
+ const echoed = new Promise<Buffer>((resolve) => web.ws.once('message', (raw) => resolve(raw as Buffer)))
+ web.ws.send(Buffer.from([1, 2, 3]))
+ expect([...await echoed]).toEqual([1, 2, 3])
+
+ const relay = await dial(`${meter.wsUrl}/api/web-ws?autonomousEnv=prod&client=relay&v=1.2.3`)
+ relay.ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: DELETED } }))
+ expect(await relay.closed).toBe(4404)
+
+ const idle = await dial(`${meter.wsUrl}/api/web-ws?autonomousEnv=prod`)
+ idle.ws.close(1000)
+ expect(await idle.closed).toBe(1000)
+
+ // As the backend reads them (#2029 wsAttribution.ts declaredKind): a kind it does not know is `unknown`, a
+ // version that is not a short plain token is none, and the adapter is the daemon.
+ const odd = await dial(`${meter.wsUrl}/api/web-ws?client=bogus&v=${encodeURIComponent('1 <b>')}`)
+ odd.ws.close(1000)
+ await odd.closed
+ const adapter = await dial(`${meter.wsUrl}/api/adapter-ws?v=2.1.0`)
+ adapter.ws.close(1000)
+ await adapter.closed
+
+ await until('the four closes recorded', () => meter.sockets.filter((s) => s.closedAt !== null).length === 4)
+ // The credential reaches the backend as the subprotocol, as clients send it, and the client's own headers
+ // with it; the handshake's are the meter's own.
+ expect(backend.protocols).toEqual(Array(5).fill('good-token'))
+ expect(backend.headers[0]).toMatchObject({ 'x-harness-probe': 'kept', cookie: 'c=1' })
+
+ const [first, second, third, fourth, fifth] = meter.sockets
+ expect(first).toMatchObject({ endpoint: '/api/web-ws', client: 'web', version: null, closedAt: null,
+ selects: [{ machineId: KNOWN, outcome: 'accepted' }] })
+ expect(second).toMatchObject({ endpoint: '/api/web-ws', client: 'relay', version: '1.2.3', closeCode: 4404,
+ selects: [{ machineId: DELETED, outcome: 'NOT_YOUR_MACHINE' }] })
+ expect(third).toMatchObject({ endpoint: '/api/web-ws', client: 'unknown', version: null, closeCode: 1000, selects: [] })
+ expect(fourth).toMatchObject({ client: 'unknown', version: null })
+ expect(fifth).toMatchObject({ endpoint: '/api/adapter-ws', client: 'daemon', version: '2.1.0' })
+ web.ws.close()
+ await web.closed
+ })
+
+ it('closes its side to the backend when the client gives up before the upgrade completes', async () => {
+ const backend = await standIn()
+ stops.push(() => { backend.server.closeAllConnections(); backend.server.close() })
+ const meter = await SocketMeter.start(backend.url)
+ stops.push(() => meter.close())
+
+ const quitter = new WebSocket(`${meter.wsUrl}/api/web-ws?client=web`, ['slow-token'])
+ quitter.on('error', () => {})
+ await until('the backend holding the upgrade', () => backend.protocols.length === 1)
+ quitter.terminate()
+ // The backend's upgrade completes after the client left; the meter must not keep that socket.
+ await new Promise((r) => setTimeout(r, 600))
+ await until('the backend side closed', () => backend.open.size === 0)
+ expect(meter.sockets).toEqual([])
+ })
+
+ it('counts a refused upgrade apart from the sockets, and HTTP requests by route', async () => {
+ const backend = await standIn()
+ stops.push(() => { backend.server.closeAllConnections(); backend.server.close() })
+ const meter = await SocketMeter.start(backend.url)
+ stops.push(() => meter.close())
+
+ const refused = new WebSocket(`${meter.wsUrl}/api/web-ws?client=web`, ['bad-token'])
+ refused.on('error', () => {})
+ const status = await new Promise<number>((resolve) => {
+ refused.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0))
+ refused.once('open', () => resolve(101))
+ })
+ refused.terminate()
+ expect(status).toBe(401)
+
+ const machine = 'ab12'.repeat(8)
+ for (const path of ['/api/machines', '/api/machines', `/api/machines/${machine}/agents`, '/api/harness-shares?x=1']) {
+ const r = await fetch(`${meter.url}${path}`)
+ expect(await r.json()).toEqual({ path, method: 'GET' })
+ }
+ const posted = await fetch(`${meter.url}/api/machines/resolve-computer`, { method: 'POST', body: '{}' })
+ expect(((await posted.json()) as { method: string }).method).toBe('POST')
+
+ expect(meter.sockets).toEqual([])
+ expect(meter.refused).toMatchObject([{ endpoint: '/api/web-ws', status: 401 }])
+ expect(meter.report().http).toEqual({
+ 'GET /api/machines': 2, 'GET /api/machines/:id/agents': 1, 'GET /api/harness-shares': 1, 'POST /api/machines/resolve-computer': 1,
+ })
+ })
+
+ it('reports per endpoint: connects a minute, median lifetime, sockets never selected, attribution, deleted-machine selects', () => {
+ const at = 1_000_000
+ const meter = SocketMeter.fromRecords({
+ startedAt: at,
+ sockets: [
+ // Two relays to a deleted machine, a second each.
+ { endpoint: '/api/web-ws', client: 'relay', version: '1.0.0', openedAt: at, closedAt: at + 1_000, closeCode: 1011, closeReason: '',
+ selects: [{ machineId: DELETED, at, outcome: 'NOT_YOUR_MACHINE' }] },
+ { endpoint: '/api/web-ws', client: 'relay', version: '1.0.0', openedAt: at + 10_000, closedAt: at + 11_000, closeCode: 1011, closeReason: '',
+ selects: [{ machineId: DELETED, at: at + 10_000, outcome: 'NOT_YOUR_MACHINE' }] },
+ // A web tab, selected, open to the end.
+ { endpoint: '/api/web-ws', client: 'web', version: null, openedAt: at, closedAt: null, closeCode: null, closeReason: '',
+ selects: [{ machineId: KNOWN, at, outcome: 'accepted' }] },
+ // A second tab, selected, dropped after 30 s.
+ { endpoint: '/api/web-ws', client: 'web', version: '2.0.0', openedAt: at + 20_000, closedAt: at + 50_000, closeCode: 1006, closeReason: '',
+ selects: [{ machineId: KNOWN, at: at + 20_000, outcome: 'accepted' }] },
+ // A daemon relay that never selected, 90 s.
+ { endpoint: '/api/web-ws', client: 'unknown', version: null, openedAt: at, closedAt: at + 90_000, closeCode: 1000, closeReason: '', selects: [] },
+ { endpoint: '/api/adapter-ws', client: 'daemon', version: '1.0.0', openedAt: at, closedAt: null, closeCode: null, closeReason: '', selects: [] },
+ // Opened before the clock started (the daemons' own start): outside the report.
+ { endpoint: '/api/web-ws', client: 'relay', version: '1.0.0', openedAt: at - 5_000, closedAt: at - 4_000, closeCode: 1011, closeReason: '',
+ selects: [{ machineId: DELETED, at: at - 5_000, outcome: 'NOT_YOUR_MACHINE' }] },
+ ],
+ refused: [{ endpoint: '/api/web-ws', status: 401, at }],
+ http: {},
+ })
+ const report = meter.report({ now: at + 120_000, deletedMachineIds: [DELETED] })
+ expect(report.durationMs).toBe(120_000)
+ const web = report.endpoints['/api/web-ws']
+ expect(web.connects).toBe(5)
+ expect(web.connectsPerMinute).toBe(2.5)
+ expect(web.refused).toBe(1)
+ // Lifetimes 1 s, 1 s, 30 s, 90 s, 120 s (still open at the report).
+ expect(web.medianLifetimeMs).toBe(30_000)
+ expect(web.livedUnder2s).toBe(2)
+ expect(web.closedWithoutSelect).toBe(1)
+ // Attributed: a client kind and a version. The two relays and the second tab.
+ expect(web.attributed).toBe(0.6)
+ // And by kind, so many attributed relays cannot hide a kind that never is.
+ expect(web.attributedByClient).toEqual({ relay: 1, web: 0.5, unknown: 0 })
+ expect(web.closeCodes).toEqual({ 1011: 2, 1000: 1, 1006: 1 })
+ expect(web.selectOutcomes).toEqual({ NOT_YOUR_MACHINE: 2, accepted: 2 })
+ expect(web.deletedMachineSelects).toBe(2)
+ expect(web.selectsByMachine).toEqual({ [DELETED]: 2, [KNOWN]: 2 })
+ // Selected fine and closed within a minute: the second tab, not the first (still open at 120 s).
+ expect(web.acceptedThenDiedUnder1m).toBe(1)
+ expect(report.endpoints['/api/adapter-ws'].connects).toBe(1)
+ })
+})
diff --git a/cli/e2e/socketScenarioRan.e2e.ts b/cli/e2e/socketScenarioRan.e2e.ts
new file mode 100644
index 000000000..d67ab3b2b
--- /dev/null
+++ b/cli/e2e/socketScenarioRan.e2e.ts
@@ -0,0 +1,59 @@
+/**
+ * The socket scenario's checks (socketChurn.e2e.ts) gate each WebSocket phase's release, and every one of them
+ * also passes when nothing happened: no select of a deleted machine, no quick redial of an offline one. So the
+ * scenario first proves it ran (harness/socketScenario.ts `shortfalls`), and these are the ways it can fail to.
+ */
+import { describe, expect, it } from 'vitest'
+import { shortfalls, type ScenarioResult } from './harness/socketScenario.js'
+import type { SocketRecord } from './harness/socketMeter.js'
+
+const A = 'a'.repeat(32), B = 'b'.repeat(32), X = 'c'.repeat(32), Y = 'd'.repeat(32)
+const at = 1_000_000
+
+const socket = (client: string, machineId: string, outcome: string): SocketRecord => ({
+ endpoint: '/api/web-ws', client, version: null, openedAt: at, closedAt: null, closeCode: null, closeReason: '',
+ selects: [{ machineId, at, outcome }],
+})
+
+/** What a run that did everything it should looks like. */
+function ran(): ScenarioResult {
+ const sockets = [socket('unknown', B, 'accepted'), socket('web', B, 'accepted'), socket('unknown', X, 'NOT_YOUR_MACHINE'),
+ socket('unknown', Y, 'MACHINE_OFFLINE'), socket('unknown', Y, 'MACHINE_OFFLINE')]
+ return {
+ report: { durationMs: 180_000, http: {}, endpoints: { '/api/web-ws': { connects: sockets.length } as any } },
+ sockets,
+ machines: { a: A, b: B, deleted: X, offline: Y },
+ clients: {
+ windows: { b: { dials: 1, closes: [] }, deleted: { dials: 3, closes: [1011, 1011, 1011] }, offline: { dials: 3, closes: [1011, 1011, 1011] } },
+ web: { dials: 1, sessions: 1 },
+ },
+ backendLog: '',
+ }
+}
+
+describe('the socket scenario proves it ran', () => {
+ it('finds nothing missing in a run that did everything', () => {
+ expect(shortfalls(ran())).toEqual([])
+ })
+
+ it('names each thing a run that did nothing is missing', () => {
+ const idle = ran()
+ idle.sockets = []
+ idle.report.endpoints = {}
+ idle.clients.windows.deleted.closes = []
+ idle.clients.web.sessions = 0
+ expect(shortfalls(idle)).toEqual([
+ 'no web-ws connects',
+ 'machine B was never accepted through a daemon relay',
+ 'the browser tab never opened a session',
+ 'the window to the deleted machine was never refused',
+ 'the offline machine was selected 0 times, not at least twice',
+ ])
+ })
+
+ it('does not count the browser tab as the daemon relay reaching B', () => {
+ const tabOnly = ran()
+ tabOnly.sockets = tabOnly.sockets.filter((s) => !(s.client !== 'web' && s.selects[0].machineId === B))
+ expect(shortfalls(tabOnly)).toEqual(['machine B was never accepted through a daemon relay'])
+ })
+})
diff --git a/cli/scripts/lib/dshRegistry.mjs b/cli/scripts/lib/dshRegistry.mjs
index 34460b433..d6efd714f 100644
--- a/cli/scripts/lib/dshRegistry.mjs
+++ b/cli/scripts/lib/dshRegistry.mjs
@@ -24,6 +24,7 @@ export function storeEntry(path, manifest, facts) {
if (manifest.engine !== undefined) entry.engines = manifest.kind === 'viewer' || manifest.engine === 'terminal'
? [] : [manifest.engine, ...processEngines.filter(engine => engine !== manifest.engine)]
if (typeof manifest.viewer?.use === 'string') entry.viewerUse = manifest.viewer.use
+ if (manifest.toolchain?.setup || manifest.toolchain?.doctor) entry.runsScripts = true
entry.tier = manifest.viewer ? 2 : manifest.verdict ? 1 : 0
entry.verified = true
return entry
diff --git a/cli/scripts/socket-churn.sh b/cli/scripts/socket-churn.sh
new file mode 100755
index 000000000..2ca5e8a89
--- /dev/null
+++ b/cli/scripts/socket-churn.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# The WebSocket roadmap's scenario (cli/e2e/socketChurn.e2e.ts): one account's daemons, Desktop windows and
+# browser tab on a local backend, measured by a recording proxy. Prints the checks and keeps the full report
+# (per endpoint: connects a minute, lifetimes, close codes, selects and their answers; HTTP requests per route).
+#
+# HARNESS_E2E_SERVICES_DIR=<dir with mongodb-memory-server and redis-memory-server> \
+# scripts/socket-churn.sh [minutes, default 3] [report.json, default a new file in the temp folder]
+#
+# A report path is read from where the script was called, never from cli/, so no report lands in the checkout.
+# HARNESS_E2E_MONGOD / HARNESS_E2E_REDIS_SERVER point at system binaries instead of downloaded ones.
+set -euo pipefail
+: "${HARNESS_E2E_SERVICES_DIR:?must name a folder with mongodb-memory-server and redis-memory-server}"
+export SOCKET_SCENARIO_MINUTES="${1:-3}"
+report="${2:-$(mktemp "${TMPDIR:-/tmp}/socket-report.XXXXXX")}"
+export SOCKET_REPORT_FILE="$(cd "$(dirname "$report")" && pwd)/$(basename "$report")"
+cd "$(dirname "$0")/.."
+status=0
+npx vitest run --config vitest.e2e.config.ts e2e/socketChurn.e2e.ts || status=$?
+echo "report: $SOCKET_REPORT_FILE"
+exit "$status"
diff --git a/cli/src/dsh/catalogPublisher.spec.ts b/cli/src/dsh/catalogPublisher.spec.ts
index da68d0ca4..dcb318ab2 100644
--- a/cli/src/dsh/catalogPublisher.spec.ts
+++ b/cli/src/dsh/catalogPublisher.spec.ts
@@ -53,6 +53,24 @@ describe('Store publication', () => {
}
})
+ it('says which packages run a setup or check script, so a computer that cannot run them refuses before downloading', () => {
+ const root = fixture()
+ expect(parseStoreCatalog(createStoreCatalog(root, ref)).entries[0]).not.toHaveProperty('runsScripts')
+ writeFileSync(join(root, 'agents', 'game', 'harness.json'), JSON.stringify({ spec: 1, id: 'autonomous/game', name: 'Game', engine: 'claude', toolchain: { setup: 'setup.sh' } }))
+ expect(parseStoreCatalog(createStoreCatalog(root, ref)).entries[0]!.runsScripts).toBe(true)
+ // The real shelf: on 2026-10-28, 65 of 67 packages ran one; `devices` runs none.
+ const real = parseStoreCatalog(createStoreCatalog(fileURLToPath(new URL('../../../store', import.meta.url)), ref)).entries
+ expect(real.filter(entry => entry.runsScripts).length).toBeGreaterThan(50)
+ expect(real.find(entry => entry.id === 'autonomous/devices') ?? {}).not.toHaveProperty('runsScripts')
+ })
+
+ it('refuses to publish a runsScripts that is not `true`, which the CLI would refuse the whole catalog over', () => {
+ const root = fixture()
+ mkdirSync(join(root, 'registry', 'acme'), { recursive: true })
+ writeFileSync(join(root, 'registry', 'acme', 'tool.json'), JSON.stringify({ id: 'acme/tool', name: 'Tool', engine: 'claude', repo: 'https://example.com/tool', runsScripts: 'yes' }))
+ expect(() => createStoreCatalog(root, ref)).toThrow('acme/tool: invalid runsScripts')
+ })
+
it('rejects corrupt manifests instead of silently publishing a partial catalog', () => {
const root = fixture()
writeFileSync(join(root, 'agents', 'game', 'harness.json'), '{bad')
diff --git a/cli/src/dsh/install.spec.ts b/cli/src/dsh/install.spec.ts
index d20fa5eb0..cc7762548 100644
--- a/cli/src/dsh/install.spec.ts
+++ b/cli/src/dsh/install.spec.ts
@@ -474,19 +474,23 @@ describe('installDsh, every way it can go', () => {
beforeEach(() => { Object.defineProperty(process, 'platform', { ...platform, value: 'win32' }) })
afterEach(() => { Object.defineProperty(process, 'platform', platform) })
- it('a harness with a setup or a doctor is refused before either runs, said in words, and not recorded', async () => {
+ it('a harness with a setup or a doctor is refused once fetched, before it is placed, and nothing stays on disk', async () => {
// 2026-10-28: every Store install on Windows failed; their setup and doctor ran through a /bin/sh Windows lacks.
+ // The review of #2026 found the refusal came after the package was placed, so its files stayed, unrecorded.
const detail = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'
- for (const toolchain of [{ setup: 'setup.sh' }, { doctor: 'doctor.sh' }]) {
+ const placed = (): boolean => { try { lstatSync(dshInstallDir('acme/thing')); return true } catch { return false } }
+ for (const [toolchain, link] of [[{ setup: 'setup.sh' }, false], [{ doctor: 'doctor.sh' }, false], [{ setup: 'setup.sh' }, true]] as const) {
rmSync(join(root, 'src'), { recursive: true, force: true })
const repo = thing({ toolchain }, { 'setup.sh': '#!/bin/sh\ntouch set-up\n', 'doctor.sh': '#!/bin/sh\ntouch checked\n' })
const frames: DshInstallProgress[] = []
- const result = await installDsh({ source: repo, onProgress: (p) => frames.push(p) })
- expect(result, JSON.stringify(toolchain)).toEqual({ ok: false, error: 'SHELL_UNAVAILABLE', detail })
+ const result = await installDsh({ source: repo, link, onProgress: (p) => frames.push(p) })
+ const what = `${JSON.stringify(toolchain)} link=${link}`
+ expect(result, what).toEqual({ ok: false, error: 'SHELL_UNAVAILABLE', detail })
expect(frames.at(-1)).toEqual({ id: 'acme/thing', phase: 'failed', error: 'SHELL_UNAVAILABLE', detail })
expect(frames.map((f) => f.phase)).toEqual(['clone', 'failed'])
- expect(existsSync(join(dshInstallDir('acme/thing'), 'set-up'))).toBe(false)
- expect(existsSync(join(dshInstallDir('acme/thing'), 'checked'))).toBe(false)
+ expect(placed(), what).toBe(false)
+ expect(leftovers(), what).toEqual([])
+ expect(existsSync(join(repo, 'set-up'))).toBe(false)
expect(readInstalledIndex()).toEqual([])
}
})
diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.ts
index 9be8a197d..89c55319e 100644
--- a/cli/src/dsh/install.ts
+++ b/cli/src/dsh/install.ts
@@ -21,7 +21,7 @@ import { readDshManifest, viewerUse, type DshManifest } from './manifest.js'
import { PACKAGE_PATH_RE, type DshRegistryEntry } from './registry.js'
import { catalogEntry, refreshDshRegistry } from './catalog.js'
import { resolveDshCommand } from './materialize.js'
-import { dshShellAvailable, runDshCommand } from './shell.js'
+import { DSH_SHELL_UNAVAILABLE, dshShellAvailable, runDshCommand } from './shell.js'
import { lockDsh, dshBusy } from './lock.js'
import { insideGitCheckout } from '../lib/gitProject.js'
@@ -337,6 +337,18 @@ export async function runDshDoctor(installed: InstalledDsh, onLine?: (line: stri
return { ok: result.code === 0 && !result.timedOut, lines: result.lines }
}
+/**
+ * A package whose setup or doctor this computer has no shell for (dsh/shell.ts), refused in words before either runs,
+ * rather than as one that could not start (`spawn /bin/sh ENOENT`). An install is refused once fetched or linked and
+ * before it is placed: one with no catalog entry (from a link) cannot be refused before its download (dsh/service.ts),
+ * but nothing of it may stay on disk (review of #2026, 2026-10-28).
+ */
+function refuseWithoutShell(manifest: DshManifest, progress: (p: DshInstallProgress) => void): DshInstallResult | null {
+ if (!(manifest.toolchain?.setup || manifest.toolchain?.doctor) || dshShellAvailable()) return null
+ progress({ id: manifest.id, phase: 'failed', detail: DSH_SHELL_UNAVAILABLE, error: 'SHELL_UNAVAILABLE' })
+ return { ok: false, error: 'SHELL_UNAVAILABLE', detail: DSH_SHELL_UNAVAILABLE }
+}
+
export async function installDsh(opts: DshInstallOptions): Promise<DshInstallResult> {
const progress = (p: DshInstallProgress): void => opts.onProgress?.(p)
const wrongId = (actual: string): DshInstallResult => {
@@ -359,6 +371,8 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail, error: linked.error }); return linked }
manifest = linked.manifest
if (opts.expectedId && manifest.id !== opts.expectedId) return wrongId(manifest.id)
+ const refused = refuseWithoutShell(manifest, progress)
+ if (refused) return refused
unlock = lockDsh(manifest.id)
if (!unlock) return dshBusy(manifest.id)
realDir = linked.realDir
@@ -375,6 +389,9 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
rmSync(cloned.tmpDir, { recursive: true, force: true })
return wrongId(manifest.id)
}
+ // The fetched copy goes with `staged`, in the finally below.
+ const refused = refuseWithoutShell(manifest, progress)
+ if (refused) return refused
unlock = lockDsh(manifest.id)
if (!unlock) return dshBusy(manifest.id)
commit = cloned.commit
@@ -406,12 +423,9 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
const { manifest, realDir } = resolved
const progress = (p: DshInstallProgress): void => opts.onProgress?.(p)
- // Refused before anything runs, rather than as a setup or doctor that could not start (`spawn /bin/sh ENOENT`).
- if ((manifest.toolchain?.setup || manifest.toolchain?.doctor) && !dshShellAvailable()) {
- const detail = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'
- progress({ id: manifest.id, phase: 'failed', detail, error: 'SHELL_UNAVAILABLE' })
- return { ok: false, error: 'SHELL_UNAVAILABLE', detail }
- }
+ // An update reaches here with its new copy placed; a failed update puts the previous one back (update.ts).
+ const refused = refuseWithoutShell(manifest, progress)
+ if (refused) return refused
const setupLines: string[] = []
if (manifest.toolchain?.setup) {
diff --git a/cli/src/dsh/registry.spec.ts b/cli/src/dsh/registry.spec.ts
index 84575fd85..50d96bbdf 100644
--- a/cli/src/dsh/registry.spec.ts
+++ b/cli/src/dsh/registry.spec.ts
@@ -60,6 +60,8 @@ describe('storeEntry', () => {
['a viewer package: its kind and no engine', { spec: 1, kind: 'viewer', id: 'autonomous/pane', name: 'Pane', viewer: { command: 'v.sh', url: 'http://127.0.0.1:${port}/' } }, { upstream: 'https://example.com/up', screenshots: ['https://example.com/1.png'] }],
['tagline: carried as written', { spec: 1, id: 'autonomous/sim', name: 'Sim', engine: 'claude' }, { tagline: 'Advanced physics simulation' }],
['examples: carried as written', { spec: 1, id: 'autonomous/lamp', name: 'Lamp', engine: 'claude', viewer: { use: 'autonomous/model-viewer' } }, { examples: [{ prompt: 'A desk lamp.', image: 'https://example.com/lamp.jpg', caption: 'Lamp · glTF' }] }],
+ ['a setup script: says it runs one', { spec: 1, id: 'autonomous/built', name: 'Built', engine: 'claude', toolchain: { setup: 'setup.sh' } }, {}],
+ ['a doctor alone: says it runs one', { spec: 1, kind: 'viewer', id: 'autonomous/probe', name: 'Probe', toolchain: { doctor: 'doctor.sh' }, viewer: { command: 'v.sh', url: 'http://127.0.0.1:${port}/' } }, {}],
]
for (const [what, manifest, facts] of cases) {
it(`${what}, the same from the build`, () => {
@@ -70,7 +72,11 @@ describe('storeEntry', () => {
}
it('says exactly what each case ships', () => {
- const [bare, checked, cad, pane, sim, lamp] = cases.map(([, manifest, facts]) => storeEntry('p', manifest, facts))
+ const [bare, checked, cad, pane, sim, lamp, built, probe] = cases.map(([, manifest, facts]) => storeEntry('p', manifest, facts))
+ // Windows cannot run them yet: the CLI refuses such a harness from its entry, before downloading it.
+ expect(built.runsScripts).toBe(true)
+ expect(probe.runsScripts).toBe(true)
+ for (const entry of [checked, cad, pane, sim, lamp]) expect(entry).not.toHaveProperty('runsScripts')
expect(sim.tagline).toBe('Advanced physics simulation')
expect(lamp.examples).toEqual([{ prompt: 'A desk lamp.', image: 'https://example.com/lamp.jpg', caption: 'Lamp · glTF' }])
expect(bare).toEqual({ id: 'autonomous/bare', name: 'Bare', repo: HARNESS_MONOREPO, ref: 'main', path: 'p', engine: 'claude', engines: dshSupportedEngines({ engine: 'claude' }), tier: 0, verified: true })
diff --git a/cli/src/dsh/registry.ts b/cli/src/dsh/registry.ts
index d6feaffbf..29ef54a66 100644
--- a/cli/src/dsh/registry.ts
+++ b/cli/src/dsh/registry.ts
@@ -64,6 +64,12 @@ export const DshRegistryEntrySchema = z.strictObject({
tier: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),
/** Shared viewer dependency, so the Store can show reverse dependencies before installation. */
viewerUse: z.string().regex(DSH_ID_RE).optional(),
+ /**
+ * The package runs a setup or doctor script, which a computer with no shell for them (Windows, dsh/shell.ts
+ * `dshShellAvailable`) cannot: the CLI refuses it from this entry, before downloading anything. On 2026-10-28 a
+ * Windows install was refused only once downloaded and placed, and its files stayed on disk.
+ */
+ runsScripts: z.literal(true).optional(),
verified: z.boolean().optional(),
/** The store's product page: where the thing lives, whose it is, what it is licensed under. */
homepage: z.string().url().max(2048).optional(),
@@ -120,6 +126,8 @@ export function storeEntry(path: string, manifest: Record<string, unknown>, fact
if (manifest.engine !== undefined) entry.engines = dshSupportedEngines(manifest as DshManifest)
const viewer = manifest.viewer as { use?: unknown } | undefined
if (typeof viewer?.use === 'string') entry.viewerUse = viewer.use
+ const toolchain = manifest.toolchain as { setup?: unknown; doctor?: unknown } | undefined
+ if (toolchain?.setup || toolchain?.doctor) entry.runsScripts = true
entry.tier = manifest.viewer ? 2 : manifest.verdict ? 1 : 0
entry.verified = true
return entry
diff --git a/cli/src/dsh/service.spec.ts b/cli/src/dsh/service.spec.ts
index 7195e24a8..ae2595afe 100644
--- a/cli/src/dsh/service.spec.ts
+++ b/cli/src/dsh/service.spec.ts
@@ -52,6 +52,39 @@ describe('daemon package mutations', () => {
expect(installDsh).not.toHaveBeenCalled()
})
+ describe('on a computer with no shell for a package\'s scripts (Windows)', () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ beforeEach(() => { Object.defineProperty(process, 'platform', { ...platform, value: 'win32' }) })
+ afterEach(() => { Object.defineProperty(process, 'platform', platform) })
+ const detail = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'
+
+ it('refuses from the catalog entry, before downloading anything, a package or its viewer that runs one', async () => {
+ // 2026-10-28 review of #2026: refused only after the download was placed, its files stayed on disk.
+ catalog.entries = [
+ { id: 'acme/thing', name: 'Thing', engine: 'claude', repo: 'https://example.com/thing', runsScripts: true },
+ { id: 'acme/drawing', name: 'Drawing', engine: 'claude', repo: 'https://example.com/drawing', viewerUse: 'acme/viewer' },
+ { id: 'acme/viewer', kind: 'viewer', name: 'Viewer', repo: 'https://example.com/viewer', runsScripts: true },
+ ]
+ for (const id of ['acme/thing', 'acme/drawing', 'acme/viewer']) {
+ expect(await mutateDsh({ id }, () => {}), id).toEqual({ ok: false, error: 'SHELL_UNAVAILABLE', detail })
+ }
+ // The download is installDsh's: it never started.
+ expect(installDsh).not.toHaveBeenCalled()
+ })
+
+ it('installs a package with no scripts, and leaves a link install to its check after the download', async () => {
+ catalog.entries = [{ id: 'acme/plain', name: 'Plain', engine: 'claude', repo: 'https://example.com/plain' }]
+ expect(await mutateDsh({ id: 'acme/plain' }, () => {})).toMatchObject({ ok: true })
+ expect(await mutateDsh({ url: 'https://example.com/unlisted' }, () => {})).toMatchObject({ ok: true })
+ expect(installDsh).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ it('a package that runs scripts installs where a shell runs them', async () => {
+ catalog.entries = [{ id: 'acme/thing', name: 'Thing', engine: 'claude', repo: 'https://example.com/thing', runsScripts: true }]
+ expect(await mutateDsh({ id: 'acme/thing' }, () => {})).toMatchObject({ ok: true })
+ })
+
it('throttles output, immediately sends doctor lines, and discards lines after terminal phases', async () => {
vi.useFakeTimers()
const progress = vi.fn()
diff --git a/cli/src/dsh/service.ts b/cli/src/dsh/service.ts
index d6b581cc4..57c0346a3 100644
--- a/cli/src/dsh/service.ts
+++ b/cli/src/dsh/service.ts
@@ -2,10 +2,17 @@
import { installDsh, resolveInstallSource } from './install.js'
import { updateDsh } from './update.js'
import { catalogEntry, refreshDshRegistry } from './catalog.js'
+import { DSH_SHELL_UNAVAILABLE, dshShellAvailable } from './shell.js'
export const mutateDsh = async ({ id, url, ref, update }: { id?: string; url?: string; ref?: string; update?: boolean }, progress: (p: import('./install.js').DshInstallProgress) => void): Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }> => {
const catalog = new Map((await refreshDshRegistry(update || (!!id && !catalogEntry(id)))).map(entry => [entry.id, entry]))
if (!update && id && !catalog.has(id)) return { ok: false, error: 'INVALID_DSH', detail: `${id} is not in this machine's Store catalog` }
+ // From the catalog entry, before anything is downloaded: refused only after its download was placed, a Windows
+ // install left its files on disk (review of #2026, 2026-10-28). A package with no entry is checked once fetched.
+ const entry = !update && id ? catalog.get(id) : undefined
+ if (entry && !dshShellAvailable() && (entry.runsScripts || (entry.viewerUse && catalog.get(entry.viewerUse)?.runsScripts))) {
+ return { ok: false, error: 'SHELL_UNAVAILABLE', detail: DSH_SHELL_UNAVAILABLE }
+ }
const resolved = update ? { source: '' } : id ? resolveInstallSource(id) : url ? { source: url, ref } : null
if (!resolved) return { ok: false, error: 'INVALID_DSH', detail: `${id ?? url} is not a known harness` }
// NARRATE THE LINES, NOT ONLY THE PHASES. A toolchain setup is minutes of npm and uv output, and
diff --git a/cli/src/dsh/shell.ts b/cli/src/dsh/shell.ts
index 5446e7ea5..6c76f88d6 100644
--- a/cli/src/dsh/shell.ts
+++ b/cli/src/dsh/shell.ts
@@ -78,6 +78,9 @@ export function dshShellAvailable(): boolean {
return process.platform !== 'win32'
}
+/** What a person is told when a package's setup or doctor cannot run here. */
+export const DSH_SHELL_UNAVAILABLE = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'
+
/**
* The line run before a DSH's command: when the login shell's PATH has no `node`, the Node this
* daemon runs on joins the END of it. Since the product moved to a private runtime, a machine with no
diff --git a/cli/src/lib/savedSkill.ts b/cli/src/lib/savedSkill.ts
index 49f0c086c..bc5039fd0 100644
--- a/cli/src/lib/savedSkill.ts
+++ b/cli/src/lib/savedSkill.ts
@@ -3,7 +3,8 @@
* the skill itself (lib/swarmSkills.ts), so the registry, which every process loads, reads its rows without loading the
* Swarm's code: with the Swarm off (`HARNESS_SWARM`, harnessd/services.ts) a row keeps the field and nothing acts on it.
*/
-export type SwarmRole = 'lead' | 'dev' | 'review'
+/** `buddy`: a person's own agent in a project, which brainstorms with them (backend superTabs/buddies.ts). */
+export type SwarmRole = 'lead' | 'dev' | 'review' | 'buddy'
/** A Swarm project's skill set, which its owner chooses (2026-10-23): Default is the team process alone, Harness orchestration
* adds Harness practices. A session saved without one launched before modes, on the orchestration text. */
export type SwarmSkillMode = 'default' | 'orchestration'
@@ -12,7 +13,7 @@ export type SwarmSkillMode = 'default' | 'orchestration'
export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode; github?: true }
/** What a session's current Swarm membership grants it, before it has a key. */
export type SwarmSkillGrant = Omit<SwarmSkill, 'key' | 'github'>
-export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review'
+export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review' || value === 'buddy'
export const isSwarmSkillMode = (value: unknown): value is SwarmSkillMode => value === 'default' || value === 'orchestration'
export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 936143af8..f63f52757 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -1,6 +1,6 @@
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
-import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
@@ -493,3 +493,56 @@ describe('built-in Swarm skills', () => {
expect(await buildLaunchOverrides(deps, 'claude', { cwd, swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED', detail: expect.not.stringContaining('HARNESS_SWARM') })
})
})
+
+describe('the Buddy skill (Ken\'s Buddy spec, 10-28)', () => {
+ it.each([undefined, 'default', 'orchestration'] as const)('brainstorms and proposes only when asked, the same in every mode (%s)', mode => {
+ expect(parseSwarmSkill({ role: 'buddy', key: 'session', ...(mode ? { mode } : {}) })).toEqual({ role: 'buddy', key: 'session', ...(mode ? { mode } : {}) })
+ const prepared = prepareSwarmSkill(fixture(), { role: 'buddy', key: 'session', ...(mode ? { mode } : {}) })
+ const text = readFileSync(prepared.file, 'utf8')
+ expect(text.startsWith('---\nname: swarm-buddy\n')).toBe(true)
+ // Harness Instructions' brainstorming: the goal first, options with a recommendation, an agreed scope.
+ for (const step of ['Ask the goal first', 'Offer 2 or 3 options', 'Agree the scope']) expect(text).toContain(step)
+ expect(text).toContain('Only when your owner asks')
+ expect(text).toContain('harness super-tab --tab TAB propose OPERATION_ID')
+ expect(text).toContain('Never assign work, start agents, change code or open pull requests')
+ expect(text).toBe(readFileSync(prepareSwarmSkill(fixture(), { role: 'buddy', key: 'other', mode: 'default' }).file, 'utf8'))
+ })
+})
+
+describe('a Buddy\'s folder (Lead\'s ruling on the privacy review of #1992)', () => {
+ it('pre-approves only its Super Tab commands for Claude Code, denies file editing, and leaves its files read-only', () => {
+ const workspace = fixture()
+ mkdirSync(join(workspace, 'src'))
+ writeFileSync(join(workspace, 'src', 'app.ts'), 'code\n', { mode: 0o644 })
+ writeFileSync(join(workspace, 'README.md'), 'readme\n', { mode: 0o644 })
+ const prepared = prepareSwarmSkill(workspace, { role: 'buddy', key: 'session' })
+ const settings = JSON.parse(readFileSync(join(workspace, '.claude', 'settings.local.json'), 'utf8'))
+ expect(settings.permissions).toEqual({ defaultMode: 'default', allow: ['Bash(harness super-tab:*)'], deny: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] })
+ for (const file of [join(workspace, 'src', 'app.ts'), join(workspace, 'README.md'), join(workspace, '.claude', 'settings.local.json')]) {
+ expect(statSync(file).mode & 0o222, file).toBe(0)
+ }
+ // Its folders stay writable, so the worktree is removed as any other; its skill keeps its own records.
+ expect(statSync(join(workspace, 'src')).mode & 0o200).toBe(0o200)
+ expect(statSync(prepared.file).mode & 0o200).toBe(0o200)
+ // A relaunch prepares it again the same way.
+ expect(() => prepareSwarmSkill(workspace, { role: 'buddy', key: 'session' })).not.toThrow()
+ })
+
+ it('locks the folder even when the skill cannot be prepared (re-check of #1992)', () => {
+ const workspace = fixture(), outside = fixture()
+ writeFileSync(join(workspace, 'README.md'), 'readme\n', { mode: 0o644 })
+ mkdirSync(join(workspace, '.harness'))
+ symlinkSync(join(outside, 'elsewhere'), join(workspace, '.harness', '.gitignore'))
+ expect(() => prepareSwarmSkill(workspace, { role: 'buddy', key: 'session' })).toThrow()
+ expect(statSync(join(workspace, 'README.md')).mode & 0o222).toBe(0)
+ expect(JSON.parse(readFileSync(join(workspace, '.claude', 'settings.local.json'), 'utf8')).permissions.allow).toEqual(['Bash(harness super-tab:*)'])
+ })
+
+ it('leaves every other role\'s folder as it is', () => {
+ const workspace = fixture()
+ writeFileSync(join(workspace, 'README.md'), 'readme\n', { mode: 0o644 })
+ prepareSwarmSkill(workspace, { role: 'dev', key: 'session' })
+ expect(statSync(join(workspace, 'README.md')).mode & 0o200).toBe(0o200)
+ expect(existsSync(join(workspace, '.claude', 'settings.local.json'))).toBe(false)
+ })
+})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 8d8837a3a..e8b9a12ef 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -1,7 +1,7 @@
/** Built into the CLI so contributed machines need no separately installed plugin. */
import { ignoreHarnessRuntime } from './harnessRuntimeIgnore.js'
import { createHash, randomUUID } from 'node:crypto'
-import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
import { join, relative, sep } from 'node:path'
import { isSwarmRole, isSwarmSkillMode, parseSwarmSkill, type SwarmRole, type SwarmSkill, type SwarmSkillGrant, type SwarmSkillMode } from './savedSkill.js'
@@ -10,7 +10,7 @@ export { isSwarmRole, isSwarmSkillMode, parseSwarmSkill }
export type { SwarmRole, SwarmSkill, SwarmSkillGrant, SwarmSkillMode }
/** The owner's texts, used verbatim. */
-const orchestration: Record<SwarmRole, string> = {
+const orchestration: Record<Exclude<SwarmRole, 'buddy'>, string> = {
lead: `---
name: swarm-lead
description: Use when coordinating a Harness Swarm project as its Lead (shown as Product Manager), before discussing, specifying, splitting, routing, assigning, reviewing or closing work.
@@ -362,7 +362,7 @@ Mark your review assignment done with the verdict and revision. Print little.
`,
}
-const defaults: Record<SwarmRole, string> = {
+const defaults: Record<Exclude<SwarmRole, 'buddy'>, string> = {
lead: `---
name: swarm-lead
description: Use when coordinating a Harness Swarm project as its Lead (shown as Product Manager): taking requests, splitting work into groups, assigning, tracking and closing them.
@@ -536,11 +536,47 @@ Mark your review done with the verdict and revision.
- Install nothing system-wide on a shared machine; put the tools you need in your session folder.
`,
}
-const skills: Record<SwarmSkillMode, Record<SwarmRole, string>> = { default: defaults, orchestration }
+/** A Buddy's skill: Harness Instructions' brainstorming (ask the goal, offer options, agree scope), and the one way it reaches
+ * the PM. The same in every mode: a Buddy does no project work, so neither mode's team process applies to it. */
+const buddy = `---
+name: swarm-buddy
+description: Use when you are a person's Buddy in a Harness Swarm project, brainstorming with them in your private chat and, only when they ask, sending their proposal to the Product Manager.
+---
+# Brainstorm with your owner
+
+You are one person's Buddy for one project. You help them think a request through; the Product Manager decides and assigns the work. Project instructions (AGENTS.md, CLAUDE.md) and your owner's words outrank this skill.
+
+## Where you talk
+- Your chat with your owner, named in your start note. Read it with harness super-tab --tab TAB messages CHAT, and reply there with harness super-tab --tab TAB post CHAT 'your message' OPERATION_ID. Only your owner and you read it.
+- The project chat, for context: its id is the project's leadConversationId in status. Read it; you cannot post there.
+- Nothing else. You cannot read workgroups or other people's chats, and the Swarm refuses every other command.
+- The person whose machine runs you can see your terminal. If your owner starts on something they may not want seen there, say so once.
+
+## Brainstorm
+1. Ask the goal first: what they want and why now. One question per message, in their language.
+2. Look before you ask: read the project chat and the code in your folder, and never ask what they already answered.
+3. Offer 2 or 3 options, each with its trade-off, and say which you recommend and why.
+4. Agree the scope: what is in, what is out, and how they will know it worked. Play it back in a sentence or two and ask what is wrong or missing.
+5. Keep it short. No specs or plans they did not ask for.
+
+## Send to the PM
+- Only when your owner asks (for example "send to the PM"), never on your own, and once for each time they ask.
+- Write the goal, the scope and a priority (low, normal or high) from what you agreed. Put in only what your owner wants sent; anything private stays in your chat.
+- Send it with harness super-tab --tab TAB propose OPERATION_ID '{"conversationId":"CHAT","ownerMessageId":"MESSAGE","goal":"...","scope":"...","priority":"normal"}', where MESSAGE is the id of your owner's message asking you to send it.
+- The Swarm posts it in the project chat as one message to the PM, marked as on your owner's behalf. Tell your owner it went; the PM answers in the project chat.
+
+## Limits
+- Never assign work, start agents, change code or open pull requests. Your folder is for reading.
+- In the shell, run only harness super-tab commands: anything else waits for an approval nobody at your terminal gives. Read the code with your file tools.
+- Say "I don't know" rather than guess, and point your owner to the PM in the project chat for anything you cannot answer.
+`
+
+const skills: Record<SwarmSkillMode, Record<SwarmRole, string>> = { default: { ...defaults, buddy }, orchestration: { ...orchestration, buddy } }
/** What a session is told to use, in its mode's words: a Default agent otherwise works its usual way. */
export function swarmSkillUse(role: SwarmRole, mode: SwarmSkillMode): string {
- return mode === 'default' ? `Use the swarm-${role} skill for this session: the team process; otherwise work your usual way.`
+ // A Buddy's text is the same in every mode, and no team process applies to it.
+ return mode === 'default' && role !== 'buddy' ? `Use the swarm-${role} skill for this session: the team process; otherwise work your usual way.`
: `Use the built-in swarm-${role} skill for this session.`
}
const MODE_NAMES: Record<SwarmSkillMode, string> = { default: 'Default', orchestration: 'Harness orchestration' }
@@ -565,6 +601,8 @@ const modeOf = (role: SwarmRole, version: string) =>
export function prepareSwarmSkill(workspace: string, saved: SwarmSkill): { file: string; instructions: string } {
if (!parseSwarmSkill(saved)) throw new Error('A Swarm skill needs a role and session key')
const root = realpathSync(workspace)
+ // First, so a skill that cannot be prepared still leaves a Buddy's folder locked (re-check of #1992).
+ if (saved.role === 'buddy') lockBuddyFolder(root)
const dir = skillDirectory(root, saved, true)!
ignoreHarnessRuntime(root)
const file = join(dir, 'SKILL.md')
@@ -581,6 +619,32 @@ export function prepareSwarmSkill(workspace: string, saved: SwarmSkill): { file:
return { file, instructions: `${swarmSkillUse(saved.role, mode)} Before working, read ${JSON.stringify(file)} with your file or shell tool.` }
}
+/** What Claude Code may do in a Buddy's folder without asking (it launches in asking mode, superTabs/start.ts): its Super Tab
+ * commands, to read and post in its owner's chat. Editing is denied outright. */
+const BUDDY_CLAUDE_SETTINGS = { permissions: { defaultMode: 'default', allow: ['Bash(harness super-tab:*)'], deny: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] } }
+
+/**
+ * A Buddy never changes code (Lead's ruling, privacy review of #1992): its own worktree gets Claude Code's settings above,
+ * and every file in it is made read-only. Its folders stay writable, so the worktree is removed like any other, and the
+ * Harness runtime folder (its skill and records) is left alone. A Codex Buddy keeps full permissions, under which read-only
+ * files only slow it down: it runs only on its owner's own machine (backend commands.ts buddy.create).
+ */
+function lockBuddyFolder(root: string): void {
+ const settings = join(root, '.claude', 'settings.local.json')
+ mkdirSync(join(root, '.claude'), { recursive: true })
+ if (existsSync(settings)) chmodSync(settings, 0o600)
+ writeFileSync(settings, `${JSON.stringify(BUDDY_CLAUDE_SETTINGS, null, 2)}\n`, { mode: 0o600 })
+ const walk = (dir: string) => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (dir === root && (entry.name === '.harness' || entry.name === '.git')) continue
+ const path = join(dir, entry.name)
+ if (entry.isDirectory()) walk(path)
+ else if (entry.isFile()) chmodSync(path, lstatSync(path).mode & 0o555)
+ }
+ }
+ walk(root)
+}
+
/** Which built-in text a session's skill file holds and of which mode, how many times the file was rewritten, and the text,
* mode and rewrite its agent was last confirmed told about (the launch prompt is rewrite 0). A file from before this record
* counts as holding its own content, already told; one from before modes, as orchestration. */
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index 7b1264c1b..638874a04 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -303,3 +303,11 @@ it('reads the caller\'s open decisions, or with --answered the answered ones', (
expect(parseSuperTabArgs([...prefix, 'decisions', '--answered'], where).payload).toMatchObject({ action: 'decisions', state: 'answered' })
for (const argv of [[...prefix, 'decisions', 'extra'], [...prefix, 'decisions', '--answered', 'extra']]) expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')
})
+
+it('parses a Buddy\'s propose OPERATION_ID JSON as its proposal command, whatever type the JSON names', () => {
+ const prefix = ['--tab', 'tab', '--agent', 'buddy']
+ const proposal = { conversationId: 'chat', ownerMessageId: 'asked', goal: 'Offline sync', scope: 'Desktop only', priority: 'normal' }
+ expect(parseSuperTabArgs([...prefix, 'propose', 'op-1', JSON.stringify({ ...proposal, type: 'work.assign' })], where).payload)
+ .toMatchObject({ action: 'command', operationId: 'op-1', command: { ...proposal, type: 'buddy.propose' } })
+ expect(() => parseSuperTabArgs([...prefix, 'propose', 'op-1'], where)).toThrow('harness super-tab')
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 798efd916..07f2e5a4c 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -10,7 +10,7 @@ import { uploadAttachments } from './attach.js'
import { keyName } from './terminal.js'
import { randomUUID } from 'node:crypto'
-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | decisions [--answered] | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | decisions [--answered] | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | propose OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
export function parseSuperTabArgs(argv: readonly string[], where: Where) {
const positional: string[] = []
let tabId = '', agentId = ''
@@ -49,6 +49,9 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {
command: { type: 'message.send', conversationId: first, text: second, replyTo, recipientIds: [], ...(mentions.length ? { mentions } : {}) } })
} else if (action === 'command' && identifier(first) && second && positional.length === 3) {
Object.assign(payload, { operationId: first, command: JSON.parse(second) })
+ } else if (action === 'propose' && identifier(first) && second && positional.length === 3) {
+ // A Buddy's proposal for its owner (backend buddies.ts): only ever that command, whatever the JSON says it is.
+ Object.assign(payload, { action: 'command', operationId: first, command: { ...JSON.parse(second), type: 'buddy.propose' } })
} else if (action === 'start' && identifier(first) && second && positional.length === 3) {
Object.assign(payload, { operationId: first, request: JSON.parse(second) })
} else if (action === 'resume' && identifier(first) && positional.length === 2) payload.startId = first
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index d59681d50..6d25b2566 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -79,6 +79,14 @@ describe('current Swarm role lookup', () => {
groups = []
expect(await swarmRoleFor(sources, 'harness')).toBeNull()
})
+ it('derives a Buddy from its owner while it is in its chat, so its skill stays the Buddy\'s', async () => {
+ const t = setup()
+ const agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' } }
+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:
+ path.includes('/hosts/') ? hostForm([{ tabId: 'tab', agent }]) : swarmReply(path, { agents: [agent],
+ conversations: [{ id: 'chat', kind: 'buddy', leadId: null, agentIds: ['agent'] }] }) } }))
+ expect(await swarmRoleFor(sourcesOf(t.core), 'harness')).toEqual({ role: 'buddy', mode: 'orchestration' })
+ })
it.each(['lead', 'member', 'assigned'] as const)('derives an old %s from current groups on its machine', async kind => {
const t = setup()
const agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }
@@ -779,6 +787,20 @@ describe('a delivery poll or claim that keeps failing', () => {
expect(claims.n).toBe(4)
})
+ // 2026-10-28: a Lead's list failed for 45 minutes and the log said only "This already exists, so nothing new was saved."
+ it('says whose delivery list keeps failing, with the backend\'s code, since when and how often', async () => {
+ const t = setup(), host = t.open()
+ failing(t, (method, path) => method === 'GET' && path.endsWith('/deliveries'))
+ await host.tick()
+ t.wait(1_000); await host.tick()
+ expect(t.log.mock.calls.slice(-2).map(call => call[0])).toEqual([
+ 'Could not read the deliveries for agent agent (session harness) in Swarm tab: This Swarm is busy. Try again in a moment. (SWARM_BUSY). '
+ + 'Failing since 1970-01-01T00:00:00.000Z, 1 try; next try in 1 s.',
+ 'Could not read the deliveries for agent agent (session harness) in Swarm tab: This Swarm is busy. Try again in a moment. (SWARM_BUSY). '
+ + 'Failing since 1970-01-01T00:00:00.000Z, 2 tries; next try in 2 s.',
+ ])
+ })
+
it('asks again for a delivery list the backend refuses only after the same growing wait', async () => {
const t = setup(), host = t.open()
const lists = failing(t, (method, path) => method === 'GET' && path.endsWith('/deliveries'))
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 26609bddf..35498be23 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -62,9 +62,11 @@ export async function swarmRoleFor(sources: SwarmSources, harnessId: string): Pr
if (led) return { role: 'lead' as const, mode: groupSkillMode(state, led) }
const member = groups.find(group => Array.isArray(group.agentIds) && group.agentIds.includes(target.id)
|| object(group.assignment).agentId === target.id && object(object(group.assignment).execution).machineId === machineId)
- return member ? { role: agent.role === 'reviewer' ? 'review' as const : 'dev' as const, mode: groupSkillMode(state, member) } : null
+ // A Buddy names its owner (backend buddies.ts); its role field stays a builder's for older readers.
+ const role = agent.buddyOf && typeof agent.buddyOf === 'object' ? 'buddy' as const : agent.role === 'reviewer' ? 'review' as const : 'dev' as const
+ return member ? { role, mode: groupSkillMode(state, member) } : null
}))
- return (['lead', 'dev', 'review'] as const).map(role => grants.find(grant => grant?.role === role)).find(Boolean) ?? null
+ return (['lead', 'dev', 'review', 'buddy'] as const).map(role => grants.find(grant => grant?.role === role)).find(Boolean) ?? null
}
interface Entry {
@@ -232,7 +234,7 @@ export class SuperTabHost {
private nextReplacementsAt = 0
private timer: ReturnType<typeof setTimeout> | null = null
/** Per agent's delivery list and per delivery's claim, the failures in a row and when it may be asked again. */
- private readonly deliveryRetries = new Map<string, { failures: number; retryAt: number; list?: string }>()
+ private readonly deliveryRetries = new Map<string, { failures: number; retryAt: number; since: number; list?: string }>()
private native: NativeRecorder | null = null
private machines: ContributedMachines | null = null
private readonly machineDeps: Partial<MachineDeps>
@@ -595,10 +597,11 @@ export class SuperTabHost {
const retry = this.deliveryRetries.get(key)
return !!retry && this.now() < retry.retryAt
}
- private retryLater(key: string, list?: string): void {
- const retry = this.deliveryRetries.get(key) ?? { failures: 0, retryAt: 0, ...(list ? { list } : {}) }
+ private retryLater(key: string, list?: string) {
+ const retry = this.deliveryRetries.get(key) ?? { failures: 0, retryAt: 0, since: this.now(), ...(list ? { list } : {}) }
retry.retryAt = this.now() + Math.min(DELIVERY_RETRY_MAX_MS, DELIVERY_RETRY_MS * 2 ** retry.failures++)
this.deliveryRetries.set(key, retry)
+ return retry
}
private async poll(): Promise<void> {
const data = (await this.sources.feed.refresh()).roster
@@ -723,9 +726,16 @@ export class SuperTabHost {
}
read.busy = deliveries.some(item => !this.settled(object(item)))
} catch (error) {
- if (!listRead) this.retryLater(listKey)
// Authority checks and network failures both withhold input. A later fresh read may grant it again.
- this.log(error instanceof Error ? error.message : String(error))
+ const message = error instanceof Error ? error.message : String(error)
+ if (listRead) this.log(message)
+ else {
+ // 2026-10-28: a Lead's list failed for 45 minutes while this log said only the backend's words, with no agent.
+ const retry = this.retryLater(listKey), code = error instanceof SuperTabHostError ? ` (${error.code})` : ''
+ this.log(`Could not read the deliveries for agent ${target.agent.id} (session ${target.agent.harnessId.slice(0, 8)}) in Swarm ${target.tabId}: `
+ + `${message}${code}. Failing since ${new Date(retry.since).toISOString()}, ${retry.failures} ${retry.failures === 1 ? 'try' : 'tries'}; `
+ + `next try in ${Math.round((retry.retryAt - this.now()) / 1_000)} s.`)
+ }
}
}
if (this.stopped) return
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index aeb80d406..b132adefc 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -231,6 +231,12 @@ describe('contributed machine executor', () => {
f.machine.stop(); f.advance(); await f.machine.tick()
expect(f.open).toHaveBeenCalledOnce()
})
+ it('launches a Buddy\'s start, which the backend lists apart so that a host from before Buddies never does', async () => {
+ const f = fixture()
+ Object.assign(f.pool, { starts: [], buddyStarts: [{ id: 'buddy-start', dispatched: false }] })
+ await f.machine.tick()
+ expect((f.start.mock.calls as unknown[][]).map(call => call[0])).toEqual([{ tabId: 'tab', startId: 'buddy-start', hostDispatch: true }])
+ })
it('probes common tools plus pending-start requirements and publishes failures without calling them missing', async () => {
const f = fixture()
Object.assign(f.pool.starts[0]!, { request: { requirements: { tools: ['docker'] } } })
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index f142973e5..ebf9a14b3 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -132,6 +132,10 @@ const CLEANING_WAIT = 'Waiting for this machine to finish cleaning up this Swarm
/** Separate from chat delivery: slow resource readers and agent launches never
* hold up a delivery lease. Only a tab's explicit owner grant wakes this queue. */
+/** A pool's starts this host launches: its agents', and its Buddies', which the backend lists apart so that a host from before
+ * Buddies never launches one as a Builder (backend read/hostRows.ts). */
+const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts)]
+
export class ContributedMachines {
private stopped = false
private running: Promise<void> | null = null
@@ -302,7 +306,7 @@ export class ContributedMachines {
const where = { dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId }
const pools = list((await this.sources.feed.current(POOLS_FRESH_MS)).pools).filter(row => identifier(row.tabId) && object(row.machine).machineId === this.machineId && identifier(object(row.machine).generation))
if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); return }
- const pendingIds = new Set(pools.flatMap(row => list(row.starts).map(start => start.id)))
+ const pendingIds = new Set(pools.flatMap(row => startsOf(row).map(start => start.id)))
for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)
for (const id of this.refusedSince.keys()) if (!pendingIds.has(id)) this.refusedSince.delete(id)
for (const id of this.preparing) if (!pendingIds.has(id)) this.preparing.delete(id)
@@ -331,7 +335,7 @@ export class ContributedMachines {
if (await this.core.agents.stopped?.(id) || (!this.core.agents.byAgent(id) && await this.core.agents.gone?.(id))) stopped.push(id)
}
const running = ids.filter(id => !!this.core.agents.byAgent(id) && !stopped.includes(id))
- const pending = list(row.starts)
+ const pending = startsOf(row)
const preparing = began >= this.preparingRefusedUntil ? pending.flatMap(start => this.preparing.has(String(start.id)) ? [String(start.id)] : []) : []
const tools = [...new Set([...COMMON_TOOLS, ...pending.flatMap(start => {
const wanted = object(object(start.request).requirements).tools
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index eaefb1fcd..6ba7b0192 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -220,6 +220,13 @@ describe('routeTask', () => {
expect(await models('other')).toContain('sonnet')
expect(await models('lead')).not.toContain('sonnet')
})
+ it('never offers a Buddy: it brainstorms with its owner and is never assigned work', async () => {
+ const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' ? { ...a, buddyOf: { personId: 'peer', generation: 'g' } } : a)
+ const s = scoped({ tab: t })
+ await routeTask(input, s, where as never, opener(), () => 'op')
+ const titles = (recorded(s).command.decision.candidates as Array<{ title: string }>).map(c => c.title)
+ expect(titles.some(c => c.startsWith('Multiply'))).toBe(false)
+ })
it('offers a Reviewer only for a review group, and starts a new one as a Reviewer', async () => {
const offered = async (reviewer: boolean, reviewGroup: boolean) => {
const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' && reviewer ? { ...a, role: 'reviewer' } : a)
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index cd4a1e64b..d68db2b17 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -193,7 +193,9 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const rules = (list(state.rules).filter(r => r.rule && typeof r.text === 'string' && (r.projectId === undefined || r.projectId === projectId)) as unknown as SwarmRule[])
.map(r => r.rule.kind !== 'machines' ? r : { ...r, rule: { ...r.rule,
machineIds: [...r.rule.machineIds, ...[...macOf].filter(([, mac]) => r.rule.kind === 'machines' && r.rule.machineIds.includes(mac)).map(([team]) => team)] } })
- const members = agents.filter(a => !busy.has(String(a.id)) && (a.role === 'reviewer') === review && ENGINES.includes(String(object(a.configuration).engine))).map(a => withLaunchEffort(a, list(state.starts)))
+ // A Buddy is a person's own, and is never assigned work (the backend refuses it too, backend buddies.ts).
+ const members = agents.filter(a => !busy.has(String(a.id)) && !a.buddyOf && (a.role === 'reviewer') === review
+ && ENGINES.includes(String(object(a.configuration).engine))).map(a => withLaunchEffort(a, list(state.starts)))
// A new agent starts only on a machine in the Swarm's Machines list (the backend refuses any other): a contributed machine, or
// one an agent of the Swarm runs on. The Lead runs here, so its own machine is always listed. Of the account's machines
// only those count; the rest were never prepared with the project and would only be excluded for a missing folder
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index c20b98025..25d973a46 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -46,6 +46,8 @@ const HELP = {
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. On Custom skills, add "roleId" to the start request to start the agent in that role of its kind (a builder or reviewer role from status); without it the agent takes the first role of its kind. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',
release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
+ // Buddies (backend superTabs/buddies.ts): a person adds and removes their own; the Buddy proposes only when they ask.
+ buddies: 'Buddies, once the Swarm owner turns them on (tab.buddies): each person may add their own Buddy per project (buddy.create with projectId, machineId of a Swarm machine, engine claude or codex) and remove it (buddy.remove with projectId). It brainstorms with them in a chat only they read. propose OPERATION_ID JSON: a Buddy only, when its owner asks: {"conversationId":"its chat","ownerMessageId":"their message asking","goal":"...","scope":"...","priority":"low|normal|high"}. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',
// A person's own command, for the machines they added; an agent's terminal is refused (command.ts), so no agent raises its
// own machine's room (Lead, 2026-10-28).
setAgents: 'set-agents MACHINE_ID COUNT: for a machine\'s owner, from their own terminal, not an agent\'s: how many Swarm agents may run on that machine at once. Each agent still needs free memory when it starts. A machine may offer one agent for every 2 GB of its memory, and at least 4; a larger number is refused.',
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index b50ba58cb..ba45239d8 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -244,6 +244,30 @@ it.each(['claude', 'codex'])('starts a %s Reviewer with the built-in swarm-revie
expect(payload.prompt).not.toContain('swarm-dev')
})
+it.each(['claude', 'codex'])('starts a %s Buddy with the built-in swarm-buddy skill, talking in its owner\'s chat and waiting for no assignment', async engine => {
+ const f = fixture()
+ f.start.request = { ...f.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' } } as typeof f.start.request
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-prompt', request: f.start.request }, f.scoped, where, f.open)
+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ expect(payload.swarmRole).toBe('buddy')
+ expect(payload.prompt).toContain('Use the built-in swarm-buddy skill for this session.')
+ expect(payload.prompt).toContain(`harness super-tab --tab tab messages ${f.start.request.conversationId}`)
+ expect(payload.prompt).not.toContain('assign')
+ expect(payload.prompt).not.toContain('swarm-dev')
+})
+
+it('starts a Claude Buddy in asking mode, never with full permissions, and no Buddy with the GitHub App\'s token', async () => {
+ for (const [engine, mode, bypass] of [['claude', 'ask', false], ['codex', 'full', true]] as const) {
+ const f = fixture()
+ f.start.request = { ...f.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' } } as typeof f.start.request
+ await startAgent({ action: 'start', tabId: 'tab', operationId: `buddy-${engine}`, request: f.start.request, hostDispatch: true, github: { requester: 'peer' } } as never,
+ f.scoped, where, f.open)
+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ expect([engine, payload.permissionMode, payload.bypassPermission, payload.swarmGitHub]).toEqual([engine, mode, bypass, undefined])
+ expect(payload.prompt).not.toContain('GitHub')
+ }
+})
+
describe('the skills of the project the agent joins', () => {
const projects = (skillMode?: string) => ({ conversations: [{ id: 'other', projectId: 'p1' }, { id: 'group', projectId: 'p2' }],
projects: [{ id: 'p1', skillMode: 'default' }, { id: 'p2', ...(skillMode ? { skillMode } : {}) }] })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index f8cff6905..9322aaf1b 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -33,6 +33,10 @@ function requireSuccess(reply: Json): Json {
{ code: typeof reply.error === 'string' ? reply.error : null })
return object(reply.value)
}
+/** A Buddy's start note: its owner's chat, where it talks, and nothing to wait for. */
+function buddyPrompt(tabId: string, chat: string, mode: SwarmSkillMode | null): string {
+ return `You are a person's Buddy in a shared Super Tab. ${mode ? `${swarmSkillUse('buddy', mode)} ` : ''}Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Your chat with your owner is conversation ${chat}: read it with harness super-tab --tab ${tabId} messages ${chat}, and reply there with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID. Then greet your owner there and ask what they have in mind. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`
+}
export async function inspectCapacity(target: Daemon, request: Json) {
const wanted = object(request.requirements)
const requirements: Requirements = {
@@ -326,19 +330,24 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
// Engines without a full mode retain their existing approving launch flags.
// The backend starts a Reviewer only on Claude Code or Codex, the engines with built-in Swarm skills.
const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'
+ // A Buddy's start names its owner (backend buddies.ts): it brainstorms in their chat and is never assigned work.
+ const buddy = !!request.buddyOf && typeof request.buddyOf === 'object'
// A contributed machine's host cannot read the tab as a Lead does: it asked the backend whose work this is when it
// readied the start, and prepared it with the app's token if it is another person's (superTabs/projectFolder.ts).
// Its Swarm read was refused with a 400 at every start until 2026-10-28, and its agents ran Harness orchestration
// whatever their project's skills: the start read names them, and a backend from before that keeps orchestration.
- const role = reviewer ? 'review' : 'dev', hosted = input.hostDispatch === true ? object(input.github) : null
+ const role = buddy ? 'buddy' : reviewer ? 'review' : 'dev', hosted = input.hostDispatch === true ? object(input.github) : null
const facts = skilled && !hosted ? await projectFacts(scoped, request.conversationId, start.machineOwnerId) : null
const mode = !skilled ? null : isSwarmSkillMode(start.skillMode) ? start.skillMode : facts?.mode ?? 'orchestration'
- const github = hosted ? (typeof hosted.requester === 'string' && hosted.requester ? { requester: hosted.requester } : null) : facts?.github ?? null
- const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,
- ...(permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
+ // A Buddy never writes code (Lead's ruling, privacy review of #1992): never the GitHub App's token, and a Claude Buddy
+ // asks before anything but its Super Tab commands, which its folder's settings pre-approve (lib/swarmSkills.ts).
+ const github = buddy ? null : hosted ? (typeof hosted.requester === 'string' && hosted.requester ? { requester: hosted.requester } : null) : facts?.github ?? null
+ const asks = buddy && request.engine === 'claude'
+ const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: !asks,
+ ...(asks ? { permissionMode: 'ask' } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
...(github ? { swarmGitHub: true } : {}),
- prompt: `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer
+ prompt: buddy ? buddyPrompt(String(input.tabId), String(request.conversationId), mode) : `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer
? `Do not review yet. You review work in conversation ${request.conversationId} when it is ready for review.`
: `Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}.`} Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.${github ? ` ${githubPromptLine(github.requester)}` : ''}`,
...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`,
diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dart
new file mode 100644
index 000000000..964dc96e2
--- /dev/null
+++ b/desktop/lib/super_tabs/buddies.dart
@@ -0,0 +1,418 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_select_field.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'identity.dart';
+import 'model.dart';
+
+/// The engines a Buddy runs on (spec: Buddies, 10-28).
+const kBuddyEngines = {'claude': 'Claude', 'codex': 'Codex'};
+
+/// An engine as people read it: "Claude", "Codex".
+String buddyEngineName(String engine) =>
+ kBuddyEngines[engine] ??
+ (engine.isEmpty ? 'Agent' : engine[0].toUpperCase() + engine.substring(1));
+
+/// The projects where the signed-in person may add a Buddy: those where they
+/// have none running.
+List<SuperTabProject> buddyProjects(SuperTabController c) => [
+ for (final project in c.snapshot?.projects ?? const <SuperTabProject>[])
+ if (c.buddy(project.id) == null) project,
+];
+
+/// A machine a Buddy may be added on, as the add dialog lists it.
+typedef BuddyMachine = ({String id, String name});
+
+/// The reader's own machines in the Swarm: a Buddy runs only there, like a
+/// Lead, whatever its engine (Ken, 10-28). Not a machine the reader may use
+/// but someone else owns, and not a Harness Team account. The backend
+/// refuses any other.
+List<BuddyMachine> buddyMachines(SuperTabController c) => [
+ for (final m in c.snapshot?.machines ?? const <Map<String, dynamic>>[])
+ if (m['hostMachineId'] == null &&
+ m['contributorId'] == c.accountId &&
+ m['machineId'] is String)
+ (
+ id: m['machineId'] as String,
+ name: superTabMachineName(m['name'] as String? ?? ''),
+ ),
+];
+
+/// A person by the name the Swarm shows: their address before the @.
+String buddyPersonName(SuperTabController c, String personId) {
+ final email = c.snapshot?.people
+ .where((p) => p.id == personId)
+ .firstOrNull
+ ?.email;
+ return email == null || email.isEmpty
+ ? 'its owner'
+ : superTabPersonName(email);
+}
+
+/// The machine [machineId]'s name as the dialog and the chat show it.
+String buddyMachineName(SuperTabController c, String machineId) {
+ final row = c.snapshot?.pool(machineId);
+ final name = row?['name'];
+ return name is String && name.isNotEmpty
+ ? superTabMachineName(name)
+ : 'another machine';
+}
+
+/// Add a Buddy: project, one of the reader's own machines, and engine.
+Future<void> showAddBuddy(
+ BuildContext context,
+ SuperTabController c, {
+ String? projectId,
+}) => showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: _AddBuddyDialog(controller: c, projectId: projectId),
+ ),
+);
+
+class _AddBuddyDialog extends StatefulWidget {
+ const _AddBuddyDialog({required this.controller, this.projectId});
+ final SuperTabController controller;
+ final String? projectId;
+
+ @override
+ State<_AddBuddyDialog> createState() => _AddBuddyDialogState();
+}
+
+class _AddBuddyDialogState extends State<_AddBuddyDialog> {
+ SuperTabController get c => widget.controller;
+
+ /// The fields' labels share one column.
+ static const _labelWidth = 72.0;
+ String? _project, _machine;
+ String _engine = 'claude';
+ bool _busy = false;
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ final projects = buddyProjects(c);
+ _project =
+ projects.where((p) => p.id == widget.projectId).firstOrNull?.id ??
+ projects.where((p) => p.id == c.currentProjectId).firstOrNull?.id ??
+ projects.firstOrNull?.id;
+ _machine = buddyMachines(c).firstOrNull?.id;
+ }
+
+ Future<void> _submit() async {
+ final project = _project, machine = _machine;
+ if (_busy || project == null || machine == null) return;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final added = await c.addBuddy(
+ projectId: project,
+ machineId: machine,
+ engine: _engine,
+ );
+ if (!mounted) return;
+ if (added) {
+ Navigator.pop(context);
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error = c.operationError ?? 'Could not add the Buddy. Try again.';
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final projects = buddyProjects(c);
+ final machines = buddyMachines(c);
+ final projectName =
+ projects.where((p) => p.id == _project).firstOrNull?.name ?? '';
+ Widget label(String text) => SizedBox(
+ width: _labelWidth,
+ child: Text(
+ text,
+ style: DesktopChrome.control(color: DesktopChrome.muted),
+ ),
+ );
+ return AlertDialog(
+ title: const Text('Add a Buddy'),
+ content: SizedBox(
+ width: 440,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'A private agent to think things through with. It runs on '
+ 'your own machine, reads #$projectName and your chat with '
+ 'it, and posts to the PM only when you ask.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 16),
+ Row(
+ children: [
+ label('Project'),
+ Expanded(
+ child: AppSelectField<String>(
+ key: const ValueKey('super-buddy-project'),
+ value: _project ?? '',
+ semanticLabel: 'Project',
+ textStyle: DesktopChrome.control(),
+ options: [
+ for (final p in projects)
+ SelectOption(value: p.id, label: p.name),
+ ],
+ onChanged: (value) {
+ if (!_busy) setState(() => _project = value);
+ },
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ Row(
+ children: [
+ label('Machine'),
+ Expanded(
+ child: machines.isEmpty
+ ? Text(
+ 'A Buddy runs on one of your own machines. Add '
+ 'one of yours to this Swarm first.',
+ style: DesktopChrome.metadata(),
+ )
+ : AppSelectField<String>(
+ key: const ValueKey('super-buddy-machine'),
+ value: _machine ?? '',
+ semanticLabel: 'Machine',
+ textStyle: DesktopChrome.control(),
+ options: [
+ for (final m in machines)
+ SelectOption(value: m.id, label: m.name),
+ ],
+ onChanged: (value) {
+ if (!_busy) setState(() => _machine = value);
+ },
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ Row(
+ children: [
+ label('Agent'),
+ Expanded(
+ child: RadioGroup<String>(
+ groupValue: _engine,
+ onChanged: (value) {
+ if (!_busy && value != null) {
+ setState(() => _engine = value);
+ }
+ },
+ child: Row(
+ children: [
+ for (final MapEntry(:key, :value)
+ in kBuddyEngines.entries)
+ Flexible(
+ child: RadioListTile<String>(
+ value: key,
+ enabled: !_busy,
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ title: Text(value),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(error, style: DesktopChrome.control()),
+ ],
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: _busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: _busy || _project == null || _machine == null
+ ? null
+ : () => unawaited(_submit()),
+ child: Text(_busy ? 'Adding…' : 'Add Buddy'),
+ ),
+ ],
+ );
+ }
+}
+
+/// Asks before removing the reader's Buddy in [projectId]; its chat stays.
+Future<void> confirmRemoveBuddy(
+ BuildContext context,
+ SuperTabController c,
+ String projectId,
+) async {
+ final remove = await showAppDialog<bool>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ projectId: projectId,
+ child: AlertDialog(
+ title: const Text('Remove Buddy?'),
+ content: Text(
+ 'Its session stops. Your chat stays, and adding a Buddy here again '
+ 'picks it up.',
+ style: DesktopChrome.text(),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Remove'),
+ ),
+ ],
+ ),
+ ),
+ );
+ if (remove == true) await c.removeBuddy(projectId);
+}
+
+/// Under a Buddy chat's header: what it runs on and who else can see its
+/// terminal, and, while it is down, a way to start it again. Before its
+/// agent is there, how its start is going (backend: the start carries the
+/// add's progress and failure).
+class SuperTabBuddyBar extends StatelessWidget {
+ const SuperTabBuddyBar({
+ super.key,
+ required this.controller,
+ required this.chat,
+ });
+ final SuperTabController controller;
+ final SuperTabConversation chat;
+
+ EdgeInsets get _padding => const EdgeInsets.fromLTRB(
+ grid.AppDesktop.panelPadding,
+ grid.AppDesktop.controlGap,
+ grid.AppDesktop.panelPadding,
+ grid.AppDesktop.menuInset,
+ );
+
+ /// A start under way, or one that failed with Start again; nothing once
+ /// there is no start (a removed Buddy: Add a Buddy brings it back).
+ Widget _starting(SuperTabController c) {
+ final start = c.buddyStart(chat.projectId);
+ if (start == null) return const SizedBox.shrink();
+ final request = superTabMap(start['request']);
+ final engine = request['engine'] as String? ?? '';
+ final machineId = request['machineId'] as String? ?? '';
+ final error = start['error'];
+ if (error is! String && start['harnessId'] != null) {
+ return const SizedBox.shrink();
+ }
+ final busy = !c.canWrite || c.saving || c.hasPendingAction;
+ return Padding(
+ key: const ValueKey('super-buddy-bar'),
+ padding: _padding,
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ error is String
+ ? "Couldn't start: $error"
+ : 'Starting ${buddyEngineName(engine)} on '
+ '${buddyMachineName(c, machineId)}…',
+ style: DesktopChrome.control(),
+ ),
+ ),
+ if (error is String)
+ TextButton(
+ onPressed: busy || machineId.isEmpty
+ ? null
+ : () => unawaited(
+ c.addBuddy(
+ projectId: chat.projectId,
+ machineId: machineId,
+ engine: engine,
+ ),
+ ),
+ child: const Text('Start again'),
+ ),
+ ],
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final c = controller;
+ final agent = c.buddy(chat.projectId);
+ if (agent == null) return _starting(c);
+ final name = c.snapshot!.agentName(agent.id, fallback: agent.name);
+ final machine = buddyMachineName(c, agent.machineId);
+ final project = c.snapshot!.projects
+ .where((p) => p.id == chat.projectId)
+ .firstOrNull;
+ final where = [
+ '${buddyEngineName(agent.engine)} on $machine',
+ if (project != null) '#${project.name}',
+ agent.machineOwnerId == c.accountId
+ ? 'only you can read this chat'
+ : '${buddyPersonName(c, agent.machineOwnerId)} can see its terminal',
+ ].join(' · ');
+ final busy = !c.canWrite || c.saving || c.hasPendingAction;
+ return Padding(
+ key: const ValueKey('super-buddy-bar'),
+ padding: _padding,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(where, style: DesktopChrome.metadata()),
+ if (agent.downSince != null)
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ '$name is offline. Your chat stays.',
+ style: DesktopChrome.control(),
+ ),
+ ),
+ TextButton(
+ onPressed: busy
+ ? null
+ : () => unawaited(
+ c.addBuddy(
+ projectId: chat.projectId,
+ machineId: agent.machineId,
+ engine: agent.engine,
+ ),
+ ),
+ child: const Text('Start again'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 6c3555b13..244f3a79c 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -1127,12 +1127,88 @@ class SuperTabController extends ChangeNotifier {
SuperTabConversation? pmChat(String projectId) => snapshot?.conversations
.where(
(g) =>
+ !g.isBuddyChat &&
g.projectId == projectId &&
g.audience?.length == 1 &&
g.audience!.single == accountId,
)
.firstOrNull;
+ /// Whether the Swarm has Buddies on: each person's Buddy chats take Chat
+ /// with PM's place (spec: Buddies, 10-28).
+ bool get buddiesOn => snapshot?.buddiesEnabled == true;
+
+ /// The signed-in person's chat with their Buddy in [projectId]. It stays
+ /// after the Buddy is removed, so adding one again reopens its history.
+ SuperTabConversation? buddyChat(String projectId) => snapshot?.conversations
+ .where(
+ (g) =>
+ g.isBuddyChat &&
+ g.projectId == projectId &&
+ g.buddyOwnerId == accountId,
+ )
+ .firstOrNull;
+
+ /// The signed-in person's Buddy in [projectId]; null when they have none.
+ SuperTabAgent? buddy(String projectId) => snapshot?.agents
+ .where(
+ (a) => a.isBuddy && a.buddyOf == accountId && a.projectId == projectId,
+ )
+ .firstOrNull;
+
+ /// The newest start of the reader's Buddy in [projectId]: under way while
+ /// it has neither a harness nor an error, failed with an error.
+ Map<String, dynamic>? buddyStart(String projectId) {
+ final chat = buddyChat(projectId)?.id;
+ return snapshot?.buddyStarts.reversed.where((start) {
+ final request = superTabMap(start['request']);
+ return superTabMap(request['buddyOf'])['personId'] == accountId &&
+ (request['projectId'] == projectId ||
+ (chat != null && request['conversationId'] == chat));
+ }).firstOrNull;
+ }
+
+ /// Adds the reader's Buddy in [projectId] on [machineId] with [engine], and
+ /// opens its chat. False when refused: [operationError] says why.
+ Future<bool> addBuddy({
+ required String projectId,
+ required String machineId,
+ required String engine,
+ }) async {
+ final result = await command({
+ 'type': 'buddy.create',
+ 'projectId': projectId,
+ 'machineId': machineId,
+ 'engine': engine,
+ });
+ if (result == null) return false;
+ final id = result['conversationId'];
+ if (id is String) await select(id);
+ return true;
+ }
+
+ /// Removes the reader's Buddy in [projectId]; its chat stays.
+ Future<bool> removeBuddy(String projectId) async =>
+ await command({'type': 'buddy.remove', 'projectId': projectId}) != null;
+
+ /// Whether [group] is out of the app: with Buddies on there is no private
+ /// channel to the PM (Ken, 10-28), so no private chat but a Buddy chat is
+ /// listed or opened, the reader's old Chat with PM included.
+ bool hiddenByBuddies(SuperTabConversation group) =>
+ buddiesOn && group.audience != null && !group.isBuddyChat;
+
+ /// Where conversation [id] opens: a chat [hiddenByBuddies] opens its
+ /// project's chat, where the PM is talked to; any other opens itself.
+ String _shownFor(String id) {
+ final group = snapshot?.conversation(id);
+ if (group == null || !hiddenByBuddies(group)) return id;
+ return snapshot!.projects
+ .where((p) => p.id == group.projectId)
+ .firstOrNull
+ ?.leadConversationId ??
+ id;
+ }
+
/// How many of [group]'s messages from others came after the reader's read
/// mark: exact once the messages held reach back to the mark
/// ([_heldSinceRead]), else a lower bound, one at least, while more are read
@@ -1160,15 +1236,18 @@ class SuperTabController extends ChangeNotifier {
}
/// The unread messages in the reader's own PM chats, for the Swarm badge.
- int get pmUnread => [
- for (final project in snapshot?.projects ?? const <SuperTabProject>[])
- if (pmChat(project.id) case final chat?) unreadCount(chat),
- ].fold(0, (a, b) => a + b);
+ int get pmUnread => buddiesOn
+ ? 0
+ : [
+ for (final project in snapshot?.projects ?? const <SuperTabProject>[])
+ if (pmChat(project.id) case final chat?) unreadCount(chat),
+ ].fold(0, (a, b) => a + b);
/// Reads each PM chat whose count is still open ([_pmCountOpen]), page by
/// page, so the count is exact up to [kCountCap]; nothing once every chat's
/// count is known.
void _readUnreadPmChats() {
+ if (buddiesOn) return;
for (final project in snapshot?.projects ?? const <SuperTabProject>[]) {
final chat = pmChat(project.id);
if (chat == null || !_pmCountOpen(chat) || !_pmCounting.add(chat.id)) {
@@ -1255,6 +1334,12 @@ class SuperTabController extends ChangeNotifier {
/// while a person who left and rejoined, whom the old chat no longer admits,
/// gets a new one.
Future<bool> openPmChat(String projectId) async {
+ // With Buddies on, the reader's way to talk privately is their Buddy:
+ // there is no new Chat with PM (spec: Buddies, 10-28).
+ if (buddiesOn) {
+ final chat = buddyChat(projectId);
+ return chat != null && await select(chat.id);
+ }
if (pmChat(projectId) case final chat?) return select(chat.id);
final me = snapshot?.people.where((p) => p.id == accountId).firstOrNull;
final email = me?.email;
@@ -1291,6 +1376,7 @@ class SuperTabController extends ChangeNotifier {
// The reader moved on while this was read: it must not pull them back.
if (ask != _selectRequest) return false;
}
+ id = _shownFor(id);
if (id == selectedId && !devicesSelected) return true;
_acted();
final group = snapshot!.conversation(id)!;
@@ -1433,6 +1519,7 @@ class SuperTabController extends ChangeNotifier {
if (!allowed.contains(selectedId)) {
selectedId = next.projects.firstOrNull?.leadConversationId ?? 'lead';
}
+ selectedId = _shownFor(selectedId);
if (localAccessChanged) _saveSoon();
// A new store holds no closed groups yet, nor one a saved view drew:
// the open projects read theirs.
diff --git a/desktop/lib/super_tabs/decisions_view.dart b/desktop/lib/super_tabs/decisions_view.dart
index 5d23983d0..8d70f0832 100644
--- a/desktop/lib/super_tabs/decisions_view.dart
+++ b/desktop/lib/super_tabs/decisions_view.dart
@@ -47,11 +47,15 @@ class SuperTabDecisionList extends StatelessWidget {
final count = d.open.where((o) => o.batchId == batch).length;
// The reader's own chat with the PM is named as the sidebar names it,
// not by the reader's own name (as notifications.dart does).
+ // With Buddies on there is no Chat with PM: it opens the project's
+ // chat, and is named so.
+ final c = d.controller;
final place =
- d.controller.pmChat(decision.projectId)?.id ==
- decision.conversationId
- ? 'Chat with PM'
- : decision.conversationTitle;
+ c.pmChat(decision.projectId)?.id != decision.conversationId
+ ? decision.conversationTitle
+ : c.buddiesOn
+ ? '#${decision.projectName}'
+ : 'Chat with PM';
yield _note(
'${decision.askerName} asked $count '
'${count == 1 ? 'question' : 'questions'} · '
diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dart
index 64c9cb4bf..fc94886a3 100644
--- a/desktop/lib/super_tabs/message_receipt.dart
+++ b/desktop/lib/super_tabs/message_receipt.dart
@@ -196,7 +196,9 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
c.selected?.leadId == null &&
// Every person reads the Product Managers' conversation; a post there
// stands even before any Product Manager receives it.
- c.selected?.id != c.snapshot?.leadsConversationId) {
+ c.selected?.id != c.snapshot?.leadsConversationId &&
+ // A Buddy chat has no Lead: its Buddy takes the message.
+ c.selected?.isBuddyChat != true) {
title = 'Not sent · this chat has no Lead';
icon = AppIcons.triangleAlert;
color = Theme.of(context).colorScheme.error;
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 9f4455933..b7fdbdb7e 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -38,10 +38,15 @@ class SuperTabMessageRow extends StatefulWidget {
this.readerId = '',
this.reactorName,
this.onReact,
+ this.proposalOwner,
});
final SuperTabMessage message;
+ /// The person a Buddy's proposal speaks for, by name, from the server's tag
+ /// on it ([SuperTabMessage.proposalOwnerId]); null for any other message.
+ final String? proposalOwner;
+
/// The names of the people [message] tags.
final List<String> mentions;
final Map<int, String> references;
@@ -338,6 +343,30 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
: () => widget.onOpenReply!(context),
),
),
+ if (widget.proposalOwner case final owner?)
+ Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.menuInset,
+ ),
+ child: Container(
+ key: const ValueKey('super-proposal-label'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ ),
+ decoration: BoxDecoration(
+ border: Border.all(
+ color: DesktopChrome.rim,
+ ),
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.rowRadius,
+ ),
+ ),
+ child: Text(
+ "Proposal · on $owner's behalf",
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ),
if (message.terminalNote case final note?)
Padding(
padding: const EdgeInsets.only(bottom: 6),
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 5d79d7345..e9eabc0ce 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -63,6 +63,10 @@ class SuperTabAgent {
row['machineOwnerId'] as String? ?? _text(row, 'contributorId'),
role = row['role'] as String?,
roleId = row['roleId'] as String?,
+ buddyOf = switch (row['buddyOf']) {
+ {'personId': final String person} => person,
+ _ => null,
+ },
limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
@@ -95,6 +99,13 @@ class SuperTabAgent {
final String? role;
final String? roleId;
bool get isReviewer => role == 'reviewer';
+
+ /// A person's private agent for one project (spec: Buddies, 10-28); it
+ /// never takes work. The backend gives it no role, only its person.
+ bool get isBuddy => buddyOf != null;
+
+ /// The person whose Buddy it is; null for any other agent.
+ final String? buddyOf;
final Map<String, dynamic> configuration;
String get engine => configuration['engine'] as String? ?? '';
}
@@ -117,13 +128,18 @@ class SuperTabConversation {
// before projects belongs to the first.
projectId =
row['projectId'] as String? ?? (row['kind'] == 'leads' ? '' : 'lead'),
+ kind = row['kind'] as String?,
+ buddyOwnerId = row['buddyOwnerId'] as String?,
number = (row['number'] as num?)?.toInt(),
title = _text(row, 'title'),
leadId = row['leadId'] as String?,
agentIds = List.unmodifiable((row['agentIds'] as List).cast<String>()),
archived = row['archived'] == true,
dormant = row['dormant'] == true,
- audience = row['audience'] is Map
+ // A Buddy chat names no audience: its person alone reads it.
+ audience = row['kind'] == 'buddy' && row['buddyOwnerId'] is String
+ ? List.unmodifiable([row['buddyOwnerId'] as String])
+ : row['audience'] is Map
? List.unmodifiable([
for (final person
in superTabMap(row['audience'])['people'] as List? ??
@@ -148,6 +164,14 @@ class SuperTabConversation {
? null
: Map.unmodifiable(superTabMap(row['assignment']));
final String id, projectId, title, brief;
+
+ /// What the backend calls it apart from a workgroup: `leads` for the Product
+ /// Managers' conversation, `buddy` for a person's chat with their Buddy.
+ final String? kind;
+ bool get isBuddyChat => kind == 'buddy';
+
+ /// The person a Buddy chat belongs to; only they read it.
+ final String? buddyOwnerId;
final SuperTabTask? task;
final int? number;
String get label => number == null ? title : '#$number $title';
@@ -254,7 +278,14 @@ class SuperTabSnapshot {
localModels = SuperTabLocalModels.read(row['localModels']),
mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
- decisionsDigest = row['decisionsDigest'] as String? {
+ decisionsDigest = row['decisionsDigest'] as String?,
+ buddiesEnabled = row['buddies'] == true,
+ buddyStarts = List.unmodifiable([
+ for (final start
+ in row['starts'] is List ? row['starts'] as List : const [])
+ if (start case {'request': {'buddyOf': Map _}})
+ Map<String, dynamic>.unmodifiable(superTabMap(start)),
+ ]) {
if (row['version'] != 1) {
throw const FormatException('Update Harness to open this Swarm.');
}
@@ -278,6 +309,14 @@ class SuperTabSnapshot {
final String id, name, ownerId;
final Map<String, dynamic>? project;
final bool paused;
+
+ /// The Swarm's Buddies setting: off unless its owner turned it on, and off
+ /// from a backend before Buddies.
+ final bool buddiesEnabled;
+
+ /// The starts of Buddies, oldest first: a Buddy's add is under way while
+ /// its start has neither a harness nor an error.
+ final List<Map<String, dynamic>> buddyStarts;
final List<SuperTabPerson> people;
final List<SuperTabAgent> agents;
final List<Map<String, dynamic>> machines;
@@ -748,6 +787,11 @@ class SuperTabMessage {
SuperTabRoute? get route => SuperTabRoute.fromSource(source);
bool get routeOverride => source['kind'] == 'route-override';
+ /// The person a Buddy's proposal speaks for, from the tag the server writes
+ /// on it; null for every other message, whatever its text says.
+ String? get proposalOwnerId =>
+ source['kind'] == 'buddy-proposal' ? source['personId'] as String? : null;
+
/// A note the backend writes about a terminal: a Lead's typing, or an alert.
bool get terminalEvent =>
source['kind'] == 'terminal-input' || source['kind'] == 'terminal-alert';
diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dart
index e51dc3044..ed66adcf5 100644
--- a/desktop/lib/super_tabs/notifications.dart
+++ b/desktop/lib/super_tabs/notifications.dart
@@ -262,12 +262,14 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
Widget _row(SuperTabMention mention, {required bool waiting}) {
final time = mention.createdAt;
// The reader's own chat with the Product Manager is named as the sidebar
- // names it, not by the reader's own name.
- final place =
- widget.mentions.controller.pmChat(mention.projectId)?.id ==
- mention.conversationId
- ? kChatWithPm
- : mention.conversationTitle;
+ // names it, not by the reader's own name. With Buddies on there is none:
+ // it opens the project's chat, and is named so.
+ final c = widget.mentions.controller;
+ final place = c.pmChat(mention.projectId)?.id != mention.conversationId
+ ? mention.conversationTitle
+ : c.buddiesOn
+ ? '#${c.snapshot?.projects.where((p) => p.id == mention.projectId).firstOrNull?.name ?? mention.projectName}'
+ : kChatWithPm;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
child: Material(
diff --git a/desktop/lib/super_tabs/pm_chat_rows.dart b/desktop/lib/super_tabs/pm_chat_rows.dart
index bcffeafa8..8b4d02ddb 100644
--- a/desktop/lib/super_tabs/pm_chat_rows.dart
+++ b/desktop/lib/super_tabs/pm_chat_rows.dart
@@ -62,6 +62,8 @@ class SuperTabPmChatRow extends StatelessWidget {
this.selected = false,
this.unread = false,
this.unreadCount = 0,
+ this.tooltip,
+ this.note,
});
/// The Product Manager's agent, for its avatar; null while it has none.
@@ -74,6 +76,12 @@ class SuperTabPmChatRow extends StatelessWidget {
final int unreadCount;
final VoidCallback? onTap;
+ /// What hovering says; Chat with PM's name when not given.
+ final String? tooltip;
+
+ /// A quiet word after the name, such as a Buddy's "offline".
+ final String? note;
+
static const _column = SuperTabSectionHeading.actionWidth;
static const _dotSize = 6.0;
@@ -98,9 +106,9 @@ class SuperTabPmChatRow extends StatelessWidget {
focusColor: grid.AppSurface.hoverFill,
borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
child: Tooltip(
- message: project == null
- ? kChatWithPm
- : '$kChatWithPm · $project',
+ message:
+ tooltip ??
+ (project == null ? kChatWithPm : '$kChatWithPm · $project'),
child: Row(
children: [
SizedBox(width: SuperTabSectionHeading.indentFor(0)),
@@ -145,6 +153,10 @@ class SuperTabPmChatRow extends StatelessWidget {
),
),
],
+ if (note case final note?) ...[
+ const SizedBox(width: 8),
+ Text(note, style: DesktopChrome.metadata()),
+ ],
],
),
),
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index d83fc4f3e..59fa6d9e6 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -13,6 +13,7 @@ import '../terminal/terminal_theme_store.dart';
import '../widgets/desktop_chrome.dart';
import 'controller.dart';
import 'local_models.dart';
+import 'buddies.dart';
import 'machines.dart';
import 'model.dart';
import 'pm_chat_rows.dart';
@@ -415,6 +416,8 @@ class ProjectSidebar extends StatelessWidget {
g.projectId == project.id &&
g.id != project.leadConversationId &&
g.id != controller.pmChat(project.id)?.id &&
+ !g.isBuddyChat &&
+ !controller.hiddenByBuddies(g) &&
g.closed,
)
.toList();
@@ -522,6 +525,54 @@ class ProjectSidebar extends StatelessWidget {
);
}
+ /// The signed-in person's Buddies, one row per project where they have one
+ /// or its chat stays, the project in brackets once there are several.
+ List<Widget> _buddies(List<SuperTabProject> projects) {
+ final listed = [
+ for (final project in projects)
+ if (controller.buddyChat(project.id) case final chat?) (project, chat),
+ ];
+ return [
+ for (final (project, chat) in listed)
+ _buddy(project, chat, named: listed.length > 1),
+ ];
+ }
+
+ Widget _buddy(
+ SuperTabProject project,
+ SuperTabConversation chat, {
+ required bool named,
+ }) {
+ final snapshot = controller.snapshot!;
+ final agent = controller.buddy(project.id);
+ // A removed Buddy's chat stays; it reads as plain "Buddy" until one is
+ // added again (its title names the owner, which the reader is).
+ final name = agent == null
+ ? 'Buddy'
+ : snapshot.agentName(agent.id, fallback: agent.name);
+ return SuperTabPmChatRow(
+ key: ValueKey('super-buddy-${project.id}'),
+ agentId: agent?.id,
+ name: name,
+ project: named ? project.name : null,
+ tooltip: 'Your Buddy · ${project.name}',
+ note: switch ((agent, controller.buddyStart(project.id))) {
+ (null, {'error': String _}) => 'not started',
+ (null, {'harnessId': null}) => 'starting',
+ (null, _) => 'removed',
+ (final agent?, _) when agent.downSince != null => 'offline',
+ _ => null,
+ },
+ selected:
+ !devicesSelected &&
+ !notificationsSelected &&
+ controller.selectedId == chat.id,
+ unread: controller.unread(chat),
+ unreadCount: controller.unreadCount(chat),
+ onTap: () => onSelect(chat.id),
+ );
+ }
+
/// A project's open conversations, newest first: the most recently created
/// has the highest number, and one without a number predates numbering.
List<SuperTabConversation> _newestFirst(SuperTabProject project) {
@@ -532,6 +583,8 @@ class ProjectSidebar extends StatelessWidget {
g.projectId == project.id &&
g.id != project.leadConversationId &&
g.id != pmChat &&
+ !g.isBuddyChat &&
+ !controller.hiddenByBuddies(g) &&
!g.closed,
)
.toList();
@@ -651,7 +704,9 @@ class ProjectSidebar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final snapshot = controller.snapshot;
- final pmChats = _pmChats(snapshot?.projects ?? const []);
+ final projects = snapshot?.projects ?? const <SuperTabProject>[];
+ final buddiesOn = controller.buddiesOn;
+ final pmChats = buddiesOn ? const <Widget>[] : _pmChats(projects);
return Material(
color: DesktopChrome.surface,
child: ListView(
@@ -719,6 +774,24 @@ class ProjectSidebar extends StatelessWidget {
...pmChats,
const SizedBox(height: 16),
],
+ // Buddies take Chat with PM's place (spec: Buddies, 10-28).
+ if (buddiesOn) ...[
+ SuperTabSectionHeading(
+ 'Buddies',
+ onAdd:
+ controller.canWrite &&
+ !controller.saving &&
+ !controller.hasPendingAction &&
+ buddyProjects(controller).isNotEmpty
+ ? () => unawaited(showAddBuddy(context, controller))
+ : null,
+ addTooltip: 'Add a Buddy',
+ endInset: 0,
+ startInset: SuperTabSectionHeading.indentFor(0),
+ ),
+ ..._buddies(projects),
+ const SizedBox(height: 16),
+ ],
// Machine online/offline, unread marks and theme changes do not touch
// the controller the rest of this sidebar rebuilds on, so this group
// watches them itself — the same sources the roster merged before the
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 0e7445ea6..6be1bde5c 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -367,6 +367,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
? 'Product Manager'
: agent.isReviewer
? 'Reviewer'
+ : agent.isBuddy
+ ? 'Buddy'
: 'Engineer');
final badge =
customRole?.name ??
@@ -374,6 +376,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
? 'PM'
: agent.isReviewer
? 'Rev'
+ : agent.isBuddy
+ ? 'Buddy'
: 'Dev');
final status = info.status ?? 'Status unavailable';
final tooltip = [
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 195d4adf7..e43b5069d 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -30,6 +30,7 @@ import 'workgroup_name.dart';
import 'message_row.dart';
import 'message_receipt.dart';
import 'notifications.dart';
+import 'buddies.dart';
import 'decisions.dart';
import 'decisions_view.dart';
import 'route_row.dart';
@@ -986,6 +987,7 @@ class _SuperTabViewState extends State<SuperTabView>
.where(
(group) =>
group.archived &&
+ !c.hiddenByBuddies(group) &&
group.projectId == c.selected?.projectId &&
group.title.toLowerCase().contains(query),
)
@@ -1122,6 +1124,13 @@ class _SuperTabViewState extends State<SuperTabView>
});
widget.onCloseTerminal?.call();
_closeSidebar();
+ if (c.buddiesOn && c.buddyChat(projectId) == null) {
+ // No Buddy here yet: the shortcut offers to add one.
+ if (c.canWrite) {
+ unawaited(showAddBuddy(context, c, projectId: projectId));
+ }
+ return Future.value(false);
+ }
return c.openPmChat(projectId);
}
@@ -1394,6 +1403,27 @@ class _SuperTabViewState extends State<SuperTabView>
bool _isPmChat(SuperTabConversation group) =>
c.pmChat(group.projectId)?.id == group.id;
+ /// Whom a Buddy's proposal speaks for, by name; null for other messages.
+ String? _proposalOwner(SuperTabMessage message) =>
+ message.proposalOwnerId == null
+ ? null
+ : buddyPersonName(c, message.proposalOwnerId!);
+
+ /// The reader's own chat with their Buddy.
+ bool _isBuddyChat(SuperTabConversation group) =>
+ c.buddyChat(group.projectId)?.id == group.id;
+
+ /// The name of the reader's Buddy that [group] is the chat with, or
+ /// "your Buddy" while it has none (removed, or starting). Null when [group]
+ /// is no Buddy chat of the reader's.
+ String? _buddyName(SuperTabConversation? group) {
+ if (group == null || !_isBuddyChat(group)) return null;
+ final agent = c.buddy(group.projectId);
+ return agent == null
+ ? 'your Buddy'
+ : c.snapshot!.agentName(agent.id, fallback: agent.name);
+ }
+
/// The open conversation's name, or what the pane shows instead of one,
/// named as the sidebar names it: "# openharness", or a workgroup's
/// [SuperTabWorkgroupName].
@@ -1413,7 +1443,11 @@ class _SuperTabViewState extends State<SuperTabView>
? '# $kProductManagersChannel'
: _isPmChat(group)
? kChatWithPm
- : null;
+ : _buddyName(group) == null
+ ? null
+ : c.buddy(group.projectId) == null
+ ? 'Your Buddy'
+ : '${_buddyName(group)} · Your Buddy';
if (name == null) return SuperTabWorkgroupName(group!, style: style);
return Text(
name,
@@ -1436,6 +1470,7 @@ class _SuperTabViewState extends State<SuperTabView>
if (_isPmChat(group)) {
return 'Message ${pmChatName(snapshot, snapshot.projectFor(group.id)!)}';
}
+ if (_buddyName(group) case final buddy?) return 'Message $buddy';
return 'Message ${group.title}';
}
@@ -1694,6 +1729,15 @@ class _SuperTabViewState extends State<SuperTabView>
item('Swarm routing', () => _groupAction('routing', group)),
if (editable && project?.ownerId == c.accountId)
item('Delete Project', () => _groupAction('delete', group)),
+ ] else if (_isBuddyChat(group)) ...[
+ // A Buddy chat is the reader's own: the Buddy itself to remove.
+ // Nothing to rename or archive, and no way to a Chat with PM (Ken,
+ // 10-28).
+ if (editable && c.buddy(group.projectId) != null)
+ item(
+ 'Remove Buddy',
+ () => unawaited(confirmRemoveBuddy(context, c, group.projectId)),
+ ),
] else ...[
// A private conversation is chat only: it has no work.
if (group.audience == null)
@@ -1726,7 +1770,11 @@ class _SuperTabViewState extends State<SuperTabView>
builder: (context, menu, _) => AppIconButton(
key: const ValueKey('super-group-options'),
icon: AppIcons.ellipsisVertical,
- tooltip: isProject ? 'Project options' : 'Workgroup options',
+ tooltip: isProject
+ ? 'Project options'
+ : _isBuddyChat(group)
+ ? 'Buddy options'
+ : 'Workgroup options',
onPressed: () => menu.isOpen ? menu.close() : menu.open(),
),
);
@@ -1794,6 +1842,7 @@ class _SuperTabViewState extends State<SuperTabView>
child: SuperTabMessageRow(
message: message,
author: _shownAuthor(c, message),
+ proposalOwner: _proposalOwner(message),
person: person,
grouped: SuperTabMessageRow.groupsWith(message, messages.lastOrNull),
reply: reply,
@@ -1869,6 +1918,7 @@ class _SuperTabViewState extends State<SuperTabView>
key: ValueKey('super-message-${message.id}'),
message: message,
author: _shownAuthor(c, message),
+ proposalOwner: _proposalOwner(message),
// A person is named by their address's first part, as people say it.
mentions: [
for (final id in message.mentions)
@@ -2224,8 +2274,12 @@ class _SuperTabViewState extends State<SuperTabView>
],
),
),
- // The reader's own chat with the PM shows what the PM asked them.
- if (group != null && _isPmChat(group))
+ if (group != null && _isBuddyChat(group))
+ SuperTabBuddyBar(controller: c, chat: group),
+ // The reader's own chat with the PM shows what the PM asked them;
+ // with Buddies on, their Buddy chat does instead.
+ if (group != null &&
+ (c.buddiesOn ? _isBuddyChat(group) : _isPmChat(group)))
SuperTabDecisionsPanel(
decisions: SuperTabDecisions.of(c),
projectId: group.projectId,
@@ -2236,18 +2290,28 @@ class _SuperTabViewState extends State<SuperTabView>
: unread && c.error != null
? _firstReadFailed(c.error!)
: messages.isEmpty && outgoing.isEmpty
- ? Center(
- child: Text(
- c.accessRevoked
- ? 'Conversation unavailable.'
- : group == null
- ? 'Loading conversation…'
- : c.snapshot!.isProjectLead(group.id)
- ? 'Discuss the plan with your product manager.'
- : _isPmChat(group)
- ? 'Only you and the Product Manager read this chat.'
- : 'Start the conversation.',
- style: DesktopChrome.text(color: DesktopChrome.muted),
+ ? Padding(
+ // The pane's side padding, as the composer has: a long line
+ // wraps inside it, centered.
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.panelPadding,
+ ),
+ child: Center(
+ child: Text(
+ c.accessRevoked
+ ? 'Conversation unavailable.'
+ : group == null
+ ? 'Loading conversation…'
+ : c.snapshot!.isProjectLead(group.id)
+ ? 'Discuss the plan with your product manager.'
+ : _buddyName(group) != null
+ ? "Only you and ${_buddyName(group)} read this chat. Say what you want to build; say 'send to the PM' when it's ready."
+ : _isPmChat(group)
+ ? 'Only you and the Product Manager read this chat.'
+ : 'Start the conversation.',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
),
)
: Stack(
diff --git a/desktop/test/super_tab_buddies_shots_test.dart b/desktop/test/super_tab_buddies_shots_test.dart
new file mode 100644
index 000000000..ae0125f43
--- /dev/null
+++ b/desktop/test/super_tab_buddies_shots_test.dart
@@ -0,0 +1,141 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/buddy_fixture.dart';
+import 'support/capture.dart';
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the Buddy PR's pictures there.
+final shots = Platform.environment['SUPER_TAB_BUDDY_SHOTS'];
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ ConversationServer swarm() {
+ final server = buddySwarm();
+ server.state['name'] = 'openharness';
+ server.state['projects'] = [
+ projectFixture('lead', 'openharness', 'lead'),
+ projectFixture('web', 'web-2', 'web-lead'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('web-lead', 'Lead'),
+ 'projectId': 'web',
+ });
+ giveBuddy(server);
+ giveBuddy(server, projectId: 'web', id: 'moss', name: 'Moss');
+ ((server.state['agents'] as List).last as Map)['downSince'] =
+ '2026-10-28T09:00:00Z';
+ server.append(
+ 'I want people to keep editing when the network drops.',
+ conversationId: 'buddy-peer-lead',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'peer',
+ 'name': '[email protected]',
+ };
+ buddyReply(
+ server,
+ 'buddy-peer-lead',
+ 'Three ways to scope it:\n1. Desktop only, last 50 messages cached (recommended)\n2. Desktop and phone\n3. Full offline workspace\nWhich fits?',
+ );
+ buddyReply(
+ server,
+ 'lead',
+ "Proposal from ken.tran's Buddy, on ken.tran's behalf\nGoal: Keep editing while offline\nScope: Desktop only, last 50 messages cached\nPriority: high",
+ source: {
+ 'kind': 'buddy-proposal',
+ 'personId': 'peer',
+ 'ownerMessageId': 'message-1',
+ },
+ );
+ server.decisions.add({
+ 'id': 'd1',
+ 'projectId': 'lead',
+ 'projectName': 'openharness',
+ 'conversationId': 'lead',
+ 'conversationTitle': 'Lead',
+ 'askerName': 'Lead',
+ 'question': 'Ship offline editing behind a flag?',
+ 'options': ['Yes', 'No'],
+ 'recommended': 0,
+ 'unblocks': 'The Desktop release',
+ 'createdAt': '2026-10-28T09:00:00Z',
+ });
+ server.state['decisionsWaiting'] = 1;
+ return server;
+ }
+
+ for (final brightness in Brightness.values) {
+ testWidgets('Buddies in ${brightness.name}', (tester) async {
+ if (shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = const Size(2400, 1400);
+ addTearDown(tester.view.reset);
+ final server = swarm();
+ final c = server.controller(account: 'peer');
+ await c.refresh();
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: RepaintBoundary(
+ key: picture,
+ child: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewProject: () {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) async {
+ await tester.pumpAndSettle();
+ await captureBoundary(
+ tester,
+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary,
+ shots,
+ 'buddy-$name-${brightness.name}',
+ );
+ }
+
+ await c.select('buddy-peer-lead');
+ await capture('chat');
+ await c.select('buddy-peer-web');
+ await capture('offline');
+ await c.select('lead');
+ await capture('proposal');
+ // Remove the web Buddy so the dialog has a project to offer.
+ (server.state['agents'] as List).removeWhere(
+ (a) => (a as Map)['id'] == 'moss',
+ );
+ await c.refresh();
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('Add a Buddy'));
+ await tester.pumpAndSettle();
+ // The dialog is a route of its own, above the captured screen.
+ await captureWindow(tester, shots, 'buddy-add-${brightness.name}');
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+}
diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dart
new file mode 100644
index 000000000..b3bbca9ea
--- /dev/null
+++ b/desktop/test/super_tab_buddies_test.dart
@@ -0,0 +1,977 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/buddy_fixture.dart';
+import 'support/pm_chat_fixture.dart';
+import 'support/super_tab_fixture.dart';
+
+/// Buddies (Ken's spec, 10-28): with the Swarm's setting on, a person's
+/// private agent per project takes Chat with PM's place in the sidebar.
+void main() {
+ List<Map<String, dynamic>> commands(ConversationServer server, String type) =>
+ [
+ for (final post in server.posts)
+ if ((post['command'] as Map)['type'] == type)
+ Map<String, dynamic>.from(post['command'] as Map),
+ ];
+
+ group('the controller', () {
+ test('Buddies are off unless the Swarm turns them on', () async {
+ final server = buddySwarm(enabled: false);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(c.buddiesOn, isFalse);
+
+ server.state['buddies'] = true;
+ await c.refresh();
+ expect(c.buddiesOn, isTrue);
+ });
+
+ test('a Buddy chat is never taken for Chat with PM, though only the reader reads both', () async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(c.buddyChat('lead')?.id, 'buddy-peer-lead');
+ expect(c.pmChat('lead'), isNull);
+ expect(c.buddy('lead')?.id, 'wren');
+ });
+
+ test("another person's Buddy is not the reader's", () async {
+ final server = buddySwarm();
+ giveBuddy(server, person: 'owner', id: 'moss', name: 'Moss');
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(c.buddy('lead'), isNull);
+ expect(c.buddyChat('lead'), isNull);
+ });
+
+ test(
+ 'adding a Buddy sends the project, machine and engine and opens its chat',
+ () async {
+ final server = buddySwarm();
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(
+ await c.addBuddy(
+ projectId: 'lead',
+ machineId: 'ken-mac',
+ engine: 'codex',
+ ),
+ isTrue,
+ );
+
+ expect(commands(server, 'buddy.create'), [
+ {
+ 'type': 'buddy.create',
+ 'projectId': 'lead',
+ 'machineId': 'ken-mac',
+ 'engine': 'codex',
+ },
+ ]);
+ expect(c.buddy('lead'), isNotNull);
+ expect(c.selectedId, 'buddy-peer-lead');
+ },
+ );
+
+ test('a refused add says why and opens nothing', () async {
+ final server = buddySwarm();
+ server.refuse = {
+ 'code': 'BUDDY_EXISTS',
+ 'message': 'You already have a Buddy in this project.',
+ };
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+ final before = c.selectedId;
+
+ expect(
+ await c.addBuddy(
+ projectId: 'lead',
+ machineId: 'ken-mac',
+ engine: 'claude',
+ ),
+ isFalse,
+ );
+ expect(c.operationError, 'You already have a Buddy in this project.');
+ expect(c.selectedId, before);
+ });
+
+ test('adding a second Buddy while one runs in the project is refused, as the backend does', () async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(
+ await c.addBuddy(
+ projectId: 'lead',
+ machineId: 'studio',
+ engine: 'claude',
+ ),
+ isFalse,
+ );
+ expect(c.operationError, 'You already have a Buddy in this project.');
+ expect(c.buddy('lead')?.id, 'wren');
+ });
+
+ test('removing a Buddy sends its project and keeps its chat', () async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(await c.removeBuddy('lead'), isTrue);
+
+ expect(commands(server, 'buddy.remove'), [
+ {'type': 'buddy.remove', 'projectId': 'lead'},
+ ]);
+ expect(c.buddy('lead'), isNull);
+ expect(c.buddyChat('lead'), isNotNull);
+ });
+
+ test('with Buddies on, the Chat with PM shortcut opens the Buddy chat and never creates a Chat with PM', () async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(await c.openCurrentPmChat(), isTrue);
+
+ expect(c.selectedId, 'buddy-peer-lead');
+ expect(commands(server, 'conversation.create'), isEmpty);
+ });
+
+ test(
+ 'with Buddies on and no Buddy, the shortcut creates nothing',
+ () async {
+ final server = buddySwarm();
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+
+ expect(await c.openCurrentPmChat(), isFalse);
+ expect(commands(server, 'conversation.create'), isEmpty);
+ },
+ );
+
+ /// Ken has a Chat with PM from before Buddies, with an unread PM reply,
+ /// and has it open; then the Swarm turns Buddies on.
+ Future<(ConversationServer, SuperTabController, String)>
+ pmChatThenBuddies() async {
+ final server = buddySwarm(enabled: false);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+ await c.openPmChat('lead');
+ final id = c.pmChat('lead')!.id;
+ await c.select('lead');
+ pmReply(server, id, 'Earlier answer from the PM');
+ await c.refresh();
+ expect(c.pmUnread, 1);
+ server.state['buddies'] = true;
+ giveBuddy(server);
+ await c.refresh();
+ return (server, c, id);
+ }
+
+ test('with Buddies on, opening the old Chat with PM by id opens the project chat instead', () async {
+ final (_, c, id) = await pmChatThenBuddies();
+
+ expect(await c.select(id), isTrue);
+
+ expect(c.selectedId, 'lead');
+ });
+
+ test(
+ 'with Buddies on, a Chat with PM left open moves to the project chat',
+ () async {
+ final server = buddySwarm(enabled: false);
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ await c.refresh();
+ await c.openPmChat('lead');
+ expect(c.selectedId, c.pmChat('lead')!.id);
+
+ server.state['buddies'] = true;
+ await c.refresh();
+
+ expect(c.selectedId, 'lead');
+ },
+ );
+
+ test(
+ 'with Buddies on, the old Chat with PM counts nothing on the Swarm tab',
+ () async {
+ final (_, c, _) = await pmChatThenBuddies();
+ expect(c.pmUnread, 0);
+ },
+ );
+ });
+
+ group('the sidebar', () {
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server, {
+ String account = 'peer',
+ Brightness brightness = Brightness.light,
+ }) async {
+ await tester.binding.setSurfaceSize(const Size(1280, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller(account: account);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ Future<void> close(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }
+
+ final pmEntry = find.byKey(const ValueKey('super-pm-chat-lead'));
+ final buddyEntry = find.byKey(const ValueKey('super-buddy-lead'));
+ final addBuddy = find.byTooltip('Add a Buddy');
+
+ testWidgets('with Buddies off, Direct messages and Chat with PM stay', (
+ tester,
+ ) async {
+ final c = await show(tester, buddySwarm(enabled: false));
+ expect(find.text('Direct messages'), findsOneWidget);
+ expect(pmEntry, findsOneWidget);
+ expect(find.text('Buddies'), findsNothing);
+ expect(addBuddy, findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'with Buddies on, a Buddies section with + replaces Chat with PM',
+ (tester) async {
+ final c = await show(tester, buddySwarm());
+ expect(find.text('Buddies'), findsOneWidget);
+ expect(addBuddy, findsOneWidget);
+ expect(find.text('Direct messages'), findsNothing);
+ expect(pmEntry, findsNothing);
+ expect(buddyEntry, findsNothing);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'the reader\'s Buddy is listed by name, without its project while it is their only one',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('Wren')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('(Pilot)')),
+ findsNothing,
+ );
+
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'buddy-peer-lead');
+ // The chat is its own row, never listed among the workgroups.
+ expect(
+ find.byKey(const ValueKey('super-group-buddy-peer-lead')),
+ findsNothing,
+ );
+ await close(tester, c);
+ },
+ );
+
+ testWidgets('with two Buddies, each row names its project', (tester) async {
+ final server = buddySwarm();
+ server.state['projects'] = [
+ projectFixture('lead', 'openharness', 'lead'),
+ projectFixture('web', 'web-2', 'web-lead'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('web-lead', 'Lead'),
+ 'projectId': 'web',
+ });
+ giveBuddy(server);
+ giveBuddy(server, projectId: 'web', id: 'moss', name: 'Moss');
+ final c = await show(tester, server);
+
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('(openharness)')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-buddy-web')),
+ matching: find.text('(web-2)'),
+ ),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ });
+
+ testWidgets('a removed Buddy keeps its chat, plainly named', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ (server.state['agents'] as List).removeWhere(
+ (a) => (a as Map)['id'] == 'wren',
+ );
+ final c = await show(tester, server);
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('Buddy')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('removed')),
+ findsOneWidget,
+ );
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ expect(find.text('Your Buddy'), findsOneWidget);
+ expect(find.textContaining("peer's Buddy"), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('a Buddy whose session is down says offline', (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ ((server.state['agents'] as List).last as Map)['downSince'] =
+ '2026-10-28T09:00:00Z';
+ final c = await show(tester, server);
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('offline')),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ });
+
+ testWidgets('the shortcut with no Buddy in the project opens Add a Buddy', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ final c = await show(tester, server);
+ expect(await c.pmChatOpener!('lead'), isFalse);
+ await tester.pumpAndSettle();
+ expect(find.text('Add a Buddy'), findsWidgets);
+ expect(commands(server, 'conversation.create'), isEmpty);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ await close(tester, c);
+ });
+
+ group('Add a Buddy', () {
+ final machine = find.byKey(const ValueKey('super-buddy-machine'));
+ final submit = find.widgetWithText(FilledButton, 'Add Buddy');
+ final notice = find.byKey(const ValueKey('super-buddy-machine-notice'));
+
+ Future<void> open(WidgetTester tester) async {
+ await tester.tap(addBuddy);
+ await tester.pumpAndSettle();
+ expect(find.text('Add a Buddy'), findsWidgets);
+ }
+
+ testWidgets(
+ 'starts on the reader\'s own machine and Claude, and adds it',
+ (tester) async {
+ final server = buddySwarm();
+ final c = await show(tester, server);
+ await open(tester);
+ expect(
+ find.descendant(of: machine, matching: find.text('Kens-MacBook')),
+ findsOneWidget,
+ );
+ expect(notice, findsNothing);
+
+ await tester.tap(submit);
+ await tester.pumpAndSettle();
+
+ expect(commands(server, 'buddy.create'), [
+ {
+ 'type': 'buddy.create',
+ 'projectId': 'lead',
+ 'machineId': 'ken-mac',
+ 'engine': 'claude',
+ },
+ ]);
+ expect(find.text('Add a Buddy'), findsNothing);
+ expect(c.selectedId, 'buddy-peer-lead');
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'lists only the reader\'s own machines: not teammates\', not a Team account (Ken, 10-28)',
+ (tester) async {
+ final server = buddySwarm();
+ (server.state['machines'] as List).addAll([
+ {
+ 'machineId': 'ken-mini',
+ 'name': 'Kens-Mini.local',
+ 'contributorId': 'peer',
+ 'scope': 'swarm',
+ },
+ {
+ 'machineId': 'ken-team',
+ 'name': 'Kens-MacBook.local',
+ 'contributorId': 'peer',
+ 'scope': 'swarm',
+ 'hostMachineId': 'ken-mac',
+ },
+ ]);
+ final c = await show(tester, server);
+ await open(tester);
+ // Studio, the owner's, is in the sidebar's Machines; the menu adds
+ // no row for it.
+ final studio = find.text('Studio').evaluate().length;
+ final macbook = find.text('Kens-MacBook').evaluate().length;
+ await tester.tap(machine);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Studio').evaluate(), hasLength(studio));
+ // One row for the MacBook: its Team account is not offered apart.
+ expect(find.text('Kens-MacBook').evaluate(), hasLength(macbook + 1));
+ expect(find.text('Kens-Mini'), findsWidgets);
+ await tester.tap(find.text('Kens-Mini').last);
+ await tester.pumpAndSettle();
+ expect(notice, findsNothing);
+ await tester.tap(find.text('Codex'));
+ await tester.pumpAndSettle();
+ await tester.tap(submit);
+ await tester.pumpAndSettle();
+ expect(commands(server, 'buddy.create').single, {
+ 'type': 'buddy.create',
+ 'projectId': 'lead',
+ 'machineId': 'ken-mini',
+ 'engine': 'codex',
+ });
+ await close(tester, c);
+ },
+ );
+
+ testWidgets('with no machine of their own, it says so and cannot add', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ (server.state['machines'] as List).removeWhere(
+ (m) => (m as Map)['contributorId'] == 'peer',
+ );
+ final c = await show(tester, server);
+ await open(tester);
+
+ expect(
+ find.text(
+ 'A Buddy runs on one of your own machines. Add one of yours to this Swarm first.',
+ ),
+ findsOneWidget,
+ );
+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);
+ await close(tester, c);
+ });
+
+ testWidgets('a refusal shows in the dialog, which keeps the choices', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ server.refuse = {
+ 'code': 'MACHINE_UNAVAILABLE',
+ 'message': 'That machine is offline.',
+ };
+ final c = await show(tester, server);
+ await open(tester);
+ await tester.tap(find.text('Codex'));
+ await tester.pumpAndSettle();
+ await tester.tap(submit);
+ await tester.pumpAndSettle();
+
+ expect(
+ find.descendant(
+ of: find.byType(AlertDialog),
+ matching: find.text('That machine is offline.'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Add a Buddy'), findsWidgets);
+ expect(
+ find.descendant(of: machine, matching: find.text('Kens-MacBook')),
+ findsOneWidget,
+ );
+ await tester.tap(submit);
+ await tester.pumpAndSettle();
+ expect(commands(server, 'buddy.create').last['engine'], 'codex');
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'a project that already has the reader\'s Buddy is not offered; with none left, there is no +',
+ (tester) async {
+ final server = buddySwarm();
+ server.state['projects'] = [
+ projectFixture('lead', 'openharness', 'lead'),
+ projectFixture('web', 'web-2', 'web-lead'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('web-lead', 'Lead'),
+ 'projectId': 'web',
+ });
+ giveBuddy(server);
+ final c = await show(tester, server);
+ await open(tester);
+ // The project the dialog starts on is the one without a Buddy.
+ final project = find.byKey(const ValueKey('super-buddy-project'));
+ expect(
+ find.descendant(of: project, matching: find.text('web-2')),
+ findsOneWidget,
+ );
+ final shown = find.text('openharness').evaluate().length;
+ await tester.tap(project);
+ await tester.pumpAndSettle();
+ // Its menu adds no row for the project that has one.
+ expect(find.text('openharness').evaluate(), hasLength(shown));
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+
+ giveBuddy(server, projectId: 'web', id: 'moss', name: 'Moss');
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(addBuddy, findsNothing);
+ await close(tester, c);
+ },
+ );
+ });
+
+ group('the Buddy chat', () {
+ testWidgets('its header names the Buddy and where it runs', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Wren · Your Buddy'), findsOneWidget);
+ expect(
+ find.text(
+ 'Claude on Kens-MacBook · #Pilot · only you can read this chat',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Message Wren'), findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'on someone else\'s machine, the header says they can see its terminal',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server, machineId: 'studio', machineOwnerId: 'owner');
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text('Claude on Studio · #Pilot · owner can see its terminal'),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a Buddy that is down offers Start again on the same machine',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server, engine: 'codex');
+ ((server.state['agents'] as List).last as Map)['downSince'] =
+ '2026-10-28T09:00:00Z';
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text('Wren is offline. Your chat stays.'),
+ findsOneWidget,
+ );
+ await tester.tap(find.widgetWithText(TextButton, 'Start again'));
+ await tester.pumpAndSettle();
+ expect(commands(server, 'buddy.create').single, {
+ 'type': 'buddy.create',
+ 'projectId': 'lead',
+ 'machineId': 'ken-mac',
+ 'engine': 'codex',
+ });
+ // The new Buddy replaces the down one: one Buddy, running.
+ expect(c.operationError, isNull);
+ expect(
+ c.snapshot!.agents.where((a) => a.buddyOf == 'peer'),
+ hasLength(1),
+ );
+ expect(c.buddy('lead')!.downSince, isNull);
+ expect(find.text('Wren is offline. Your chat stays.'), findsNothing);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a message to the Buddy never reads as having no Lead: a Buddy chat has none',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ server.append('Hello Wren', conversationId: 'buddy-peer-lead');
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'peer',
+ 'name': '[email protected]',
+ };
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Hello Wren'), findsOneWidget);
+ expect(find.text('Not sent · this chat has no Lead'), findsNothing);
+ expect(find.text('Add a Lead'), findsNothing);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets('the empty Buddy chat text keeps the pane\'s side padding', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ final text = tester.getRect(find.textContaining('Only you and Wren'));
+ final composer = tester.getRect(
+ find.byKey(const ValueKey('super-message-composer-row')),
+ );
+ // The composer row spans the pane; its field is inset by the panel
+ // padding, and so is the empty text.
+ expect(
+ text.left,
+ greaterThanOrEqualTo(composer.left + grid.AppDesktop.panelPadding),
+ );
+ expect(
+ text.right,
+ lessThanOrEqualTo(composer.right - grid.AppDesktop.panelPadding),
+ );
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'an empty Buddy chat says who reads it and how to reach the PM',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text(
+ "Only you and Wren read this chat. Say what you want to build; say 'send to the PM' when it's ready.",
+ ),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'the decisions asked of the reader show above the Buddy chat',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ server.decisions.add({
+ 'id': 'd1',
+ 'projectId': 'lead',
+ 'projectName': 'Pilot',
+ 'conversationId': 'lead',
+ 'conversationTitle': 'Lead',
+ 'askerName': 'Lead',
+ 'question': 'Ship the Buddy?',
+ 'options': ['Yes', 'No'],
+ 'recommended': 0,
+ 'unblocks': 'The release',
+ 'createdAt': '2026-10-28T09:00:00Z',
+ });
+ server.state['decisionsWaiting'] = 1;
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Ship the Buddy?'), findsOneWidget);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'Remove Buddy asks first, then removes it and keeps the chat',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byTooltip('Buddy options'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Remove Buddy'));
+ await tester.pumpAndSettle();
+ expect(commands(server, 'buddy.remove'), isEmpty);
+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));
+ await tester.pumpAndSettle();
+
+ expect(commands(server, 'buddy.remove'), hasLength(1));
+ expect(c.buddyChat('lead'), isNotNull);
+ await close(tester, c);
+ },
+ );
+ });
+
+ testWidgets(
+ 'the Buddy chat lists only its person and its Buddy, and offers no Add agent',
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ final c = await show(tester, server);
+ expect(
+ find.byKey(const ValueKey('super-person-owner')),
+ findsOneWidget,
+ );
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+
+ expect(find.byKey(const ValueKey('super-person-peer')), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-person-owner')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('super-member-lead-agent')),
+ findsNothing,
+ );
+ expect(find.byTooltip('Add agent'), findsNothing);
+ await close(tester, c);
+ },
+ );
+
+ group('a Buddy being added', () {
+ testWidgets('says it is starting, in the sidebar and its chat', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ startBuddy(server);
+ final c = await show(tester, server);
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('starting')),
+ findsOneWidget,
+ );
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ expect(find.text('Starting Claude on Kens-MacBook…'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Start again'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'whose start failed says why and starts again with the same choices',
+ (tester) async {
+ final server = buddySwarm();
+ startBuddy(
+ server,
+ error: 'Its machine did not start it within 3 minutes.',
+ );
+ final c = await show(tester, server);
+ expect(
+ find.descendant(of: buddyEntry, matching: find.text('not started')),
+ findsOneWidget,
+ );
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ "Couldn't start: Its machine did not start it within 3 minutes.",
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.widgetWithText(TextButton, 'Start again'));
+ await tester.pumpAndSettle();
+ expect(commands(server, 'buddy.create').single, {
+ 'type': 'buddy.create',
+ 'projectId': 'lead',
+ 'machineId': 'ken-mac',
+ 'engine': 'claude',
+ });
+ await close(tester, c);
+ },
+ );
+ });
+
+ group('no Chat with PM', () {
+ Future<(ConversationServer, SuperTabController)> withHistory(
+ WidgetTester tester,
+ ) async {
+ final server = buddySwarm(enabled: false);
+ final c = server.controller(account: 'peer');
+ await c.refresh();
+ await c.openPmChat('lead');
+ final id = c.pmChat('lead')!.id;
+ pmReply(server, id, 'Earlier answer from the PM');
+ server.tag('message-${server.revision}', conversationId: id);
+ server.ask(['Ship it?'], conversationId: id);
+ c.dispose();
+ server.state['buddies'] = true;
+ giveBuddy(server);
+ return (server, await show(tester, server));
+ }
+
+ testWidgets('no other private chat is listed or opened either', (
+ tester,
+ ) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('private', 'Pricing talk'),
+ 'projectId': 'lead',
+ 'agentIds': ['lead-agent'],
+ 'audience': {
+ 'people': [
+ {'id': 'peer', 'generation': 'fixture'},
+ {'id': 'owner', 'generation': 'fixture'},
+ ],
+ },
+ });
+ final c = await show(tester, server);
+ if (!c.expandedProjects.contains('lead')) c.toggleProject('lead');
+ await tester.pumpAndSettle();
+
+ expect(
+ find.byKey(const ValueKey('super-group-offline')),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('super-group-private')), findsNothing);
+ expect(find.text('Pricing talk'), findsNothing);
+ expect(await c.select('private'), isTrue);
+ expect(c.selectedId, 'lead');
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'Notifications keep Decisions, for anyone with or without a Buddy',
+ (tester) async {
+ final server = buddySwarm();
+ server.ask(['Ship it?']);
+ final c = await show(tester, server);
+ await tester.tap(find.byKey(const ValueKey('super-notifications')));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Decisions'), findsOneWidget);
+ expect(find.text('Ship it?'), findsOneWidget);
+ await close(tester, c);
+ },
+ );
+
+ testWidgets('the Buddy menu offers none', (tester) async {
+ final (_, c) = await withHistory(tester);
+ await tester.tap(buddyEntry);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('Buddy options'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Remove Buddy'), findsOneWidget);
+ expect(find.text('Earlier Chat with PM'), findsNothing);
+ expect(find.textContaining('Chat with PM'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets(
+ 'a tag from the old Chat with PM is placed in the project chat and opens it',
+ (tester) async {
+ final (_, c) = await withHistory(tester);
+ await tester.tap(find.byKey(const ValueKey('super-notifications')));
+ await tester.pumpAndSettle();
+
+ expect(find.textContaining('Chat with PM'), findsNothing);
+ await tester.tap(
+ find.byKey(const ValueKey('super-mention-mention-1')),
+ );
+ await tester.pumpAndSettle();
+
+ expect(c.selectedId, 'lead');
+ expect(find.text('Earlier answer from the PM'), findsNothing);
+ await close(tester, c);
+ },
+ );
+ });
+
+ group('a proposal in the project chat', () {
+ testWidgets(
+ "is labelled from the server's tag, with whose behalf it is on",
+ (tester) async {
+ final server = buddySwarm();
+ giveBuddy(server);
+ buddyReply(
+ server,
+ 'lead',
+ 'Proposal from ken.tran\'s Buddy, on ken.tran\'s behalf\nGoal: Offline mode\nScope: Desktop only\nPriority: high',
+ source: {
+ 'kind': 'buddy-proposal',
+ 'personId': 'peer',
+ 'ownerMessageId': 'message-1',
+ },
+ );
+ // A Buddy's ordinary message carries no label, whatever it says.
+ buddyReply(server, 'lead', 'Proposal · on ken.tran\'s behalf');
+ final c = await show(tester, server);
+ await c.select('lead');
+ await tester.pumpAndSettle();
+
+ expect(
+ find.byKey(const ValueKey('super-proposal-label')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-proposal-label')),
+ matching: find.text("Proposal · on ken.tran's behalf"),
+ ),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ },
+ );
+ });
+ });
+}
diff --git a/desktop/test/super_tab_project_skills_test.dart b/desktop/test/super_tab_project_skills_test.dart
index 88f809f83..939620496 100644
--- a/desktop/test/super_tab_project_skills_test.dart
+++ b/desktop/test/super_tab_project_skills_test.dart
@@ -109,7 +109,7 @@ void main() {
() {
final source = File('../cli/src/lib/swarmSkills.ts').readAsStringSync();
final sections = source.split(
- 'const defaults: Record<SwarmRole, string> = {',
+ RegExp(r'const defaults: Record<.*?, string> = \{'),
);
expect(sections, hasLength(2));
final defaults = sections.last;
diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dart
index 9c9eb1eeb..324613e49 100644
--- a/desktop/test/super_tab_roster_test.dart
+++ b/desktop/test/super_tab_roster_test.dart
@@ -906,6 +906,21 @@ void main() {
await f.close(tester);
});
+ testWidgets('a Buddy reads Buddy, never Dev: it takes no work', (
+ tester,
+ ) async {
+ final f = await fixture(tester);
+ (f.server.state['agents'] as List)[1]['buddyOf'] = {
+ 'personId': 'owner',
+ 'generation': 'fixture',
+ };
+ await f.controller.refresh();
+ await f.show(tester);
+ expect(f.inRow(1, find.text('Buddy')), findsOneWidget);
+ expect(f.inRow(1, find.text('Dev')), findsNothing);
+ await f.close(tester);
+ });
+
testWidgets('custom role name appears in the roster and agent details', (
tester,
) async {
diff --git a/desktop/test/support/buddy_fixture.dart b/desktop/test/support/buddy_fixture.dart
new file mode 100644
index 000000000..9283088d5
--- /dev/null
+++ b/desktop/test/support/buddy_fixture.dart
@@ -0,0 +1,116 @@
+import 'pm_chat_fixture.dart';
+import 'super_tab_fixture.dart';
+
+/// [pmChatSwarm] with Buddies turned on: Ken (`peer`) reads it, owns a Mac,
+/// and the owner's Studio is shared with the Swarm. Ken has no Buddy yet;
+/// [giveBuddy] adds one.
+ConversationServer buddySwarm({bool enabled = true}) {
+ final server = pmChatSwarm();
+ if (enabled) server.state['buddies'] = true;
+ server.state['machines'] = <dynamic>[
+ {
+ 'machineId': 'ken-mac',
+ 'name': 'Kens-MacBook.local',
+ 'contributorId': 'peer',
+ 'scope': 'swarm',
+ 'engines': <dynamic>[],
+ 'maxAgents': 4,
+ 'availableSlots': 4,
+ },
+ {
+ 'machineId': 'studio',
+ 'name': 'Studio.local',
+ 'contributorId': 'owner',
+ 'scope': 'swarm',
+ 'engines': <dynamic>[],
+ 'maxAgents': 8,
+ 'availableSlots': 8,
+ },
+ ];
+ return server;
+}
+
+/// Gives [person] a running Buddy named [name] in [projectId], on [machineId],
+/// with its private chat, as the backend's `buddy.add` leaves them.
+void giveBuddy(
+ ConversationServer server, {
+ String person = 'peer',
+ String projectId = 'lead',
+ String id = 'wren',
+ String name = 'Wren',
+ String machineId = 'ken-mac',
+ String machineOwnerId = 'peer',
+ String engine = 'claude',
+}) {
+ (server.state['agents'] as List).add({
+ 'id': id,
+ 'name': name,
+ 'projectId': projectId,
+ 'buddyOf': {'personId': person, 'generation': 'fixture'},
+ 'machineId': machineId,
+ 'harnessId': 'h-$id',
+ 'contributorId': person,
+ 'machineOwnerId': machineOwnerId,
+ 'confidential': true,
+ 'configuration': {'engine': engine, 'model': 'default'},
+ });
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('buddy-$person-$projectId', "$person's Buddy"),
+ 'kind': 'buddy',
+ 'projectId': projectId,
+ 'buddyOwnerId': person,
+ 'agentIds': [id],
+ });
+}
+
+/// The Buddy [agentId] posts [text] in [conversationId].
+void buddyReply(
+ ConversationServer server,
+ String conversationId,
+ String text, {
+ String agentId = 'wren',
+ String name = 'Wren',
+ Map<String, dynamic>? source,
+}) {
+ server.append(text, conversationId: conversationId);
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': agentId,
+ 'name': name,
+ };
+ if (source != null) server.messages.last['source'] = source;
+}
+
+/// [person]'s Buddy in [projectId] being added: its chat and its start, with
+/// no agent yet. With [error] the start failed.
+void startBuddy(
+ ConversationServer server, {
+ String person = 'peer',
+ String projectId = 'lead',
+ // A Buddy runs only on its person's own machines (Ken, 10-28).
+ String machineId = 'ken-mac',
+ String engine = 'claude',
+ String? error,
+}) {
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('buddy-$person-$projectId', "$person's Buddy"),
+ 'kind': 'buddy',
+ 'projectId': projectId,
+ 'buddyOwnerId': person,
+ 'agentIds': <String>[],
+ });
+ server.state['starts'] = [
+ {
+ 'id': 'start-1',
+ 'machineOwnerId': person,
+ 'request': {
+ 'conversationId': 'buddy-$person-$projectId',
+ 'machineId': machineId,
+ 'engine': engine,
+ 'buddyOf': {'personId': person, 'generation': 'fixture'},
+ },
+ 'harnessId': null,
+ 'error': error,
+ },
+ ];
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 45620bd46..0e02d4242 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -170,6 +170,10 @@ class SwarmPartsBackend {
if (reader == null || part.deleted || !id.startsWith('groups:')) {
return false;
}
+ // A Buddy chat is read by its person alone (backend Buddies, 10-28).
+ if (part.data['kind'] == 'buddy') {
+ return part.data['buddyOwnerId'] != reader;
+ }
final audience = part.data['audience'];
if (audience is! Map) return false;
final generation = (state['people'] as List?)
@@ -652,6 +656,96 @@ class ConversationServer {
..['resolvedBy'] = 'done';
state['mentionsWaiting'] = (state['mentionsWaiting'] as int) - 1;
revision++;
+ } else if (command['type'] == 'buddy.create') {
+ // As the backend's Buddy create: a start for the reader's Buddy and
+ // its chat, fixed per person and project. The fixture's host starts it
+ // at once.
+ final person = reader ?? 'owner';
+ final projectId = command['projectId'] as String;
+ bool mine(Object? a) =>
+ a is Map &&
+ (a['buddyOf'] as Map?)?['personId'] == person &&
+ a['projectId'] == projectId;
+ // As the backend: one Buddy per person and project. A running one
+ // refuses another; a down one is replaced.
+ if ((state['agents'] as List).any(
+ (a) => mine(a) && (a as Map)['downSince'] == null,
+ )) {
+ throw const SuperTabFailure(
+ 'BUDDY_EXISTS',
+ 'You already have a Buddy in this project.',
+ statusCode: 409,
+ );
+ }
+ revision++;
+ final agentId = 'buddy-$revision';
+ final chatId = 'buddy-$person-$projectId';
+ final machine = (state['machines'] as List? ?? const [])
+ .cast<Map>()
+ .where((m) => m['machineId'] == command['machineId'])
+ .firstOrNull;
+ final owner = (state['people'] as List? ?? const [])
+ .cast<Map>()
+ .where((p) => p['id'] == person)
+ .firstOrNull;
+ // A test's lists may be typed literals: copy into plain lists.
+ state['agents'] = <dynamic>[
+ for (final a in state['agents'] as List)
+ if (!mine(a)) a,
+ ];
+ state['starts'] = <dynamic>[...state['starts'] as List? ?? const []];
+ (state['starts'] as List).add({
+ 'id': 'start-$revision',
+ 'machineOwnerId': machine?['contributorId'] ?? person,
+ 'request': {
+ 'conversationId': chatId,
+ 'projectId': projectId,
+ 'machineId': command['machineId'],
+ 'engine': command['engine'],
+ 'buddyOf': {'personId': person, 'generation': 'fixture'},
+ },
+ 'harnessId': 'h-$agentId',
+ 'error': null,
+ });
+ (state['agents'] as List).add({
+ 'id': agentId,
+ 'name': 'Buddy',
+ 'projectId': projectId,
+ 'buddyOf': {'personId': person, 'generation': 'fixture'},
+ 'machineId': command['machineId'],
+ 'harnessId': 'h-$agentId',
+ 'contributorId': person,
+ 'machineOwnerId': machine?['contributorId'] ?? person,
+ 'confidential': true,
+ 'configuration': {'engine': command['engine'], 'model': 'default'},
+ });
+ final conversations = (state['conversations'] as List)
+ .cast<Map<String, dynamic>>();
+ final chat = conversations.where((g) => g['id'] == chatId).firstOrNull;
+ if (chat != null) {
+ chat['agentIds'] = [agentId];
+ } else {
+ final name = (owner?['email'] as String? ?? person).split('@').first;
+ conversations.add({
+ ...conversationFixture(chatId, "$name's Buddy"),
+ 'kind': 'buddy',
+ 'projectId': projectId,
+ 'buddyOwnerId': person,
+ 'agentIds': [agentId],
+ });
+ }
+ output
+ ..['startId'] = 'start-$revision'
+ ..['conversationId'] = chatId;
+ } else if (command['type'] == 'buddy.remove') {
+ revision++;
+ final person = reader ?? 'owner';
+ (state['agents'] as List).removeWhere(
+ (a) =>
+ a is Map &&
+ (a['buddyOf'] as Map?)?['personId'] == person &&
+ a['projectId'] == command['projectId'],
+ );
} else if (command['type'] == 'conversation.create') {
revision++;
final id = 'group-$revision';
diff --git a/docs/swarms.md b/docs/swarms.md
index 2c178d2ae..5ec879722 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -177,13 +177,47 @@ each person and project, and the server answers a repeat with the conversation
it already made.
It behaves like the project chat: replies, attachments, the unread mark and the
-product manager's tags in Notifications. Only that person and the product
+product manager's tags in Notifications. While the Swarm's Buddies are on, it is read-only (see Buddies). Only that person and the product
manager read it. Other members, the project's owner and the Swarm's owner
included, never receive it, its messages or its notifications. The chat is
chat only: no work is assigned in it, and only the product manager joins it
among agents. As with any session, the owner of the machine running the
product manager can see what its terminal shows.
+## Buddies
+
+A Buddy is a person's own agent in one project. They brainstorm with it in a chat that only they and their Buddy read:
+it asks what they want and why, offers two or three options with the one it recommends, and agrees the scope with
+them. When they say to send it to the product manager, it posts one proposal (goal, scope and priority) in the project
+chat. The proposal is addressed to the product manager and marked as on that person's behalf. The product manager assigns
+the work as usual; a Buddy never assigns work, starts agents, changes code or opens pull requests.
+
+The Swarm's owner turns Buddies on for the Swarm; they are off until then. Turning them off removes every Buddy, fails
+any still starting, and stops their posts. Their chats stay for their owners to read.
+
+- Each person may add one Buddy per project. They choose the project, one of their own machines in the Swarm's Machines
+ list, and Claude Code or Codex. Like a Product Manager, a Buddy runs only on its owner's own machine, in their own
+ account: never on a machine shared with them, and never in a Harness Team account.
+- A Buddy reads its project's chat and its own chat, nothing else. It cannot read workgroups, other people's chats or
+ the Leads conversation. It can post only in its own chat. The server refuses every other command, and a Buddy's own
+ Swarm read shows no machines or routing rules.
+- A Buddy never changes code. A Claude Code Buddy starts in asking mode: only its Super Tab commands run without asking,
+ file editing is turned off, and the files in its own copy of the project are read-only. A Codex Buddy keeps Codex's
+ full permissions with read-only files (follow-up: give Codex the same pre-approved commands). No Buddy gets the
+ Harness GitHub App's token.
+ Claude Code also merges allow rules from the machine owner's own settings and the project's checked-in settings: a
+ broad shell rule there applies to a Buddy too, so keep those narrow on machines that run Claude Buddies.
+- Nobody else is ever added to a Buddy chat, the Swarm's owner and the product manager included.
+- A proposal is sent only for its owner's own message in their Buddy chat that asked for it: their newest message there,
+ or one from the last hour, and only once for each such message. The server writes the "on behalf of" label, so a Buddy cannot leave it out or change it.
+- Nobody else reads a Buddy chat: not the product manager, and not the project's or the Swarm's owner. Private matters
+ stay there; the Buddy posts only what its owner asks it to send.
+- Removing a Buddy, the owner leaving the Swarm, or deleting the project closes its session. Adding a Buddy again
+ reopens the same chat. Adding one while the person's Buddy there is down replaces it in one step, in the same chat;
+ while it runs or starts, adding another is refused. The idle tidy-up leaves Buddies alone: a Buddy waits for its owner.
+- While Buddies are on, Chat with PM is read-only. Nobody opens a new one or posts in an old one, the product manager
+ included, and old history stays readable. To talk to the product manager, people use the project chat.
+
## Leaderboard
The leaderboard shows how each person helped the team ship this week. People
diff --git a/store/spec/CHANGES.md b/store/spec/CHANGES.md
index 60cf17aea..ed97f0986 100644
--- a/store/spec/CHANGES.md
+++ b/store/spec/CHANGES.md
@@ -231,3 +231,16 @@ Initial contract. Lifted from the `.board.json` (Circuit) and `.episode.json` (T
- **Mechanism:** the selected daemon validates compatibility, refreshes availability, and resolves
credentials after reserving the creation receipt and before preparing a project. Receipt identity
contains the model/grid pair, never a rotating credential. Unavailable models refuse launch.
+
+## 2026-10-28 — `runsScripts` in the catalog
+
+- **Change:** registry entries may include `runsScripts: true`. Built-in entries derive it from
+ `harness.json`'s `toolchain.setup` or `toolchain.doctor`; an outside entry states it. Any other value
+ is refused at publication.
+- **Why:** Harness cannot run a setup or doctor script on Windows yet. 25 of 25 Windows Store installs
+ failed between 10-26 and 10-28, and once the CLI named the reason it still refused only after the
+ download, leaving the files on disk. With the flag, the CLI refuses before downloading anything.
+- **Backward compatible:** yes. Older CLIs drop unknown entry fields; an outside entry without the flag
+ is still checked after its download, before it is moved into place.
+- **Mechanism:** `cli/src/dsh/registry.ts` (`storeEntry`, `DshRegistryEntrySchema`),
+ `cli/scripts/lib/dshRegistry.mjs`, `store/tools/catalog.mjs`, `cli/src/dsh/service.ts`.
diff --git a/store/tools/catalog.mjs b/store/tools/catalog.mjs
index 9acc754c6..93c342fe4 100644
--- a/store/tools/catalog.mjs
+++ b/store/tools/catalog.mjs
@@ -27,6 +27,7 @@ export function createStoreCatalog(storeDir, ref, {revisionFor}={}) {
if(entry.path!==undefined&&!PACKAGE_PATH.test(entry.path))throw new Error(`${entry.id}: invalid package path`);
if(entry.viewerUse!==undefined&&!ID.test(entry.viewerUse))throw new Error(`${entry.id}: invalid viewer dependency`);
if(entry.tier!==undefined&&![0,1,2].includes(entry.tier))throw new Error(`${entry.id}: invalid tier`);
+ if(entry.runsScripts!==undefined&&entry.runsScripts!==true)throw new Error(`${entry.id}: invalid runsScripts`);
for(const key of ['homepage','upstream'])if(entry[key]!==undefined)new URL(entry[key]);
if(entry.examples!==undefined){if(!Array.isArray(entry.examples)||entry.examples.length>8)throw new Error(`${entry.id}: invalid examples`);for(const ex of entry.examples){if(!ex||typeof ex!=='object'||typeof ex.prompt!=='string'||!ex.prompt.trim()||ex.prompt.length>600)throw new Error(`${entry.id}: an example needs a prompt`);for(const media of ['image','video'])if(ex[media]!==undefined&&(typeof ex[media]!=='string'||ex[media].length>2048||new URL(ex[media]).protocol!=='https:'))throw new Error(`${entry.id}: an example ${media} is an https URL`);if(ex.caption!==undefined&&(typeof ex.caption!=='string'||ex.caption.length>120))throw new Error(`${entry.id}: invalid example caption`);for(const key of Object.keys(ex))if(!['prompt','image','video','caption'].includes(key))throw new Error(`${entry.id}: unknown example field ${key}`);}}
if(entry.screenshots!==undefined){if(!Array.isArray(entry.screenshots)||entry.screenshots.length>8)throw new Error(`${entry.id}: invalid screenshots`);for(const shot of entry.screenshots){if(typeof shot!=='string'||shot.length>2048)throw new Error(`${entry.id}: invalid screenshot`);new URL(shot);}}