The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
A person can have several Buddies: default and cap (#3818, part 1) (#3383)
harness-for-autonomous[bot]878448b21e92
diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.tsindex 890acf820..d1d4c98f3 100644--- a/backend/integration/superTabSwarmBuddy.test.ts+++ b/backend/integration/superTabSwarmBuddy.test.ts@@ -832,3 +832,45 @@ describe('older apps', () => {await expect(f.store.messages(peer, f.tab, 'lead', {}, agentId)).rejects.toThrow(UNAVAILABLE)})})++// Task #3818: a person's other Buddies' chats are listed on their main one, whose id every command derives, so a command loads+// them even once they have gone quiet; and a name chosen in one stays taken.+describe('several Buddies through the store (#3818)', () => {+ /** [chat] gone quiet, as the tidy pass leaves it: only a command that names it, or loads it with its list, reads it. */+ const quiet = async (f: Swarm, chat: string) => {+ const row = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: chat } })+ await db.swarmGroup.update({ where: { id: row.id }, data: { dormant: true, version: row.version + 1, changedAt: new Date(),+ data: { ...row.data as object, dormant: true } } })+ }+ const named = async (f: Swarm, name: string) => {+ const added = await f.execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name } as Command, peer)+ return { chat: String(added.result.conversationId), agent: await f.launch(String(added.result.startId)) }+ }+ const agents = async (f: Swarm) => (await f.store.read(peer, f.tab)).state.agents.filter(a => a.buddyOf?.personId === peer.sub).map(a => a.id)++ it('removes a quiet default Buddy, and the first becomes the default again', async () => {+ const f = await swarm()+ const first = await buddy(f)+ const second = await named(f, 'Research')+ await f.execute({ type: 'buddy.default', conversationId: second.chat } as Command, peer)+ await quiet(f, second.chat)+ await f.execute({ type: 'buddy.remove' }, peer)+ expect(await agents(f)).toEqual([first.main])+ const chats = (await f.store.read(peer, f.tab)).state.conversations+ expect(chats.find(c => c.id === first.chat)).toMatchObject({ buddyDefault: true })+ expect(chats.find(c => c.id === first.chat)!.buddyChats).toBeUndefined()+ })++ it('keeps a quiet Buddy\'s name taken, and counts it against the cap', async () => {+ const f = await swarm()+ await buddy(f)+ const research = await named(f, 'Research')+ await quiet(f, research.chat)+ await expect(f.execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer))+ .rejects.toMatchObject({ code: 'BUDDY_NAME_TAKEN' })+ await f.execute({ type: 'tab.buddyCap', cap: 2 } as Command)+ await expect(f.execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Planning' } as Command, peer))+ .rejects.toMatchObject({ code: 'BUDDY_CAP' })+ expect((await f.store.read(peer, f.tab)).state.buddyCap).toBe(2)+ })+})diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 72392004a..be36abe78 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -4,8 +4,9 @@ import { applyCommand, commandSchema, type Command, type CommandContext } from 'import { createSuperTab, stableId, visibleState, type Actor, type Conversation } from './model.js'import { canReadGroup, canWatchAgent, isConfidential, readsRecordsIn, wordsOf } from './projects.js'import { CLOSED_CHAT_ANSWERED_NOTICE } from './decisions.js'-import { buddyChatId, shownBefore, swarmBuddyChatId } from './buddies.js'+import { buddyChatId, defaultBuddy, defaultBuddyChat, shownBefore, swarmBuddyChatId } from './buddies.js'import { isRoleName } from './agentNames.js'+import { buddiesTold } from './buddyNews.js'import { sweepLiveness } from './liveness.js'import { hostTab } from './read/hostRows.js'import { groupView } from './read/views.js'@@ -1546,3 +1547,233 @@ describe('naming a Buddy (Diego, 10-29)', () => {expect(group(f, chat).buddyName).toBeUndefined()})})++// Task #3818 (Phase 2 of the Buddy board spec, "Many Buddies", approved by Ken and anh Dee 11-06): a person creates, names and+// removes several Buddies, one per purpose, so each keeps its own context; one is their default; a cap per Swarm bounds them.+describe('several Buddies', () => {+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }+ /** peer's Buddy added in [chat] (or a new one named [name]) and started on their Mac. */+ function add(f: ReturnType<typeof setup>, fields: { name?: string; conversationId?: string } = {}) {+ const added = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', ...fields } as Command, peer, host)+ const startId = added.result.startId as string+ const agentId = f.run({ type: 'agent.started', startId, harnessId: `native-${startId}`, configuration }, peer, host).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null }, peer, host)+ return { agentId, chat: added.result.conversationId as string }+ }+ const refusal = (body: () => unknown): { code: string; message: string } | null => {+ try { body(); return null } catch (error) { return error as { code: string; message: string } }+ }+ const peerPerson = (f: ReturnType<typeof setup>) => f.state.people.find(p => p.id === 'peer')!++ it('creates a second Buddy with its name, in its own chat beside the first, which stays the default', () => {+ const f = fresh()+ const first = add(f)+ expect(first.chat).toBe(peerSwarmChat)+ const second = add(f, { name: 'Research' })+ expect(second.chat).not.toBe(peerSwarmChat)+ const chat = group(f, second.chat)+ expect(chat).toMatchObject({ kind: 'swarm-buddy', title: 'Research', buddyName: 'Research', agentIds: [second.agentId],+ audience: { people: [{ id: 'peer', generation: 'first' }] } })+ expect([canReadGroup(f.state, peer, chat), canReadGroup(f.state, owner, chat)]).toEqual([true, false])+ expect(group(f, peerSwarmChat).buddyChats).toEqual([second.chat])+ expect(defaultBuddyChat(f.state, peerPerson(f)).id).toBe(peerSwarmChat)+ expect(defaultBuddy(f.state, 'peer')?.id).toBe(first.agentId)+ // A name another Buddy has is refused, as a rename is.+ expect(refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer, host))?.code).toBe('BUDDY_NAME_TAKEN')+ })++ it('refuses one more past the Swarm\'s cap, which its owner sets, counting Buddies still starting', () => {+ const f = fresh()+ f.run({ type: 'tab.buddyCap', cap: 2 } as Command, owner)+ expect(f.state.buddyCap).toBe(2)+ add(f)+ f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer, host)+ const refused = refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Planning' } as Command, peer, host))+ expect(refused).toMatchObject({ code: 'BUDDY_CAP', message: 'You have 2 Buddies, the most this Swarm allows. Remove one to add another.' })+ expect(refusal(() => f.run({ type: 'tab.buddyCap', cap: 3 } as Command, peer))?.code).toBe('OWNER_REQUIRED')+ })++ // Review of #3818 (Readycheck, P1): the cap counts every start that adds a Buddy, also into one of the person's chats with none.+ it('refuses a Buddy past the cap into a chat of theirs that has none: a failed start retried, or an empty main chat', () => {+ const f = fresh()+ f.run({ type: 'tab.buddyCap', cap: 3 } as Command, owner)+ add(f)+ add(f, { name: 'Planning' })+ const failed = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer, host)+ f.run({ type: 'agent.startFailed', startId: failed.result.startId as string, error: 'It did not launch.' }, peer, host)+ // At the cap once its owner lowers it: retrying the failed Buddy's chat would be a third.+ f.run({ type: 'tab.buddyCap', cap: 2 } as Command, owner)+ const starts = f.state.starts!.length+ expect(refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', conversationId: failed.result.conversationId } as Command, peer, host))?.code).toBe('BUDDY_CAP')+ // A refusal starts nothing.+ expect(f.state.starts!.length).toBe(starts)+ // The main chat left empty, with the cap lowered below what is left: neither a new Buddy nor that chat takes one.+ const g = fresh()+ g.run({ type: 'tab.buddyCap', cap: 3 } as Command, owner)+ add(g)+ add(g, { name: 'Research' })+ add(g, { name: 'Planning' })+ g.run({ type: 'buddy.remove', conversationId: peerSwarmChat } as Command, peer)+ g.run({ type: 'tab.buddyCap', cap: 2 } as Command, owner)+ expect(refusal(() => g.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Writing' } as Command, peer, host))?.code).toBe('BUDDY_CAP')+ expect(refusal(() => g.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', conversationId: peerSwarmChat } as Command, peer, host))?.code).toBe('BUDDY_CAP')+ expect(g.state.starts!.filter(s => !s.harnessId && !s.error)).toEqual([])+ })++ // Review of #3818 (SecReview3293, Important): a new Buddy whose start failed left an empty chat that nothing reused or removed.+ it('reuses a failed Buddy\'s empty chat for the next one, and removes an empty chat when asked', () => {+ const f = fresh()+ add(f)+ const fail = (name: string) => {+ const added = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name } as Command, peer, host)+ f.run({ type: 'agent.startFailed', startId: added.result.startId as string, error: 'It did not launch.' }, peer, host)+ return added.result.conversationId as string+ }+ const empty = fail('Research')+ expect(fail('Planning')).toBe(empty)+ expect(group(f, peerSwarmChat).buddyChats).toEqual([empty])+ expect(group(f, empty).title).toBe('Planning')+ f.run({ type: 'buddy.remove', conversationId: empty } as Command, peer)+ expect(group(f, empty).archived).toBe(true)+ expect(group(f, peerSwarmChat).buddyChats).toBeUndefined()+ // The main chat stays theirs, as before: with no Buddy there, removing it says so.+ f.run({ type: 'buddy.remove' }, peer)+ expect(refusal(() => f.run({ type: 'buddy.remove', conversationId: peerSwarmChat } as Command, peer))?.code).toBe('NOT_FOUND')+ })++ // Review of #3818 (SecReview3293, Minor): a person's lines never go to a chat with no Buddy because it was picked as default.+ it('refuses a default with no Buddy running or starting in it', () => {+ const f = fresh()+ add(f)+ const added = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer, host)+ f.run({ type: 'agent.startFailed', startId: added.result.startId as string, error: 'It did not launch.' }, peer, host)+ expect(refusal(() => f.run({ type: 'buddy.default', conversationId: added.result.conversationId } as Command, peer))?.code).toBe('NO_BUDDY')+ expect(defaultBuddyChat(f.state, f.state.people.find(p => p.id === 'peer')!).id).toBe(peerSwarmChat)+ })++ it('moves the default, passes it to the oldest left when the default is removed, and archives a removed Buddy\'s chat', () => {+ const f = fresh()+ const first = add(f), second = add(f, { name: 'Research' }), third = add(f, { name: 'Planning' })+ f.run({ type: 'buddy.default', conversationId: second.chat } as Command, peer)+ expect(defaultBuddyChat(f.state, peerPerson(f)).id).toBe(second.chat)+ expect(defaultBuddy(f.state, 'peer')?.id).toBe(second.agentId)+ expect([peerSwarmChat, second.chat, third.chat].map(id => group(f, id).buddyDefault ?? false)).toEqual([false, true, false])+ // Without a chat named, the default goes, and the oldest Buddy left becomes the default.+ f.run({ type: 'buddy.remove' }, peer)+ expect(f.state.agents.some(a => a.id === second.agentId)).toBe(false)+ expect(group(f, second.chat).archived).toBe(true)+ expect(group(f, peerSwarmChat).buddyChats).toEqual([third.chat])+ expect(defaultBuddy(f.state, 'peer')?.id).toBe(first.agentId)+ f.run({ type: 'buddy.remove', conversationId: third.chat } as Command, peer)+ expect(group(f, third.chat).archived).toBe(true)+ expect(defaultBuddy(f.state, 'peer')?.id).toBe(first.agentId)+ })++ it('is only its person\'s to change: never another person\'s, an agent\'s, or a chat that is not their Buddy\'s', () => {+ const f = fresh()+ add(f)+ const second = add(f, { name: 'Research' })+ expect(refusal(() => f.run({ type: 'buddy.default', conversationId: second.chat } as Command, owner))?.code).toBe('NOT_FOUND')+ expect(refusal(() => f.run({ type: 'buddy.remove', conversationId: second.chat } as Command, owner))?.code).toBe('NOT_FOUND')+ // An agent: one that cannot read the chat is told it is not there; the Buddy itself may not pick for its person either.+ expect(refusal(() => f.run({ type: 'buddy.default', conversationId: second.chat } as Command, agentActor(f.pm)))?.code).toBe('NOT_FOUND')+ expect(refusal(() => f.run({ type: 'buddy.default', conversationId: second.chat } as Command, agentActor(second.agentId)))).not.toBeNull()+ expect(defaultBuddyChat(f.state, f.state.people.find(p => p.id === 'peer')!).id).toBe(peerSwarmChat)+ expect(refusal(() => f.run({ type: 'buddy.default', conversationId: f.group } as Command, peer))?.code).toBe('NOT_FOUND')+ expect(refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', conversationId: f.group } as Command, peer, host))?.code).toBe('NOT_FOUND')+ })++ it('changes nothing for a person with one Buddy: the same chat, its running Buddy kept, and removed as before', () => {+ const f = fresh()+ const first = add(f)+ expect(refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude' }, peer, host))?.code).toBe('BUDDY_EXISTS')+ expect(group(f, peerSwarmChat).buddyChats).toBeUndefined()+ expect(group(f, peerSwarmChat).buddyDefault).toBeUndefined()+ f.run({ type: 'buddy.remove' }, peer)+ expect(f.state.agents.some(a => a.id === first.agentId)).toBe(false)+ expect(group(f, peerSwarmChat).archived).toBe(false)+ })++ it('starts a named Buddy again in its own chat, and a second Buddy\'s start is not failed by the first\'s', () => {+ const f = fresh()+ add(f)+ const pending = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command, peer, host)+ add(f, { name: 'Planning' })+ expect(f.state.starts!.find(s => s.id === pending.result.startId)!.error).toBeNull()+ const research = pending.result.conversationId as string+ expect(refusal(() => f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', conversationId: research } as Command, peer, host))?.code).toBe('BUDDY_EXISTS')+ })+})++// Task #3818: what is addressed to a person goes to their default Buddy; news of a proposal to the Buddy that sent it while it is+// still theirs, else to the default.+describe('several Buddies: where a person\'s lines go', () => {+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }+ function two() {+ const f = fresh()+ const start = (fields: Record<string, unknown> = {}) => {+ const added = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', ...fields } as Command, peer, host)+ const startId = added.result.startId as string+ const agentId = f.run({ type: 'agent.started', startId, harnessId: `native-${startId}`, configuration }, peer, host).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null }, peer, host)+ return { agentId, chat: added.result.conversationId as string }+ }+ return { f, first: start(), second: start({ name: 'Research' }) }+ }++ it('sends a PM\'s line to the default Buddy\'s chat, and an older app\'s Buddy chat is the default\'s', () => {+ const { f, second } = two()+ f.run({ type: 'buddy.default', conversationId: second.chat } as Command, peer)+ const told = f.run({ type: 'person.tell', personId: 'peer', text: 'Your idea is next up.' }, agentActor(f.pm))+ expect(told.messages.filter(m => m.text === 'Your idea is next up.').map(m => m.conversationId)).toContain(second.chat)+ expect(told.messages.filter(m => m.text === 'Your idea is next up.').map(m => m.conversationId)).not.toContain(peerSwarmChat)+ expect(f.run({ type: 'buddy.chat' }, peer).result.conversationId).toBe(second.chat)+ })++ it('tells a proposal\'s news to the Buddy that sent it, and to the default once that one is removed', () => {+ const { f, first, second } = two()+ const answer = { id: 'm1', conversationId: f.app.conversationId, text: 'Accepted: next up.', replyTo: 'p1', recipients: [],+ author: { kind: 'agent', id: f.pm, name: 'app-pm' } } as never+ const proposal = { kind: 'buddy-proposal', personId: 'peer', buddyId: second.agentId }+ expect(buddiesTold(f.state, answer, proposal)).toEqual([second.agentId])+ f.run({ type: 'buddy.remove', conversationId: second.chat } as Command, peer)+ expect(buddiesTold(f.state, answer, proposal)).toEqual([first.agentId])+ })+})++// Task #3818: on its machine, each of a person's Buddies and its thread sessions are told their own chat, so the host ends a+// session and moves a model switch in the right one; an older host, which names the main chat, still ends the right session.+describe('several Buddies on their machine', () => {+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }+ 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+ function withSession() {+ const f = fresh()+ const start = (command: Record<string, unknown>) => {+ const added = f.run(command as Command, peer, host)+ const startId = added.result.startId as string+ const agentId = f.run({ type: 'agent.started', startId, harnessId: `native-${startId}`, configuration }, peer, host).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null }, peer, host)+ return { agentId, conversationId: added.result.conversationId as string, messageId: added.result.messageId as string }+ }+ const first = start({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude' })+ const second = start({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' })+ const session = start({ type: 'message.send', conversationId: second.conversationId, text: 'Dig into the CPU spike', replyTo: null, recipientIds: [], newSession: true })+ return { f, first, second, session }+ }++ it('tells each Buddy and its thread sessions their own chat', async () => {+ const { f, first, second, session } = withSession()+ const rows = (await hostTab('swarm', f.state, 'peer-mac', user, null, lookups)).roster as Array<{ agent: { id: string }; buddyChatId?: string | null }>+ const chatOf = (agentId: string) => rows.find(r => r.agent.id === agentId)?.buddyChatId+ expect([chatOf(first.agentId), chatOf(second.agentId), chatOf(session.agentId)]).toEqual([peerSwarmChat, second.conversationId, second.conversationId])+ expect(rows.find(r => r.agent.id === f.pm)?.buddyChatId).toBeUndefined()+ })++ it('ends a thread session of another Buddy that an older host names by the main chat', () => {+ const { f, second, session } = withSession()+ const ended = f.run({ type: 'buddy.sessionEnd', conversationId: peerSwarmChat, thread: session.messageId, reason: 'idle' }, peer)+ expect(ended.result.ended).toBe(true)+ expect(group(f, second.conversationId).buddySessions ?? []).toEqual([])+ })+})diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.tsindex ce3c85fd5..cde7efd83 100644--- a/backend/src/superTabs/buddies.ts+++ b/backend/src/superTabs/buddies.ts@@ -85,6 +85,110 @@ export function openSwarmBuddyChat(state: SuperTabState, owner: Person): Conversreturn chat}+/** Whether [agent] is [person]'s own main Buddy now: theirs at their current membership, never a thread session's. */+const ownBuddy = (agent: Agent, person: Pick<Person, 'id' | 'generation'>): boolean => isSwarmBuddy(agent) && !agent.buddySession+ && agent.buddyOf!.personId === person.id && agent.buddyOf!.generation === person.generation++/** The Buddy chat [agent] is in (its main Buddy or a thread session of it), when loaded (task #3818). */+export const buddyChatOf = (state: SuperTabState, agent: Pick<Agent, 'id'>): Conversation | undefined =>+ state.conversations.find(c => isSwarmBuddyChat(c) && c.agentIds.includes(agent.id))++/** How many Buddies a person may have in a Swarm unless its owner sets another number (spec: "Many Buddies", task #3818). */+export const BUDDY_CAP = 5+/** The most a Swarm's owner may allow (tab.buddyCap): every Buddy is a session on its person's machine. */+export const MAX_BUDDY_CAP = 20+export const buddyCapOf = (state: Pick<SuperTabState, 'buddyCap'>): number => state.buddyCap ?? BUDDY_CAP+export const buddyCapRefusal = (cap: number): string => `You have ${cap} Buddies, the most this Swarm allows. Remove one to add another.`++/** [person]'s Buddy chats loaded here, oldest first: their main chat (swarmBuddyChatId), then those it lists (buddyChats), each+ * theirs at their current membership and not removed. */+export function buddyChatsOf(state: SuperTabState, person: Pick<Person, 'id' | 'generation'>): Conversation[] {+ const main = state.conversations.find(c => c.id === swarmBuddyChatId(person))+ const listed = (main?.buddyChats ?? []).map(id => state.conversations.find(c => c.id === id))+ return [main, ...listed].filter((c): c is Conversation => !!c && isSwarmBuddyChat(c) && !c.archived+ && !!c.audience?.people.some(p => p.id === person.id && p.generation === person.generation))+}++/** The chat whose Buddy is [person]'s default: the one marked, else their main chat. Undefined when none is loaded. */+const defaultChatOf = (state: SuperTabState, person: Pick<Person, 'id' | 'generation'>): Conversation | undefined => {+ const chats = buddyChatsOf(state, person)+ return chats.find(c => c.buddyDefault) ?? chats.find(c => c.id === swarmBuddyChatId(person))+}++/** [personId]'s default Buddy in this Swarm: the one their lines go to, a removed Buddy's news and what is asked of them (task+ * #3818): the Buddy of their default chat; with that chat not loaded, their first Buddy, as before several. Undefined when they+ * have none, or are not in the Swarm. Never throws. */+export function defaultBuddy(state: SuperTabState, personId: string): Agent | undefined {+ const person = state.people.find(p => p.id === personId)+ if (!person) return undefined+ const chat = defaultChatOf(state, person)+ return chat ? state.agents.find(agent => ownBuddy(agent, person) && chat.agentIds.includes(agent.id))+ : state.agents.find(agent => ownBuddy(agent, person))+}++/** The chat a line for [person] goes to: their default Buddy's, or with none their main Buddy chat, opened if missing, so there+ * is always somewhere to write (task #3818). */+export function defaultBuddyChat(state: SuperTabState, person: Person): Conversation {+ return defaultChatOf(state, person) ?? openSwarmBuddyChat(state, person)+}++/** Whether [chat] of [person] has their Buddy in it, running or starting (task #3818): a chat whose start failed has none. */+export function hasBuddy(state: SuperTabState, person: Pick<Person, 'id' | 'generation'>, chat: Conversation): boolean {+ return state.agents.some(a => ownBuddy(a, person) && chat.agentIds.includes(a.id))+ || !!state.starts?.some(s => s.request.conversationId === chat.id && !s.request.buddySession && !s.harnessId && !s.error)+}++/** How many Buddies [person] has, running or starting, against the Swarm's cap. */+export function buddyCount(state: SuperTabState, person: Pick<Person, 'id' | 'generation'>): number {+ return buddyChatsOf(state, person).filter(chat => hasBuddy(state, person, chat)).length+}++/** A new Buddy's own chat for [owner], with id [id], listed on their main chat so it loads with it (task #3818). */+export function openNewBuddyChat(state: SuperTabState, owner: Person, id: string): Conversation {+ const main = openSwarmBuddyChat(state, owner)+ const number = nextConversationNumber(state)+ state.groupCounter = number+ const chat: Conversation = { id, kind: 'swarm-buddy', number, title: defaultBuddyName(owner), leadId: null, agentIds: [], archived: false, brief: '',+ checks: [], assignment: null, lastMessageSequence: 0, audience: { people: [{ id: owner.id, generation: owner.generation }] } }+ state.conversations.push(chat)+ main.buddyChats = [...main.buddyChats ?? [], id]+ return chat+}++/** [chat]'s Buddy becomes [person]'s default (buddy.default): marked on that chat alone. */+export function setDefaultBuddy(state: SuperTabState, person: Pick<Person, 'id' | 'generation'>, chat: Conversation): void {+ for (const other of buddyChatsOf(state, person)) delete other.buddyDefault+ chat.buddyDefault = true+}++/** [chat] of [person] after its Buddy was removed: a chat other than their main one is archived and leaves the main chat's list;+ * the main chat stays, as before, for a Buddy added again. A removed default passes to their oldest Buddy left. */+export function dropBuddyChat(state: SuperTabState, person: Pick<Person, 'id' | 'generation'>, chat: Conversation): void {+ const wasDefault = defaultChatOf(state, person)?.id === chat.id+ const main = state.conversations.find(c => c.id === swarmBuddyChatId(person))+ if (chat.id !== swarmBuddyChatId(person)) {+ chat.archived = true+ if (main?.buddyChats) {+ main.buddyChats = main.buddyChats.filter(id => id !== chat.id)+ if (!main.buddyChats.length) delete main.buddyChats+ }+ }+ delete chat.buddyDefault+ if (!wasDefault) return+ const next = buddyChatsOf(state, person).find(c => c.id !== chat.id && state.agents.some(a => ownBuddy(a, person) && c.agentIds.includes(a.id)))+ if (next) setDefaultBuddy(state, person, next)+}++/** Where a notice about what [senderBuddyId] sent for [person] goes (task #3817's decided and needs-you lines): that Buddy and its+ * chat while it is still theirs, else their default (defaultBuddyChat), so a removed sender's news is never lost. */+export function buddyFor(state: SuperTabState, person: Person, senderBuddyId: string | null): { agent?: Agent; chat: Conversation } {+ const sender = senderBuddyId ? state.agents.find(a => a.id === senderBuddyId && ownBuddy(a, person)) : undefined+ const chat = sender && state.conversations.find(c => isSwarmBuddyChat(c) && c.agentIds.includes(sender.id))+ if (sender && chat) return { agent: sender, chat }+ const agent = defaultBuddy(state, person.id)+ return { ...agent ? { agent } : {}, chat: defaultBuddyChat(state, person) }+}+/** What a Buddy is called until its owner names it: "ken's Buddy". */export const defaultBuddyName = (owner: Pick<Person, 'email'>): string => `${owner.email.split('@')[0]}'s Buddy`diff --git a/backend/src/superTabs/buddyDefault.test.ts b/backend/src/superTabs/buddyDefault.test.tsnew file mode 100644index 000000000..bc0b97bf0--- /dev/null+++ b/backend/src/superTabs/buddyDefault.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest'+import { createSuperTab, type Agent, type Person } from './model.js'+import { buddyFor, defaultBuddy, defaultBuddyChat, openSwarmBuddyChat, swarmBuddyChatId } from './buddies.js'++// Task #3818 (Phase 2 of the Buddy board spec, approved 11-06): a person's lines (a decision, a needs-you, a removed Buddy's+// news) go to their default Buddy, and a proposal's notice to the Buddy that sent it while it is still theirs. Until a person+// may have several, the default is their one Buddy.+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }++function setup() {+ const state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')+ const peer: Person = { id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'second' }+ state.people.push(peer)+ const buddy = (id: string, extra: Partial<Agent> = {}): Agent => {+ const agent = { id, machineId: 'machine', harnessId: `${id}-harness`, machineOwnerId: 'peer', contributorId: 'peer', membershipGeneration: 'second',+ name: id, configuration, buddyOf: { personId: 'peer', generation: 'second' }, buddyScope: 'swarm', ...extra } as Agent+ state.agents.push(agent)+ return agent+ }+ return { state, peer, buddy }+}++describe('a person\'s default Buddy', () => {+ it('is their Buddy in this Swarm, never a thread session\'s, one of an older membership, or another person\'s', () => {+ const { state, peer, buddy } = setup()+ expect(defaultBuddy(state, peer.id)).toBeUndefined()+ buddy('old', { buddyOf: { personId: 'peer', generation: 'first' } })+ buddy('session', { buddySession: { thread: 't1', from: 0 } } as Partial<Agent>)+ buddy('theirs', { buddyOf: { personId: 'other', generation: 'second' } })+ expect(defaultBuddy(state, peer.id)).toBeUndefined()+ const main = buddy('main')+ openSwarmBuddyChat(state, peer).agentIds.push(main.id)+ expect(defaultBuddy(state, peer.id)?.id).toBe('main')+ expect(defaultBuddy(state, 'nobody')).toBeUndefined()+ })++ it('has a chat to write to, even before the person has a Buddy', () => {+ const { state, peer, buddy } = setup()+ expect(defaultBuddyChat(state, peer).id).toBe(swarmBuddyChatId(peer))+ const main = buddy('main')+ const chat = openSwarmBuddyChat(state, peer)+ chat.agentIds.push(main.id)+ expect(defaultBuddyChat(state, peer)).toBe(chat)+ })+})++describe('the Buddy a proposal\'s notice goes to', () => {+ it('is the Buddy that sent it while it is still that person\'s, else their default', () => {+ const { state, peer, buddy } = setup()+ const main = buddy('main')+ const chat = openSwarmBuddyChat(state, peer)+ chat.agentIds.push(main.id)+ expect(buddyFor(state, peer, 'main')).toEqual({ agent: main, chat })+ // Removed, an older membership's, another person's, or none named: the default.+ expect(buddyFor(state, peer, 'gone')).toEqual({ agent: main, chat })+ buddy('old', { buddyOf: { personId: 'peer', generation: 'first' } })+ expect(buddyFor(state, peer, 'old').agent?.id).toBe('main')+ buddy('theirs', { buddyOf: { personId: 'other', generation: 'second' } })+ expect(buddyFor(state, peer, 'theirs').agent?.id).toBe('main')+ expect(buddyFor(state, peer, null)).toEqual({ agent: main, chat })+ })++ it('with no Buddy left, is the person\'s main Buddy chat, with no agent', () => {+ const { state, peer } = setup()+ expect(buddyFor(state, peer, 'gone')).toEqual({ chat: expect.objectContaining({ id: swarmBuddyChatId(peer) }) })+ })+})diff --git a/backend/src/superTabs/buddyModel.test.ts b/backend/src/superTabs/buddyModel.test.tsindex 486e39c3b..f7f825f94 100644--- a/backend/src/superTabs/buddyModel.test.ts+++ b/backend/src/superTabs/buddyModel.test.ts@@ -163,6 +163,8 @@ describe('the Buddy\'s machine reporting the switch', () => {const { f, requestId } = asked()f.state.agents.push({ ...structuredClone(f.agent()), id: 'session', harnessId: 'h-session', buddySession: { thread: 't', from: 0 } })delete f.state.agents.at(-1)!.modelRequest+ // A session is in its Buddy's chat, as a New session puts it (commands.ts routeBuddySession).+ f.state.conversations.find(c => c.id === f.chat)!.agentIds.push('session')f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, f.buddy())expect(f.state.agents.find(a => a.id === 'session')!.gridModel).toBe(MODEL)f.run({ type: 'buddy.model', gridModel: null })@@ -367,3 +369,35 @@ describe('a Buddy\'s new thread session', () => {expect(request.model).toBeUndefined()})})++// Task #3818: a person with several Buddies switches one of them, named by its chat (else their default); its own thread+// sessions move with it, and the outcome is told in its own chat.+describe('switching one of several Buddies', () => {+ function two() {+ const f = setup()+ const added = f.run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', name: 'Research' } as Command)+ const startId = added.result.startId as string+ const second = f.run({ type: 'agent.started', startId, harnessId: 'peer-research', configuration }).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null })+ return { f, second, secondChat: added.result.conversationId as string, agent: (id: string) => f.state.agents.find(a => a.id === id)! }+ }++ it('switches the Buddy whose chat is named, and tells it there', () => {+ const { f, second, secondChat, agent } = two()+ f.run({ type: 'buddy.model', gridModel: MODEL, conversationId: secondChat } as Command)+ expect(agent(second).modelRequest).toMatchObject({ gridModel: MODEL })+ expect(f.agent().modelRequest).toBeUndefined()+ const effects = f.run({ type: 'buddy.modelResult', agentId: second, requestId: agent(second).modelRequest!.id, ok: true },+ { kind: 'agent', agentId: second, machineOwnerId: 'peer' })+ expect(effects.messages.filter(m => m.text.startsWith('Your Buddy now runs')).map(m => m.conversationId)).toEqual([secondChat])+ })++ it('switches the default without a chat named, and refuses a chat that is not one of the person\'s Buddies', () => {+ const { f, second, secondChat, agent } = two()+ f.run({ type: 'buddy.default', conversationId: secondChat } as Command)+ f.run({ type: 'buddy.model', gridModel: MODEL })+ expect(agent(second).modelRequest).toBeDefined()+ expect(f.agent().modelRequest).toBeUndefined()+ expect(code(() => f.run({ type: 'buddy.model', gridModel: MODEL, conversationId: 'lead' } as Command))).toBe('NOT_FOUND')+ })+})diff --git a/backend/src/superTabs/buddyModel.ts b/backend/src/superTabs/buddyModel.tsindex b39fc2f2e..31fc3d77b 100644--- a/backend/src/superTabs/buddyModel.ts+++ b/backend/src/superTabs/buddyModel.ts@@ -10,7 +10,8 @@* Whoever serves the model is told whose Buddy runs on it, and their limits hold (AGENTS.md, contributed capacity): a model that* hits a limit, keeps failing or is no longer served sends the Buddy back to its owner's subscription.*/-import { isSwarmBuddy, openSwarmBuddyChat, swarmBuddyChatId } from './buddies.js'+import { buddyChatOf, buddyChatsOf, defaultBuddy, defaultBuddyChat, isSwarmBuddy, swarmBuddyChatId } from './buddies.js'+import { mainBuddyOf, sessionAgentsOf } from './buddySessions.js'import { machineOffline, servedLocalModels } from './machines.js'import { fail, person, type Actor, type Agent, type SuperTabState } from './model.js'import { usernameOf } from './usernames.js'@@ -50,11 +51,14 @@ function served(state: SuperTabState, gridModel: string, now: number) {...(windows.length ? { contextWindow: Math.min(...windows) } : {}) }}-/** The person's own running Buddy for the Swarm: never a thread session, never someone else's. */-function ownBuddy(state: SuperTabState, actor: Actor): Agent {+/** The person's own running Buddy for the Swarm: never a thread session, never someone else's. With several (task #3818), the+ * one whose chat [conversationId] names, one of theirs, else their default. */+function ownBuddy(state: SuperTabState, actor: Actor, conversationId?: string): Agent {if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person switches their own Buddy.', 403)const me = person(state, actor.userId)- return mainBuddy(state, me.id, me.generation) ?? fail('NO_BUDDY', 'You have no Buddy running.', 404)+ const chat = conversationId ? buddyChatsOf(state, me).find(c => c.id === conversationId) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404) : undefined+ const buddy = chat ? mainBuddyOf(state, chat) : defaultBuddy(state, me.id) ?? mainBuddy(state, me.id, me.generation)+ return buddy ?? fail('NO_BUDDY', 'You have no Buddy running.', 404)}const mainBuddy = (state: SuperTabState, personId: string, generation: string) =>state.agents.find(a => isSwarmBuddy(a) && a.buddyOf!.personId === personId && a.buddyOf!.generation === generation && !a.buddySession)@@ -70,8 +74,8 @@ function switchable(state: SuperTabState, buddy: Agent, now: number): { ok: truereturn { ok: true }}-export function askBuddyModel(state: SuperTabState, actor: Actor, gridModel: string | null, requestId: string, now: number): void {- const buddy = ownBuddy(state, actor)+export function askBuddyModel(state: SuperTabState, actor: Actor, gridModel: string | null, requestId: string, now: number, conversationId?: string): void {+ const buddy = ownBuddy(state, actor, conversationId)const can = switchable(state, buddy, now)if (!can.ok) fail(can.code, can.message, 409)if (buddy.modelRequest) fail('BUDDY_SWITCHING', 'Your Buddy is already switching.', 409)@@ -86,7 +90,9 @@ export function askBuddyModel(state: SuperTabState, actor: Actor, gridModel: str* cannot carry it out (then its own lines say so: its model fails in its terminal, and the person can switch it). */export function sendBuddyHome(state: SuperTabState, from: Agent, reason: 'limit' | 'failing' | 'gone', requestId: string, now: number): void {if (!from.buddyOf) return- const buddy = mainBuddy(state, from.buddyOf.personId, from.buddyOf.generation)+ // The main Buddy of [from]'s own chat (task #3818: a person may have several), else theirs as before.+ const chat = buddyChatOf(state, from)+ const buddy = (chat && mainBuddyOf(state, chat)) ?? mainBuddy(state, from.buddyOf.personId, from.buddyOf.generation)if (!buddy?.gridModel || buddy.modelRequest || !switchable(state, buddy, now).ok) returnbuddy.modelRequest = { id: requestId, gridModel: null, name: current(state, buddy, now), reason,requestedBy: buddy.buddyOf!.personId, at: new Date(now).toISOString() }@@ -121,7 +127,9 @@ export function buddyModelResult(state: SuperTabState, actor: Actor,const hidden = hiddenMachines(state, buddy, request, now)delete buddy.modelRequestconst owner = buddy.buddyOf!- const conversationId = swarmBuddyChatId({ id: owner.personId, generation: owner.generation })+ // Its own chat (task #3818), where its owner talks with it.+ const chat = buddyChatOf(state, buddy)+ const conversationId = chat?.id ?? swarmBuddyChatId({ id: owner.personId, generation: owner.generation })const mine = (text: string): ModelLine[] => [{ conversationId, text, machines: hidden }]if (!command.ok) {return mine(`Couldn't switch your Buddy: ${clean(command.error ?? '') || 'it failed'}. It is still on ${current(state, buddy, now)}.`)@@ -129,7 +137,7 @@ export function buddyModelResult(state: SuperTabState, actor: Actor,delete buddy.gridModelUnservedSince// Its machine moved its thread sessions with it (cli superTabs/buddyModel.ts): what they run on is recorded the same way, so// costs and the serving member's "Used by" read it right.- const sessions = state.agents.filter(a => a.buddySession && a.buddyOf?.personId === owner.personId && a.buddyOf.generation === owner.generation)+ const sessions = chat ? sessionAgentsOf(state, chat) : state.agents.filter(a => a.buddySession && a.buddyOf?.personId === owner.personId && a.buddyOf.generation === owner.generation)for (const session of sessions) {if (request.gridModel === null) delete session.gridModelelse session.gridModel = request.gridModel@@ -164,7 +172,7 @@ export function buddyModelResult(state: SuperTabState, actor: Actor,const member = state.people.find(p => p.id === s.personId)if (!member) continue// No machine named: their own Buddy reads this chat, and a Buddy reads no machines.- theirs.push({ conversationId: openSwarmBuddyChat(state, member).id, machines: [],+ theirs.push({ conversationId: defaultBuddyChat(state, member).id, machines: [],text: `${personName(state, owner.personId)}'s Buddy now runs on ${name}, ${s.api ? 'on your saved API' : 'which your machine serves'}.` })}// The Buddy moved; a thread session that could not is named, so its owner knows where that thread's answers come from.@@ -179,7 +187,7 @@ export function expiredModelRequests(state: SuperTabState, now: number): Array<{const request = buddy.modelRequestif (!request || !buddy.buddyOf || now < Date.parse(request.at) + BUDDY_MODEL_LEASE_MS) continuedelete buddy.modelRequest- out.push({ buddy, requestId: request.id, conversationId: swarmBuddyChatId({ id: buddy.buddyOf.personId, generation: buddy.buddyOf.generation }),+ out.push({ buddy, requestId: request.id, conversationId: buddyChatOf(state, buddy)?.id ?? swarmBuddyChatId({ id: buddy.buddyOf.personId, generation: buddy.buddyOf.generation }),machines: hiddenMachines(state, buddy, request, now),text: `Couldn't switch your Buddy: its computer didn't answer. It is still on ${current(state, buddy, now)}.` })}diff --git a/backend/src/superTabs/buddyNews.ts b/backend/src/superTabs/buddyNews.tsindex 89a6eb27c..c018843d2 100644--- a/backend/src/superTabs/buddyNews.ts+++ b/backend/src/superTabs/buddyNews.ts@@ -2,7 +2,8 @@* proposal, tag them, or say work they requested shipped, and a notice when work they requested is assigned. Only while* the Buddy reads that conversation as its person would (projects.ts canReadGroup), checked again when its machine picks* the delivery up (store.ts deliveryAllowed). Nothing else of the project chat, and nothing private, reaches a Buddy. */-import { isBuddy, isBuddyChat, isSwarmBuddy, routingRow } from './buddies.js'+import { buddyChatOf, defaultBuddy, isBuddy, isBuddyChat, isSwarmBuddy, routingRow } from './buddies.js'+import { mainBuddyOf } from './buddySessions.js'import { agentOnly, isLeads, stableId, AGENT_ONLY, type Agent, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, canReadGroup, groupProject } from './projects.js'import { SHIP_KIND } from './ship.js'@@ -12,15 +13,26 @@ const PROPOSAL_KIND = 'buddy-proposal'/** [personId]'s Buddy in [group]'s project, when it reads [group] as its person would: never a private conversation, and* nothing once its person left, rejoined or stopped reading the project. */-function listeningBuddy(state: SuperTabState, personId: string, group: Conversation): Agent | undefined {+function listeningBuddy(state: SuperTabState, personId: string, group: Conversation, senderId?: string): Agent | undefined {const project = groupProject(state, group)- // The main Buddy alone: a thread session hears only its own thread (buddySessions.ts). Their one Buddy for the Swarm first- // (Dee, 10-31), else their older Buddy of that project.+ // The main Buddy alone: a thread session hears only its own thread (buddySessions.ts). The Buddy that sent the proposal while+ // it is still theirs (a session's own main Buddy), else their default (task #3818), else their older Buddy of that project.+ const person = state.people.find(p => p.id === personId)+ const sent = senderId ? state.agents.find(a => a.id === senderId) : undefined+ // A thread session that sent it stands for its own chat's main Buddy.+ const sentChat = sent?.buddySession ? buddyChatOf(state, sent) : undefined+ const main = sent?.buddySession ? sentChat && mainBuddyOf(state, sentChat) : sent+ const sender = main && person && isSwarmBuddy(main) && !main.buddySession && main.buddyOf!.personId === person.id+ && main.buddyOf!.generation === person.generation ? main : undefinedconst mains = state.agents.filter(a => isBuddy(a) && !a.buddySession && a.buddyOf!.personId === personId)- const buddy = mains.find(a => isSwarmBuddy(a)) ?? mains.find(a => agentProjectId(state, a) === project.id)+ const buddy = sender ?? defaultBuddy(state, personId) ?? mains.find(a => isSwarmBuddy(a)) ?? mains.find(a => agentProjectId(state, a) === project.id)return buddy && canReadGroup(state, { kind: 'agent', agentId: buddy.id, machineOwnerId: buddy.machineOwnerId }, group) ? buddy : undefined}+/** The Buddy that sent the proposal [message]'s thread answers, when it does (task #3818): its news goes back to that one. */+const senderOf = (message: MessageDraft, threadSource: Record<string, unknown> | null): string | undefined =>+ message.replyTo && threadSource?.kind === PROPOSAL_KIND && typeof threadSource.buddyId === 'string' ? threadSource.buddyId : undefined+/** The people a project-chat row is news for: whoever's proposal its thread answers, each person it tags, and who requested* the work it says shipped. Never its own author: they know what they wrote. */function newsFor(message: MessageDraft, threadSource: Record<string, unknown> | null): string[] {@@ -36,7 +48,8 @@ function newsFor(message: MessageDraft, threadSource: Record<string, unknown> |export function buddiesTold(state: SuperTabState, message: MessageDraft, threadSource: Record<string, unknown> | null): string[] {const group = state.conversations.find(c => c.id === message.conversationId)if (!group || isLeads(group) || isBuddyChat(group) || agentOnly(message.source, message.recipients) || routingRow(message.source) || groupProject(state, group).leadConversationId !== group.id) return []- return newsFor(message, threadSource).flatMap(id => listeningBuddy(state, id, group)?.id ?? [])+ const sender = senderOf(message, threadSource)+ return newsFor(message, threadSource).flatMap(id => listeningBuddy(state, id, group, id === threadSource?.personId ? sender : undefined)?.id ?? [])}/** Marks who of the Buddies hears [message]: a delivery each, kept off its recipients so readers never see whose Buddy listens. */diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 484a38fb3..144f768bf 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -66,7 +66,7 @@ import { recordClosing, sessionClosed } from './closedAgents.js'import { declinedWith, declinedWithout } from './sharing.js'import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'-import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, okayedWords, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalBrief, proposalSentText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'+import { BUDDY_REQUIREMENTS, buddyCapOf, buddyCapRefusal, buddyChatId, buddyChatOf, buddyChatsOf, buddyCount, defaultBuddy, defaultBuddyChat, hasBuddy, dropBuddyChat, MAX_BUDDY_CAP, openNewBuddyChat, setDefaultBuddy, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, okayedWords, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalBrief, proposalSentText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'@@ -228,6 +228,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('swarm.delete'), name: z.string().max(160) }).strict(),z.object({ type: z.literal('swarm.restore') }).strict(),z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSaveSchema.nullable() }).strict(),+ // The most Buddies a person may have in this Swarm (buddies.ts BUDDY_CAP), set by its owner (task #3818).+ z.object({ type: z.literal('tab.buddyCap'), cap: z.number().int().min(1).max(MAX_BUDDY_CAP) }).strict(),z.object({ type: z.literal('tab.tidy'), 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(),@@ -335,7 +337,10 @@ export const commandSchema = z.discriminatedUnion('type', [scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']),attachmentIds: z.array(id).max(MAX_PROPOSAL_ATTACHMENTS, `Attach at most ${MAX_PROPOSAL_ATTACHMENTS} files to a proposal.`).optional() }).strict(),// Without `projectId`, the person's one Buddy (Dee, 10-31); an older app names a project, and removes that same one Buddy.- z.object({ type: z.literal('buddy.remove'), projectId: id.optional() }).strict(),+ // `conversationId`: which of the person's Buddies, by its chat (task #3818); without it, their default.+ z.object({ type: z.literal('buddy.remove'), projectId: id.optional(), conversationId: id.optional() }).strict(),+ // The person's default Buddy, by its chat (task #3818): their lines and what is asked of them go to it.+ z.object({ type: z.literal('buddy.default'), conversationId: id }).strict(),// A Buddy's proposal closed by hand, with its reason: out of the open proposals, posting nothing (River 11-04, task #2926).z.object({ type: z.literal('proposal.close'), projectId: id, messageId: id, reason: z.string().trim().min(1).max(200) }).strict(),// A person's one Buddy chat in the Swarm, opened before any Buddy is (buddies.ts openSwarmBuddyChat); with `projectId`, their@@ -346,7 +351,8 @@ export const commandSchema = z.discriminatedUnion('type', [// A person ends a thread session of their own Buddy chat (buddySessions.ts): `ended` from their app, `idle` and `stopped` from// their machine's host, which acts as them. Idempotent: a thread with no session is told so and nothing changes.// The person's own Buddy onto a model the Swarm's grid serves now, or back to their subscription (null): buddyModel.ts.- z.object({ type: z.literal('buddy.model'), gridModel: z.string().trim().min(1).max(200).nullable() }).strict(),+ // `conversationId`: which of the person's Buddies, by its chat (task #3818); without it, their default.+ z.object({ type: z.literal('buddy.model'), gridModel: z.string().trim().min(1).max(200).nullable(), conversationId: id.optional() }).strict(),// What the Buddy's machine reports once it carried the request out: `fresh` when the conversation was too long for the model.z.object({ type: z.literal('buddy.modelResult'), agentId: id, requestId: id, ok: z.boolean(), fresh: z.boolean().optional(),error: z.string().max(300).optional() }).strict(),@@ -358,8 +364,11 @@ export const commandSchema = z.discriminatedUnion('type', [// engines): it is recorded Buddy-only (machines.ts ContributedMachine.buddyOnly). Ignored for a machine already listed.// Without `projectId`, the person's one Buddy for the Swarm (Dee, 10-31); an older app's Start names a project, and adds that// same one Buddy.+ // Several Buddies (task #3818): `name` and no `conversationId` adds a new one in its own chat, within the Swarm's cap;+ // `conversationId` starts that one of the person's Buddies again; neither, the default, as before.z.object({ type: z.literal('buddy.create'), projectId: id.optional(), machineId: id, engine: swarmEngine, model: z.string().trim().min(1).max(200).optional(),- setup: z.object({ name: title, cwd: path, engines: z.array(swarmEngine).min(1).max(2) }).strict().optional() }).strict(),+ setup: z.object({ name: title, cwd: path, engines: z.array(swarmEngine).min(1).max(2) }).strict().optional(),+ name: z.string().max(200).optional(), conversationId: id.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(),@@ -788,7 +797,9 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS/** Also checked before returning an idempotent receipt: a retry does not retain* access after the person has been removed from a private project. *//** What may name a person's one Buddy chat: posts, reactions, proposals, naming the Buddy and ending a session. */-const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'message.edit', 'message.delete', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd'])+const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'message.edit', 'message.delete', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd',+ // Which of a person's several Buddies (task #3818).+ 'buddy.create', 'buddy.remove', 'buddy.default', 'buddy.model'])export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return@@ -804,7 +815,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, commaconst buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefinedif (buddy) requireBuddyCommand(buddy, command, state.conversations)// 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') {+ // A Buddy command names a chat only to pick one of the person's Buddies (task #3818): without one, it names none.+ if ('conversationId' in command && command.conversationId && command.type !== 'invite.create') {const group = readConversation(state, actor, command.conversationId)// A person's one Buddy chat is for talking with their Buddy: no task, member or archive there (Dee, 10-31).if (isSwarmBuddyChat(group) && !SWARM_BUDDY_CHAT_COMMANDS.has(command.type)) fail('BUDDY_CHAT_ONLY', 'Your Buddy chat is for talking with your Buddy.', 403)@@ -921,8 +933,10 @@ function proposalOf(state: SuperTabState, project: SwarmProject, proposal: Propo// membership. Without a one Buddy (removed since), the author keeps it.const gone = !buddy ? state.people.find(p => p.id === personId) : undefinedconst owner = buddy?.buddyOf ?? (gone ? { personId: gone.id, generation: gone.generation } : undefined)+ // With several Buddies (task #3818): the main Buddy of the session's own chat, else (its chat gone) the person's default.+ const sessionChat = buddy?.buddySession ? buddyChatOf(state, buddy) : undefinedconst main = owner && !(buddy && isSwarmBuddy(buddy) && !buddy.buddySession)- ? state.agents.find(a => isSwarmBuddy(a) && !a.buddySession && a.buddyOf!.personId === owner.personId && a.buddyOf!.generation === owner.generation)+ ? (sessionChat && mainBuddyOf(state, sessionChat)) ?? (owner.generation === state.people.find(p => p.id === owner.personId)?.generation ? defaultBuddy(state, owner.personId) : undefined): undefinedreturn { buddyId: main?.id ?? buddyId!, messageId: proposal.id, ...personId ? { personId } : {} }}@@ -1464,7 +1478,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,delete chat.buddyDownToldreturn}- const main = state.agents.find(a => isSwarmBuddy(a) && !a.buddySession && a.buddyOf!.personId === owner.id && a.buddyOf!.generation === owner.generation)+ // The person's default Buddy answers in their older project chats (task #3818).+ const main = owner.generation === state.people.find(p => p.id === owner.id)?.generation ? defaultBuddy(state, owner.id) : undefinedif (!main) returnconst pool = machineContribution(state, main.machineId), machine = pool?.name ?? 'my machine'if (state.paused) return 'the Swarm is paused'@@ -1502,7 +1517,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const buddyDownLine = (chat: Conversation, why: string) => {if (chat.buddyDownTold) returnconst owner = chatOwner(chat)- const main = owner && state.agents.find(a => isSwarmBuddy(a) && !a.buddySession && a.buddyOf!.personId === owner.id && a.buddyOf!.generation === owner.generation)+ const main = owner && owner.generation === state.people.find(p => p.id === owner.id)?.generation ? defaultBuddy(state, owner.id) : undefinedif (!main) returnchat.buddyDownTold = trueeffects.messages.push({ id: stableId(operationId, BUDDY_DOWN_SOURCE), conversationId: chat.id, replyTo: null, recipients: [],@@ -1554,8 +1569,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,delete chat.buddySessions}}- // The one Buddy takes its sessions in the person's older project chats with it (startOldChatBuddy).- if (isSwarmBuddy(target) && !target.buddySession) {+ // The default Buddy takes its sessions in the person's older project chats with it (startOldChatBuddy); another of their+ // Buddies leaves them to the default (task #3818).+ if (isSwarmBuddy(target) && !target.buddySession && defaultBuddy(state, target.buddyOf!.personId)?.id === target.id) {for (const other of state.agents.filter(a => a.buddyNarrow && !a.buddySession && a.buddyOf?.personId === target.buddyOf!.personId)) removeAgent(other)for (const start of state.starts ?? []) {if (start.request.buddyNarrow && !start.request.buddySession && start.request.buddyOf?.personId === target.buddyOf!.personId && !start.harnessId && !start.error) {@@ -2111,7 +2127,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const to = person(state, personId)const text = approvedDropNotice(who, project, rules)const id = stableId(operationId, 'rule-approved', personId)- message(openSwarmBuddyChat(state, to).id, text, [], null, { kind: PM_LINE_KIND, projectId: project.id }, undefined, undefined, undefined, id)+ message(defaultBuddyChat(state, to).id, text, [], null, { kind: PM_LINE_KIND, projectId: project.id }, undefined, undefined, undefined, id)Object.assign(effects.messages.at(-1)!, { buddyProject: project.id })effects.messages.push({ id: stableId(id, 'project-chat'), conversationId: openBuddyChat(state, project.id, to).id, author: sender, text, replyTo: null, recipients: [] })}@@ -2459,7 +2475,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const names = leaving.map(a => a.displayName ?? a.name)const join = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]const signedIn = newOwner ? `signed in as ${usernameOf(state, newOwner.id) ?? 'another account'}` : 'signed in to another account'- effects.messages.push({ id: stableId(operationId, 'computer-moved'), conversationId: openSwarmBuddyChat(state, person(state, pool.contributorId)).id,+ effects.messages.push({ id: stableId(operationId, 'computer-moved'), conversationId: defaultBuddyChat(state, person(state, pool.contributorId)).id,author: sender, replyTo: null, recipients: [], source: { kind: 'computer-moved', machineId: pool.machineId },text: `Your ${pool.name} is ${signedIn} now, so it left this Swarm under your account${join ? `, and ${join} with it` : ''}.` })result.moved = true@@ -2525,6 +2541,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can change its routing policy.', 403)ignored()break+ case 'tab.buddyCap':+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm\'s owner sets how many Buddies each person may have.', 403)+ state.buddyCap = command.cap+ breakcase 'rule.set': {// An older CLI's rule: its words become one more line of the project's Routing, saved as any change to the instructions// (project instructions, phase 4, decision 3). The rule itself is kept nowhere.@@ -3076,27 +3096,47 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Without a project, the person's one Buddy; with one (an older app), the Buddy of their older chat there, never the one// Buddy (spec: Older apps).const project = command.projectId ? readProject(state, actor, command.projectId) : undefined- const chatId = project ? buddyChatId(project.id, me) : swarmBuddyChatId(me)+ // Which of their Buddies (task #3818): the one whose chat is named, one of their own; else their default.+ const chosen = project ? undefined : command.conversationId+ ? buddyChatsOf(state, me).find(c => c.id === command.conversationId) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404)+ : defaultBuddyChat(state, me)+ const chatId = project ? buddyChatId(project.id, me) : chosen!.idconst target = state.agents.find(a => a.buddyOf?.personId === me.id && !a.buddySession && state.conversations.some(c => c.id === chatId && c.agentIds.includes(a.id)))const starting = state.starts?.filter(s => s.request.conversationId === chatId && !s.harnessId && !s.error) ?? []+ // A chat of theirs with no Buddy left in it (its start failed) is cleared when they remove it; their main chat stays.+ if (!target && !starting.length && chosen && chosen.id !== swarmBuddyChatId(me)) {+ dropBuddyChat(state, me, chosen)+ break+ }if (!target && !starting.length) fail('NOT_FOUND', project ? 'You have no Buddy in this project.' : 'You have no Buddy.', 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.+ // Its session closes. The main chat stays, and adding a Buddy again reopens it; another Buddy's chat is archived, and a+ // removed default passes to the oldest Buddy left (buddies.ts dropBuddyChat).if (target) removeAgent(target)+ if (chosen) dropBuddyChat(state, me, chosen)+ break+ }+ case 'buddy.default': {+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person picks their own default Buddy.', 403)+ const me = person(state, actor.userId)+ const chat = buddyChatsOf(state, me).find(c => c.id === command.conversationId) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404)+ // Their lines go to the default: never a chat with no Buddy running or starting in it (review of #3818).+ if (!hasBuddy(state, me, chat)) fail('NO_BUDDY', 'That chat has no Buddy. Add one there first.', 409)+ setDefaultBuddy(state, me, chat)break}case 'buddy.chat': {if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person opens their own Buddy chat.', 403)// With no project, the person's one Buddy chat (Dee, 10-31); with one, their older chat there, which older apps show.result.conversationId = command.projectId ? openBuddyChat(state, readProject(state, actor, command.projectId).id, person(state, actor.userId)).id- : openSwarmBuddyChat(state, person(state, actor.userId)).id+ : defaultBuddyChat(state, person(state, actor.userId)).idbreak}case 'buddy.rename':renameBuddy(state, actor, readConversation(state, actor, command.conversationId), command.name, context.buddyNames)breakcase 'buddy.model':- askBuddyModel(state, actor, command.gridModel, operationId, context.now)+ askBuddyModel(state, actor, command.gridModel, operationId, context.now, command.conversationId)breakcase 'buddy.modelResult': {// The machines a line names leave a Buddy's read of it (store.ts withoutMachineNames): a Buddy reads no machines.@@ -3110,12 +3150,16 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}case 'buddy.sessionEnd': {if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person ends their own Buddy session.', 403)- const chat = readConversation(state, actor, command.conversationId)- requireChatOwner(state, chat, actor.userId)- const entry = sessionOf(state, chat, command.thread)- result.ended = !!entry- if (!entry) break- endBuddySession(chat, entry, command.reason)+ const named = readConversation(state, actor, command.conversationId)+ requireChatOwner(state, named, actor.userId)+ // An older host names the person's main Buddy chat for every session (task #3818): a thread of another of their Buddies is+ // found in that Buddy's own chat.+ const me = person(state, actor.userId)+ const chats = named.id === swarmBuddyChatId(me) ? [named, ...buddyChatsOf(state, me).filter(c => c.id !== named.id)] : [named]+ const found = chats.map(chat => ({ chat, entry: sessionOf(state, chat, command.thread) })).find(hit => hit.entry)+ result.ended = !!found+ if (!found) break+ endBuddySession(found.chat, found.entry!, command.reason)break}case 'person.tell': {@@ -3135,7 +3179,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// To nobody: the person reads it; their Buddy, if they have one, is not asked to answer for them. In their one Buddy chat,// marked with its project so it hides once they lose it (buddies.ts hiddenProjectRow), and in their older chat there,// which older apps and the phone still show (spec: Older apps).- message(openSwarmBuddyChat(state, to).id, command.text, [], null, { kind: PM_LINE_KIND, projectId: project.id })+ message(defaultBuddyChat(state, to).id, command.text, [], null, { kind: PM_LINE_KIND, projectId: project.id })Object.assign(effects.messages.at(-1)!, { buddyProject: project.id })effects.messages.push({ id: stableId(operationId, 'project-chat'), conversationId: openBuddyChat(state, project.id, to).id, author: sender,text: command.text, replyTo: null, recipients: [] })@@ -3147,10 +3191,24 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// One Buddy per person per Swarm (Dee, 10-31). An older app's Start names a project it reads: it adds that same one Buddy.if (command.projectId) readProject(state, actor, command.projectId)const me = person(state, actor.userId)- const chatId = swarmBuddyChatId(me)+ // Which Buddy (task #3818): one of the person's own, by its chat; a new one, named, in the main chat while no Buddy is there,+ // else in a chat of its own, within the Swarm's cap; neither, the default, as before several.+ const own = buddyChatsOf(state, me)+ const occupied = (chat: Conversation) => hasBuddy(state, me, chat)+ const main = own.find(c => c.id === swarmBuddyChatId(me))+ // A new one takes the first of their chats with no Buddy in it (the main chat first, then one whose start failed: review of+ // #3818), so failed starts never pile up chats; else a chat of its own.+ const picked = command.conversationId ? own.find(c => c.id === command.conversationId) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404)+ : command.name === undefined ? defaultBuddyChat(state, me) : own.find(c => !occupied(c))+ // The cap counts every start that adds a Buddy: into a new chat, or into one of theirs with none in it (a failed start+ // retried, their main chat left empty). Only a start that replaces a Buddy already there adds none (review of #3818).+ if ((!picked || !occupied(picked)) && buddyCount(state, me) >= buddyCapOf(state)) fail('BUDDY_CAP', buddyCapRefusal(buddyCapOf(state)), 409)+ const chat = picked ?? (main ? openNewBuddyChat(state, me, stableId('buddy', 'swarm', me.id, me.generation, operationId)) : openSwarmBuddyChat(state, me))+ const chatId = chat.id+ if (command.name !== undefined) renameBuddy(state, actor, chat, command.name, context.buddyNames)// 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 => isSwarmBuddy(a) && a.buddyOf!.personId === me.id && !a.buddySession)+ const existing = state.agents.find(a => isSwarmBuddy(a) && a.buddyOf!.personId === me.id && !a.buddySession && chat.agentIds.includes(a.id))if ((existing && !downSince(state, existing, context.now))|| state.starts?.some(s => s.request.conversationId === chatId && !s.request.buddySession && !s.harnessId && !s.error)) {fail('BUDDY_EXISTS', 'You already have a Buddy. Remove it to add another.')@@ -3160,8 +3218,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Found by the agent, never by its chat, which may be quiet and not loaded here: every main Buddy of theirs that is not the// one Buddy is an older chat's.for (const old of state.agents.filter(a => a.buddyOf?.personId === me.id && !isSwarmBuddy(a) && !a.buddySession)) removeAgent(old)+ // Only an older project chat's start: another of their Buddies' (task #3818) keeps starting.for (const start of state.starts ?? []) {- if (start.request.buddyOf?.personId === me.id && start.request.conversationId !== chatId && !start.harnessId && !start.error) start.error = 'Your Buddy is now one for the whole Swarm.'+ if (start.request.buddyOf?.personId === me.id && !state.conversations.some(c => c.id === start.request.conversationId && isSwarmBuddyChat(c))+ && !start.harnessId && !start.error) start.error = 'Your Buddy is now one for the whole Swarm.'}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@@ -3185,7 +3245,6 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// A slot for its person's Buddy there and its sessions: it takes nothing else.if (pool.buddyOnly) pool.maxAgents = machineSlots(state, pool) + 1const contributor = person(state, grant.contributorId)- const chat = openSwarmBuddyChat(state, me)const named = chosenBuddyName(state, chat, me, context.buddyNames)// 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,@@ -3598,7 +3657,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (moved && label && asked && owner && asked !== owner.id) {// The owner's Buddy reads it: by name, never email (review of #2954).const who = agentWrittenNameOf(state, asked) ?? 'Someone'- effects.messages.push({ id: stableId(operationId, 'pm-switch-notice'), conversationId: openSwarmBuddyChat(state, owner).id, author: sender, replyTo: null, recipients: [],+ effects.messages.push({ id: stableId(operationId, 'pm-switch-notice'), conversationId: defaultBuddyChat(state, owner).id, author: sender, replyTo: null, recipients: [],source: { kind: 'pm-switch-notice', machineId: target.machineId },text: `${who} moved the PM of ${project.name} on ${pool?.name ?? target.machineId} to your ${engine} account "${label}".` })}diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex ff30b601a..dbe321ac4 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -3,7 +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: the PM's private lines go* to the person's Buddy chat (buddies.ts). Called inside SuperTabStore's transactions. */-import { isBuddy, isSwarmBuddy, openBuddyChat, openSwarmBuddyChat } from './buddies.js'+import { defaultBuddyChat, isBuddy, isSwarmBuddy, openBuddyChat } from './buddies.js'import { usernameOf } from './usernames.js'import { agentWrittenNameOf } from './personNames.js'import { createHash } from 'node:crypto'@@ -183,7 +183,7 @@ function delegatedLine(state: SuperTabState, projectId: string, leadId: string,const question = asked.question.replace(/\s+/g, ' ')const text = `${defaulted ? `Default applied: ${asked.options[choice]!}` : answerText(asked.options[choice]!, true)} — ${question}`// In their one Buddy chat, marked with its project (Dee, 10-31), and in their older chat there for older apps.- return [{ conversationId: openSwarmBuddyChat(state, to).id, author, text, source: { kind: 'decision-delegated', decisionId: asked.id, projectId }, buddyProject: projectId },+ return [{ conversationId: defaultBuddyChat(state, to).id, author, text, source: { kind: 'decision-delegated', decisionId: asked.id, projectId }, buddyProject: projectId },{ conversationId: openBuddyChat(state, projectId, to).id, author, text, source: { kind: 'decision-delegated', decisionId: asked.id } }]}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 9919c74d7..2123891ca 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -469,6 +469,12 @@ export interface Conversation {/** The name a Buddy chat's owner chose for their Buddy (buddies.ts renameBuddy): kept here, which outlives the Buddy, so* one added again takes it. Absent: the default, "<person>'s Buddy". */buddyName?: string+ /** A person's main Buddy chat (buddies.ts swarmBuddyChatId) lists their other Buddies' chats, oldest first, so they load+ * with it, whose id every command can derive (task #3818). At most the Swarm's Buddy cap. Absent: one Buddy. */+ buddyChats?: string[]+ /** This Buddy chat's Buddy is its person's default (task #3818): their lines go to it. One per person; with none marked, the+ * main chat's. */+ buddyDefault?: true/** A Buddy chat's live and starting thread sessions (buddySessions.ts); absent while it has none. */buddySessions?: BuddySessionEntry[]/** An older project Buddy chat whose person was told their one Buddy cannot start there now (commands.ts buddyDownLine):@@ -634,6 +640,8 @@ export interface SuperTabState {deletion?: { at: string; by: string; purgeAt: string }/** Idle workers stop and finished groups archive by themselves (tidy.ts); false once the owner turns it off. */tidy?: false+ /** The most Buddies a person may have in this Swarm (buddies.ts BUDDY_CAP), set by its owner (task #3818). */+ buddyCap?: number/** Buddies (buddies.ts) are on in every Swarm; readers are always told so (visibleState), as apps from before 10-29 hide* Buddies and show Chat with PM without it. A stored value from the old switch is ignored. */buddies?: truediff --git a/backend/src/superTabs/othersWork.ts b/backend/src/superTabs/othersWork.tsindex c9c2fa052..42a514fc4 100644--- a/backend/src/superTabs/othersWork.ts+++ b/backend/src/superTabs/othersWork.ts@@ -4,7 +4,7 @@* the server's words; the person card shows the rest. Someone else's work is what Lent counts (leaderboard/lent.ts): a* task its machine's contributor did not ask for, never a PM's or a private chat's.*/-import { openSwarmBuddyChat } from './buddies.js'+import { defaultBuddyChat } from './buddies.js'import { homeOf, weeklyUse } from './leaderboard/brought.js'import { weekStart } from './leaderboard/week.js'import { isLeads, type Agent, type Conversation, type SuperTabState } from './model.js'@@ -39,7 +39,7 @@ export function othersWorkNotice(state: SuperTabState, group: Conversation, workconst readable = canReadProject(state, { kind: 'person', userId: owner.id, email: owner.email }, groupProject(state, group))const use = weeklyUse(home, worker.configuration.engine)const used = use.usedPercent == null ? '' : `, ${Math.round(use.usedPercent)}% of this week used${use.resetsAt == null ? '' : `, resets in ${until(use.resetsAt, now)}`}`- return { conversationId: openSwarmBuddyChat(state, owner).id, machineId: pool.machineId,+ return { conversationId: defaultBuddyChat(state, owner).id, machineId: pool.machineId,text: `${requester ? `${requester}'s` : 'A teammate\'s'} work${readable ? ` "${group.title}"` : ''} started on your ${home.name} (${engineName}${used}). `+ 'Members › your card shows what it runs and ships; Manage › Machines can pause new work.' }}diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 5c4e72ef3..fc41983af 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -36,6 +36,8 @@ const conversation: Required<Conversation> = {audience: { people: [] },brief: '',briefAt: 1,+ buddyChats: ['other'],+ buddyDefault: true,buddyDownTold: true,buddyName: 'Sparky',buddySessions: [],diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 626130572..442b5b159 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -65,6 +65,8 @@ export const GROUP_FIELDS = {'assignment.verdicts','brief','briefAt',+ 'buddyChats',+ 'buddyDefault','buddyDownTold','buddyName','buddySessions',diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 5a55b93c6..f54ce6b1b 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -27,7 +27,11 @@ export type GroupChange = LivePart<GroupView> | Tombstone | DormantStub* (autoJoin.ts), from the sharing the head holds; who declined is never sent. */export type HeadView = Pick<SuperTabState, 'version' | 'id' | 'name' | 'project' | 'projects' | 'leadsConversationId' | 'ownerId'| 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility' | 'buddies' | 'removedMachines'- | 'autoJoin'>+ | 'autoJoin'> & {+ /** How many Buddies each person may have (task #3818): always sent, 5 unless the Swarm's owner set another. An older backend+ * sends none, so an app offers several Buddies only where this is present. */+ buddyCap: number+}/** 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@@ -299,6 +303,9 @@ export interface HostAgentRow {* names that loss, since one task can be lost, resumed and lost again. */resume: { conversationId: string; assignmentId: string; lostAt: number; at: string } | nullagent: Agent+ /** A Buddy's own chat, its main one's or the thread session's (task #3818): its host ends a session and moves a model switch+ * there. Absent on every other agent; null while its chat is not loaded. An older backend sends none: the person's main chat. */+ buddyChatId?: string | nulljoinSwarm: booleanskillMode: 'default' | 'orchestration'role?: { id: string; name: string; kind: string; version: string; projectId: string } | nulldiff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.tsindex c2a3319a3..7eb8841c2 100644--- a/backend/src/superTabs/read/hostRows.ts+++ b/backend/src/superTabs/read/hostRows.ts@@ -5,7 +5,7 @@*/import type { AuthUser } from '../../lib/ssoAuth.js'import { activeWork, agent, isLeads, SuperTabError, conversation, type Agent, type SuperTabState } from '../model.js'-import { isSwarmBuddyChat } from '../buddies.js'+import { buddyChatOf, isSwarmBuddy, isSwarmBuddyChat } from '../buddies.js'import { hostLocalGrid, machineContribution, machineLimitReached, machineRoom, type MachineCleanup } from '../machines.js'import { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, startProject, skillSetOf, watchClosed } from '../projects.js'import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contract.js'@@ -113,6 +113,8 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:confidential: isConfidential(state, target, closed),// But for this Swarm's current Lead: its listed observers watch it while this row is in force (Ken, 2026-10-28).membersWatch: isConfidential(state, target, closed) && !watchClosed(state, target, closed),+ // Which of its person's Buddies' chats it is in (task #3818).+ ...isSwarmBuddy(target) || (target.buddySession && target.buddyOf) ? { buddyChatId: buddyChatOf(state, target)?.id ?? null } : {},}}diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.tsindex eca63bcc9..cecc2ae5d 100644--- a/backend/src/superTabs/read/views.test.ts+++ b/backend/src/superTabs/read/views.test.ts@@ -34,6 +34,15 @@ const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machinconst keys = (list: Array<{ key: string }>) => list.map(p => p.key)describe('reader view of the parts (design 4.1, 4.3)', () => {+ // Task #3818 (Desktop's ask, #3820): the head always says how many Buddies a person may have, so an app tells a backend that+ // makes several from an older one, which sends none.+ it('always sends the Swarm\'s Buddy cap: its owner\'s number, else the default', () => {+ const { s } = scene()+ const head = (state: typeof s.state) => readerView(store.split(state, { tabId: 'tab', version: R, now: NOW }), peer, NOW, { teamMachines: [] }).parts.head.data+ expect(head(s.state).buddyCap).toBe(5)+ expect(head({ ...s.state, buddyCap: 3 }).buddyCap).toBe(3)+ })+it('sends the head without owner-only and internal fields, and projects without their progress', () => {const { parts } = scene()const { head } = readerView(parts, peer, NOW, { teamMachines: [] }).partsdiff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 02372ca35..3afec997f 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -7,7 +7,7 @@ import { machineSuspensionReason, suspendedEngines } from '../engineHealth.js'import { DISPATCH_RULES, laneOf } from '../dispatch.js'import { leadChoices } from '../leadStart.js'import { heldView } from '../heldReason.js'-import { isBuddyChat, isBuddyReader } from '../buddies.js'+import { buddyCapOf, isBuddyChat, isBuddyReader } from '../buddies.js'import { agentForBuddy, agentWithoutMachine, groupForBuddy, machineHiddenFrom, seenMachineIds, visibleState, withSeenRequirement, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'import { availableSlots, slotCounter, machineTeamWork, type ContributedMachine } from '../machines.js'import * as store from '../parts/index.js'@@ -61,7 +61,9 @@ export interface ReadExtras {}const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',- 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility', 'buddies', 'removedMachines', 'autoJoin'] as const+ 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility', 'buddies', 'removedMachines', 'autoJoin',+ // How many Buddies each person may have (task #3818): apps offer a new one below it.+ 'buddyCap'] as constexport const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, data: T): LivePart<T> =>({ key: part.key, version: part.version, changedAt: part.changedAt, data })@@ -109,6 +111,9 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:// no reader shows them. What the PM owes is its host's alone (timeChecks.ts owedAsk): it may name a message in someone's private chat.if (head.projects) head.projects = head.projects.map(({ progress: _progress, schedule: _schedule, releases: _releases, owed: _owed, ...project }) => ({ ...project, coordinatorName: coordinatorNameOf(project) }))head.invitations = visible.invitations.filter(i => readable.has(i.conversationId))+ // Always, its default too (task #3818): an app offers several Buddies only where the head says how many, so an older backend,+ // which sends none, is never taken for one that makes them.+ head.buddyCap = buddyCapOf(state)const projects = new Set((visible.projects ?? []).map(p => p.id)), seen = seenMachineIds(visible), names = swarmUsernames(state)const buddy = isBuddyReader(state, actor)return {diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 7ad39d82b..7a459d16b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -46,7 +46,7 @@ import { logger } from '../utils/logger.js'import { noteClaim, recordDeliveryCall } from '../lib/deliveryCalls.js'import { retryTransient } from './retry.js'import { recordReload } from './retryStats.js'-import { buddyChatId, shownBefore, swarmBuddyChatId, type ChosenBuddyName } from './buddies.js'+import { buddyChatId, isSwarmBuddyChat, shownBefore, swarmBuddyChatId, type ChosenBuddyName } from './buddies.js'import { cleanPullRequestLinks } from './cards.js'import { accountOf, wordsOf, buddyInstructionsProject, canReadAgent, canReadGroup, groupRepositoryUrl, canWatchAgent, groupProject, ledProject, onTeamAccount, ownerAccount, ownsProject, admitPerson, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey, GITHUB_SEEN, type GitHubSeen, type RepositoryCreation, repositoryCreator, type SwarmProject } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'@@ -1014,6 +1014,8 @@ export class SuperTabStore {// And their one Buddy chat, which takes it too (spec: Guard).if (asked && command.delegate) swarmChat(asked.personId)}+ // A private line from an agent goes to the person's default Buddy (task #3818): their Buddy chats, quiet or not.+ if (command.type === 'person.tell') swarmChat(command.personId)// A switch's result tells the machine's owner in their one Buddy chat, quiet or not (commands.ts agent.switchResult).if (command.type === 'agent.switchResult') swarmChat(state.agents.find(a => a.id === command.agentId)?.machineOwnerId)// A project's sharing ends its sessions in the one Buddy chats of whoever loses it (commands.ts endLostProjectSessions).@@ -1743,7 +1745,10 @@ export class SuperTabStore {// A Workspace removal leaves a deleted Swarm too, so its restore cannot bring the person back (security review 2 of #2457).const leavingDeleted = workspaceLeave && command.type === 'member.remove' && command.userId === user.sub && !asAgentIdconst first = await this.load(tx, user, tabId, namedFor(command), DELETED_SWARM_COMMANDS.has(command.type) || leavingDeleted)- const loaded = await this.ensure(tx, first, await this.moreNamed(tx, tabId, first.state, command, asAgentId ? null : user.sub, asAgentId))+ const named = await this.ensure(tx, first, await this.moreNamed(tx, tabId, first.state, command, asAgentId ? null : user.sub, asAgentId))+ // A person's other Buddies' chats load with their main one, which lists them (task #3818): a command that reads that person's+ // Buddies, their default's chat included, reads all of them. Nothing more is read when none is listed.+ const loaded = await this.ensure(tx, named, { groupIds: listedBuddyChats(named.state) })const original = loaded.stateconst team = await this.teamHost(tx, user)// Removal retries can arrive after the actor itself left. Return only this host's exact prior receipt.@@ -5647,9 +5652,19 @@ export async function buddyNames(tx: Transaction, tabId: string, state: SuperTabconst keys = [...projectsOf(state).flatMap(project => state.people.map(person => buddyChatId(project.id, person))),...state.people.map(person => swarmBuddyChatId(person))]if (!keys.length) return []- const rows = await groupsBy(tx, 'key', [- { $match: { tabId, key: { $in: keys }, deleted: false, 'data.buddyName': { $gt: '' } } },- { $project: { _id: 0, key: 1, name: '$data.buddyName' } },- ]) as Array<{ key: string; name: string }>- return rows.map(row => ({ conversationId: row.key, name: row.name }))+ const named = (match: Record<string, unknown>) => groupsBy(tx, 'key', [+ { $match: { tabId, deleted: false, ...match } },+ { $project: { _id: 0, key: 1, name: '$data.buddyName', chats: '$data.buddyChats' } },+ ]) as Promise<Array<{ key: string; name?: string; chats?: string[] }>>+ // A main Buddy chat may list a person's other Buddies' chats (task #3818), whose ids no one derives: they are read by those keys.+ const rows = await named({ key: { $in: keys }, $or: [{ 'data.buddyName': { $gt: '' } }, { 'data.buddyChats.0': { $exists: true } }] })+ const listed = rows.flatMap(row => row.chats ?? [])+ const more = listed.length ? await named({ key: { $in: listed }, 'data.buddyName': { $gt: '' } }) : []+ return [...rows, ...more].flatMap(row => row.name ? [{ conversationId: row.key, name: row.name }] : [])+}++/** The Buddy chats listed on [state]'s loaded main Buddy chats (task #3818) that are not loaded yet. */+function listedBuddyChats(state: SuperTabState): string[] {+ const loaded = new Set(state.conversations.map(c => c.id))+ return [...new Set(state.conversations.filter(isSwarmBuddyChat).flatMap(c => c.buddyChats ?? []))].filter(id => !loaded.has(id))}diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.tsindex f373c7bc1..2737bc00e 100644--- a/cli/src/superTabs/cards.spec.ts+++ b/cli/src/superTabs/cards.spec.ts@@ -2061,6 +2061,14 @@ describe('one Buddy per Swarm', () => {leadsOf(state, 'm1', idle, 'me', focus, side).leads.find(l => l.projectId === project)!const inLead = { kind: 'lead', id: 'lead-web', name: 'Lead', working: false }+ // Task #3818: a reader with several Buddies sees their default on the dial, the chat the backend marks buddyDefault.+ it('shows the reader\'s default Buddy when they have several', () => {+ const research = agent('y2', { name: 'Research', buddyOf: { personId: 'me', generation: 'g1' }, configuration: { engine: 'codex' }, buddyScope: 'swarm' })+ const state = one({ agents: [...chats().agents as object[], buddy({ buddyScope: 'swarm' }), research],+ conversations: [...swarm().conversations, sb(), conv('sb2', null, { projectId: undefined, kind: 'swarm-buddy', buddyOwnerId: 'me', agentIds: ['y2'], buddyDefault: true }), group()] })+ expect(lead(state).buddy).toMatchObject({ chatId: 'sb2', name: 'Research' })+ })+it('gives every project\'s card the reader\'s one Buddy, and the Buddy side shows its chat', () => {const block = { chatId: 'sb', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true, local: 'h-y1' }for (const project of ['web', 'mobile']) {diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.tsindex e91c50e4d..d0a71e3e3 100644--- a/cli/src/superTabs/cards.ts+++ b/cli/src/superTabs/cards.ts@@ -84,7 +84,9 @@ const idsOf = (v: unknown): string[] => Array.isArray(v) ? v.filter((id): id is* person's chat is neither, whatever a read holds. */function buddyChatOf(conversations: Json[], projectId: string, me: string | undefined): Json | undefined {const live = (c: Json) => isReadersBuddyChat(c, me) && c.archived !== true && cardId(c.id)- return conversations.find(c => isSwarmBuddyChat(c) && live(c)) ?? conversations.find(c => !isSwarmBuddyChat(c) && inProject(c, projectId) && live(c))+ // Of several (task #3818), the reader's default: the chat the backend marks so, else the first.+ return conversations.find(c => isSwarmBuddyChat(c) && live(c) && c.buddyDefault === true) ?? conversations.find(c => isSwarmBuddyChat(c) && live(c))+ ?? conversations.find(c => !isSwarmBuddyChat(c) && inProject(c, projectId) && live(c))}/** The reader's Buddies in their chat: the chat's agents that are a Buddy of the reader. One whose `buddyOf` names someone* else (an agent id reused or misfiled) is not, and neither is a thread session (spec 2026-10-30-buddy-thread-sessions),diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 4265465d1..fd22910a7 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -4388,6 +4388,19 @@ describe('a Buddy\'s model request', () => {expect(serve).toHaveBeenCalledWith(expect.objectContaining({ agent: expect.objectContaining({ id: 'buddy' }) }),[expect.objectContaining({ agent: expect.objectContaining({ id: 'session' }) })])})++ // Task #3818: a person with several Buddies switches one; only that Buddy's own sessions, in its own chat, move with it.+ it('moves only the sessions in the switching Buddy\'s own chat, when the backend names each one\'s chat', async () => {+ const serve = vi.fn(async () => {})+ const main = { ...buddyRow({ id: 'buddy', harnessId: 'h-main', modelRequest: { id: 'req1', gridModel: 'm' } }), buddyChatId: 'chat-1' }+ const mine = { ...buddyRow({ id: 'session', harnessId: 'h-session', buddySession: { thread: 't', from: 0 } }), buddyChatId: 'chat-1' }+ const theirs = { ...buddyRow({ id: 'research-session', harnessId: 'h-research', buddySession: { thread: 'r', from: 0 } }), buddyChatId: 'chat-2' }+ const t = lifeFixture([main, mine, theirs], { buddyModels: { serve } })+ await t.poll()+ await vi.waitFor(() => expect(serve).toHaveBeenCalledTimes(1))+ expect(serve).toHaveBeenCalledWith(expect.objectContaining({ agent: expect.objectContaining({ id: 'buddy' }) }),+ [expect.objectContaining({ agent: expect.objectContaining({ id: 'session' }) })])+ })})// Spec 2026-10-30-buddy-thread-sessions: a Buddy's thread session never stays on its person's machine once its thread is done@@ -4403,6 +4416,16 @@ describe('ending a Buddy\'s thread sessions', () => {/** Time passing as the host sees it awake: a look each minute, never a gap it would take for sleep. */const awake = async (t: ReturnType<typeof lifeFixture>, ms: number) => { for (let left = ms; left > 0; left -= 60_000) await t.poll(Math.min(60_000, left)) }+ // Task #3818: a session of a person's second Buddy is in that Buddy's chat, which the backend names on its row.+ it('names the chat the backend gives its row, a second Buddy\'s own', async () => {+ const t = lifeFixture([sessionRow({ buddyChatId: 'research-chat' })])+ t.live(true)+ await t.poll()+ await awake(t, BUDDY_SESSION_IDLE_MS)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ expect(ends(t)[0]!.command).toMatchObject({ type: 'buddy.sessionEnd', conversationId: 'research-chat', thread: 'root-1' })+ })+it('ends one idle for 30 minutes, once, naming its own chat and thread, as the backend computes the chat', async () => {const t = lifeFixture([sessionRow()])t.live(true)diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex b1850d20d..7c839d375 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -899,10 +899,13 @@ export class SuperTabHost {const rows = data.map(object).filter(row => identifier(row.tabId) && object(row.agent).machineId === this.machineId&& identifier(object(row.agent).harnessId) && object(row.agent).buddyOf)const ownerOf = (row: Record<string, unknown>) => { const of = object(object(row.agent).buddyOf); return `${row.tabId}\0${of.personId}\0${of.generation}` }+ // A person may have several Buddies (task #3818): a Buddy's sessions are those in its own chat, which the backend names on+ // each row; an older backend names none, and the person's sessions all go with their one Buddy.+ const chatOf = (row: Record<string, unknown>) => identifier(row.buddyChatId) ? `${row.tabId}\0chat\0${row.buddyChatId}` : ownerOf(row)for (const row of rows) {const agent = object(row.agent)if (agent.buddySession || !agent.modelRequest) continue- const sessions = rows.filter(other => object(other.agent).buddySession && ownerOf(other) === ownerOf(row))+ const sessions = rows.filter(other => object(other.agent).buddySession && chatOf(other) === chatOf(row))void this.buddyModels.serve(row as unknown as BuddyModelRow, sessions as unknown as BuddyModelRow[]).catch(error => this.log(`Buddy model: ${error instanceof Error ? error.name : typeof error}`))}@@ -1657,7 +1660,9 @@ export class SuperTabHost {// the backend's stableId('buddy', 'swarm', person, generation); an older project chat's session is in that chat.const swarm = agent.buddyScope === 'swarm' || identifier(session.projectId)const projectId = swarm ? 'swarm' : identifier(agent.projectId) ? agent.projectId : 'lead'- const conversationId = buddyChatIdOf(projectId, buddyOf.personId, buddyOf.generation)+ // With several Buddies (task #3818) the backend names the session's own chat on its row; an older backend names none.+ const named = object(row).buddyChatId+ const conversationId = identifier(named) ? named : buddyChatIdOf(projectId, buddyOf.personId, buddyOf.generation)state.running = trueconst ending = reason, short = String(agent.harnessId).slice(0, 8)// One id per session and reason: a retry is the same request, and a changed reason never reuses an id for another.diff --git a/docs/plans/2026-11-06-many-buddies-plan.md b/docs/plans/2026-11-06-many-buddies-plan.mdnew file mode 100644index 000000000..567efe2d2--- /dev/null+++ b/docs/plans/2026-11-06-many-buddies-plan.md@@ -0,0 +1,105 @@+# A person can have several Buddies (part 1: many Buddies, a default, a cap): implementation plan++> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,+> the failing test committed before its code. No Execution Handoff.++**Goal:** A person creates, names and removes several Buddies in a Swarm, one is their default, and a per-Swarm cap bounds+how many (task #3818, requested by Dee through Harness; spec docs/plans/2026-11-06-buddy-board-final-spec.md, "Many+Buddies", approved by Ken and anh Dee 11-06). Sleep and wake, a Buddy on a Team machine, and agents' asks to the default+Buddy are separate tasks (proposed split, in the task's chat).++**Architecture:** Today a person has one Swarm Buddy, and its chat's id is derived from the person alone+(buddies.ts swarmBuddyChatId). Each Buddy gets its own chat; the person's first chat keeps today's id, so their existing+Buddy and history are their first Buddy and default. Every place that wrote to "the" Buddy chat writes to the default+Buddy's chat instead, through three helpers (buddies.ts): `defaultBuddy`, `defaultBuddyChat`, `buddyFor`. Task #3817+(proposal cards) uses `buddyFor` for its notices. The cap is a Swarm setting with a default, set by the Swarm owner.++**Tech Stack:** TypeScript backend and CLI host, vitest.++**Spec:** docs/plans/2026-11-06-buddy-board-final-spec.md ("Many Buddies", "Design").++## Global Constraints++- A person with one Buddy sees no change: same chat, same Buddy, same name.+- The server enforces every right: only the person creates, names, removes or picks the default of their own Buddies.+- Swarm code stays out of cli/src/core. Temp files only in `mktemp -d` folders.++## Design++- growth: Buddies per person per Swarm are capped (default 5); a removed Buddy's chat is archived and its lines go to the+ default. No new collection.+- concurrency: Buddy writes are the Swarm's usual write on the person's chats and agents.+- read cost: unchanged; a Buddy chat is a conversation like any other, read by its owner and its Buddy only.+- scale: 10x people at the cap is 50 Buddies each per Swarm at most; the first warning is machine load, which part 2 (sleep)+ bounds.+- compatibility: an older app sees the person's first Buddy chat as today; a new Buddy's chat appears to it as another chat+ of theirs. An older CLI host starts each Buddy by its start request as today.+- migration + rollback: none: the first chat keeps its id. Rolled back, extra Buddies' chats stay and read as chats.+- audience: a Buddy chat is read by its person and its Buddy only, as today (projects.ts readsRecordsIn).+- identity: a Buddy runs on its person's own machine under their login, as today.+- failure: a refused create (cap, name) says why; a line for a person always has a chat (`defaultBuddyChat`).+- platforms: backend and CLI host (macOS, Linux, Windows); Desktop's list is its own task.++## Review Focus++- No place still writes to a person's Buddy chat by the person alone, except through the helpers.+- The cap and the rights hold on the server.++## Task 1: the default-Buddy helpers (for #3817)++**Files:** backend/src/superTabs/buddies.ts, backend/src/superTabs/buddyDefault.test.ts++**Interfaces:** `defaultBuddy(state, personId): Agent | undefined`; `defaultBuddyChat(state, person): Conversation`;+`buddyFor(state, person, senderBuddyId | null): { agent?: Agent; chat: Conversation }`. None throws.++- [x] Test: the default is the person's Buddy (never a session's, an older membership's or another person's); there is+ always a chat; a notice goes to the sender while it is still theirs, else the default.+- [x] Watch it fail; commit.+- [x] Code (today's behaviour: the one Buddy); watch it pass; commit.++## Storage++- The person's **main Buddy chat** keeps today's derived id (`swarmBuddyChatId`), so every command can load it by id. It lists+ the person's other Buddy chats (`Conversation.buddyChats`, at most the cap), so they load with it (store.ts loads the+ person's Buddy chats through it wherever it loaded the one chat).+- A new Buddy's chat id is `stableId('buddy', 'swarm', person, generation, operationId)`: unique, never derived by others.+- The **default** chat carries `buddyDefault: true` (one per person). With none marked, the main chat is the default, so a+ person from before has their one Buddy as default with no migration.+- The **cap** is `SuperTabState.buddyCap` (default 5), set by the Swarm owner with `tab.buddyCap`, read by apps in the head.++## Task 2: several Buddies: create with a name, remove one, set the default, the cap++**Files:** backend/src/superTabs/{model.ts, buddies.ts, commands.ts, store.ts, read/views.ts, read/contract.ts,+parts/touches.ts}, backend/src/superTabs/buddies.test.ts, backend/integration/superTabSwarmBuddy.test.ts++**Interfaces:** `buddy.create { …, name?, conversationId? }` (a name and no chat: a new Buddy in a new chat; a chat: that+Buddy again; neither: as today on the default); `buddy.remove { conversationId? }` (that Buddy, else the default; the+default's role passes to the oldest remaining); `buddy.default { conversationId }`; `tab.buddyCap { cap }`; refusal+`BUDDY_CAP`. `defaultBuddy` reads the marked default.++- [x] Test: a second Buddy is created with its name in its own chat; the cap refuses one more; remove and default behave as+ above; only the person acts on their Buddies; a person with one Buddy sees no change.+- [x] Watch it fail; commit. Code; watch it pass; commit.++## Task 3: lines for a person go to their default Buddy; a proposal's news to its sender++**Files:** backend/src/superTabs/{commands.ts (person.tell, instructions notice, machine.moved, switch notice, proposalOf,+startOldChatBuddy, buddyDownLine), decisions.ts, othersWork.ts, buddyNews.ts, leaderboard/stats.ts, buddyModel.ts}++- [x] Test: with two Buddies and the second as default, a PM line, a delegated decision and a move notice go to the second's+ chat; a proposal's news goes to the Buddy that sent it, and to the default once it is removed; a model switch moves only+ the chosen Buddy and its own sessions.+- [x] Watch it fail; commit. Code; watch it pass; commit.++## Task 4: the CLI host with several Buddies++**Files:** cli/src/superTabs/{host.ts (session end's chat, model serve grouping), cards.ts (the dial's default)};+backend read/hostRows.ts and read/contract.ts (`buddyChatId` on a Buddy's host row), commands.ts (an older host's session end+naming the main chat finds the thread in another Buddy's chat).++Left out: the Buddy start prompt's "one Buddy" wording (start.ts), and the leaderboard's credit of a thread session's proposal+(leaderboard/stats.ts creditee), which still folds into the person's first Buddy.++- [x] Test: a second Buddy's thread session ends in its own chat; a model switch groups by the Buddy's chat; the dial shows+ the default Buddy.+- [x] Watch it fail; commit. Code; watch it pass; commit.