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
Idle Buddies sleep and wake (#3824) (#3430)
harness-for-autonomous[bot]5fffa7cba17d
diff --git a/.github/workflows/cli-e2e.yml b/.github/workflows/cli-e2e.ymlindex b9895ac36..1cd4b1037 100644--- a/.github/workflows/cli-e2e.yml+++ b/.github/workflows/cli-e2e.yml@@ -113,10 +113,10 @@ jobs:overwrite: trueretention-days: 7- # The tests that need macOS: a data folder on a small disk image that fills (hdiutil). Opt-in- # locally (DISKFULL=1); here on one macOS runner, filtered to those tests alone, a few minutes.+ # Native macOS checks: a disk image that fills (hdiutil), and Buddy sleep/resume on an owner OS account.+ # Team accounts cannot launch Buddies; the hosted runner exercises the real terminal lifecycle.e2e-macos-disk:- name: e2e (macOS, full disk)+ name: e2e (macOS, full disk and Buddy)runs-on: macos-15timeout-minutes: 30defaults:@@ -131,6 +131,27 @@ jobs:cache-dependency-path: cli/package-lock.json- run: command -v tmux || brew install tmux- run: npm ci --no-audit --no-fund+ - name: An idle Buddy releases its session and wakes on a message+ env:+ E2E_BUNDLE: '1'+ E2E_ARTIFACTS_DIR: ${{ runner.temp }}/e2e-daemon-logs+ run: >-+ npx vitest run --config vitest.e2e.config.ts e2e/superTabSwarmBuddy.e2e.ts+ --reporter=default --reporter=json --outputFile.json="$RUNNER_TEMP/buddy-result.json"+ - name: Require the native Buddy flow to pass without skipping+ env:+ BUDDY_RESULT: ${{ runner.temp }}/buddy-result.json+ run: >-+ node -e 'const r = JSON.parse(require("node:fs").readFileSync(process.env.BUDDY_RESULT, "utf8"));+ if (r.numPassedTests !== 1 || r.numPendingTests !== 0 || r.numFailedTests !== 0) process.exit(1)'+ - name: Preserve the native Buddy result+ if: ${{ !cancelled() }}+ uses: actions/upload-artifact@v4+ with:+ name: cli-e2e-buddy-macos+ path: ${{ runner.temp }}/buddy-result.json+ if-no-files-found: error+ retention-days: 7- name: A full disk, and an update on a disk that fillsenv:DISKFULL: '1'diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex 7c996280f..a927d4431 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -14,11 +14,12 @@ import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'import { sweepUnsentAttachments } from '../src/lib/attachmentSweep.js'-import type { Command } from '../src/superTabs/commands.js'+import { commandSchema, type Command } from '../src/superTabs/commands.js'import { poolRows, rosterRows } from './hostRows.test-support.js'import { SwarmReads } from '../src/superTabs/read/service.js'import { beforeFirstWrite } from './interleave.test-support.js'import { quotaReset } from './holds.test-support.js'+import { profiled, reads, plan } from './plans.test-support.js'// Buddies end to end through the store (buddies.ts): a person adds one on their own Swarm machine, its host starts it, they// talk to it alone, and it sends their proposal to the PM. A fresh loopback replica set, created here.@@ -72,9 +73,9 @@ async function closedPmChat(f: { store: SuperTabStore; tab: string }, conversati}/** A Swarm whose PM runs on the owner's Mac, and peer a member with their own Mac in the Machines list. */-async function swarm() {+async function swarm(now: () => number = () => Date.now()) {const files = new MemoryAttachmentStore()- const store = new SuperTabStore(db, () => Date.now(), { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })+ const store = new SuperTabStore(db, now, { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })const tab = (await store.create(owner, randomUUID(), 'Buddies', 'public')).idconst execute = (command: Command, user = owner, asAgentId?: string, hostMachineId?: string) =>store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId)@@ -104,8 +105,8 @@ async function launch(f: Swarm, startId: string) {/** peer's one Buddy of the Swarm (Dee, 10-31), added from # buddy and started by peer-mac's host; [pool] is what that host read* while it started. */-async function swarmBuddy(f: Swarm) {- const added = await f.execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude' }, peer)+async function swarmBuddy(f: Swarm, fresh = false) {+ const added = await f.execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude', ...(fresh ? { name: 'Research' } : {}) }, peer)const pool = (await poolRows(f.store, peer, 'peer-mac')).find(p => p.tabId === f.tab)!return { swarmChat: String(added.result.conversationId), main: await launch(f, String(added.result.startId)), pool }}@@ -1277,3 +1278,110 @@ describe('the person\'s own browser, reading and writing the Swarm straight fromexpect(await refusal(new SwarmReads(f.store).firstLoad(peerTeam, f.tab))).toMatchObject(LIMITED)})})+++describe('idle Buddy sleep (#3824)', () => {+ it('sleeps only after an idle hour and no open delivery, using the agent status index', async () => {+ let now = Date.now()+ const f = await swarm(() => now)+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })+ const { main, swarmChat, pool } = await swarmBuddy(f)+ const agent = (await f.store.read(peer, f.tab)).state.agents.find(a => a.id === main)!+ const sent = await f.execute({ type: 'message.send', conversationId: swarmChat, text: 'Remember this', replyTo: null, recipientIds: [] }, peer)+ const { receivedAt: _, sessionKind: __, ...report } = pool.machine.observation!+ const idle = { ...report, runningHarnessIds: [agent.harnessId], idleBuddyHarnessIds: [agent.harnessId] }+ const current = async () => (await f.store.read(peer, f.tab)).state.agents.find(a => a.id === main)!+ now += 3_600_000 - 1+ await f.store.observeMachine(peer, f.tab, 'peer-mac', idle)+ expect((await current()).asleep).toBeUndefined()+ now+++ for (const status of ['queued', 'claimed', 'uncertain']) {+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: main, messageId: String(sent.result.messageId) }, data: { status } })+ await f.store.observeMachine(peer, f.tab, 'peer-mac', idle)+ expect((await current()).asleep, status).toBeUndefined()+ now += 30_001+ }+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: main }, data: { status: 'answered' } })+ const entries = await profiled(db, () => f.store.observeMachine(peer, f.tab, 'peer-mac', idle))+ expect((await current()).asleep).toEqual({ since: now })+ const pending = reads(entries, 'SuperTabDelivery', ['tabId', 'agentId', 'status'])+ expect(pending.length).toBeGreaterThan(0)+ for (const row of plan(pending)) {+ expect(row.plan).toContain('IXSCAN { tabId: 1, agentId: 1, status: 1, createdAt: 1 }')+ expect(row.docsExamined).toBe(0)+ expect(row.keysExamined).toBeLessThanOrEqual(3)+ }+ const row = (await rosterRows(f.store, peer, 'peer-mac')).find(r => 'agent' in r && r.agent.id === main)+ expect(row).toMatchObject({ buddySleepManaged: true, agent: { harnessId: agent.harnessId, buddyOf: agent.buddyOf } })+ })+})+++describe('Buddy input and sleep race (#3824)', () => {+ it('wakes only the authorized recipient and retries sleep when input commits first', async () => {+ let now = Date.now()+ const f = await swarm(() => now)+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })+ const first = await swarmBuddy(f), second = await swarmBuddy(f, true)+ const agents = (await f.store.read(peer, f.tab)).state.agents.filter(a => [first.main, second.main].includes(a.id))+ const { receivedAt: _, sessionKind: __, ...report } = first.pool.machine.observation!+ const idle = { ...report, runningHarnessIds: agents.map(a => a.harnessId), idleBuddyHarnessIds: agents.map(a => a.harnessId) }+ const current = async (id: string) => (await f.store.read(peer, f.tab)).state.agents.find(a => a.id === id)!+ now += 3_600_000+ await f.store.observeMachine(peer, f.tab, 'peer-mac', idle)+ expect((await current(first.main)).asleep).toBeDefined()+ expect((await current(second.main)).asleep).toBeDefined()+ await expect(f.execute({ type: 'message.send', conversationId: first.swarmChat, text: 'Not yours', replyTo: null, recipientIds: [] })).rejects.toThrow()+ expect((await current(first.main)).asleep).toBeDefined()+ const input = { type: 'message.send' as const, conversationId: first.swarmChat, text: 'Continue', replyTo: null, recipientIds: [] }+ const sent = await f.execute(input, peer)+ expect((await current(first.main)).asleep).toBeUndefined()+ expect((await current(second.main)).asleep).toBeDefined()+ const waiting = (await f.store.deliveries(peer, f.tab, first.main)).find(d => d.messageId === sent.result.messageId)!+ const claim = await f.store.delivery(peer, f.tab, first.main, waiting.id, { type: 'claim', claimId: randomUUID() })+ expect(claim).toMatchObject({ message: { id: sent.result.messageId } })+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: first.main }, data: { status: 'answered' } })+ now += 3_600_001+ let injected = false+ const racing = new SuperTabStore(beforeFirstWrite(db, async () => {+ if (injected) return+ injected = true+ await f.execute({ ...input, text: 'A message just before sleep' }, peer)+ }), () => now)+ await racing.observeMachine(peer, f.tab, 'peer-mac', idle)+ expect(injected).toBe(true)+ expect((await current(first.main)).asleep).toBeUndefined()+ expect((await f.store.deliveries(peer, f.tab, first.main)).some(d => d.status === 'queued')).toBe(true)+ })+})+++describe('a sleeping proposal sender (#3824)', () => {+ it('wakes the card’s original Buddy for a PM question even when another Buddy is the default', async () => {+ let now = Date.now()+ const f = await swarm(() => now)+ await f.execute({ type: 'project.boardMode', projectId: 'lead', on: true })+ const first = await swarmBuddy(f), second = await swarmBuddy(f, true)+ const approved = await f.execute({ type: 'message.send', conversationId: first.swarmChat, text: 'Preserve drafts', replyTo: null, recipientIds: [] }, peer)+ const proposal = await f.execute(commandSchema.parse({ type: 'buddy.propose', conversationId: first.swarmChat, projectId: 'lead', ownerMessageId: approved.result.messageId,+ title: 'Preserve drafts', text: 'Preserve drafts', goal: 'Preserve work', scope: 'Draft storage', priority: 'P2',+ why: 'Reconnect loses work', doneWhen: 'Draft returns', evidence: ['Offline reproduction'] }), peer, first.main)+ await f.execute({ type: 'buddy.default', conversationId: second.swarmChat }, peer)+ const agents = (await f.store.read(peer, f.tab)).state.agents.filter(a => [first.main, second.main].includes(a.id))+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: { in: agents.map(a => a.id) } }, data: { status: 'answered' } })+ const { receivedAt: _, sessionKind: __, ...report } = first.pool.machine.observation!+ now += 3_600_001+ await f.store.observeMachine(peer, f.tab, 'peer-mac', { ...report, runningHarnessIds: agents.map(a => a.harnessId), idleBuddyHarnessIds: agents.map(a => a.harnessId) })+ const current = async (id: string) => (await f.store.read(peer, f.tab)).state.agents.find(a => a.id === id)!+ expect((await current(first.main)).asleep).toBeDefined()+ expect((await current(second.main)).asleep).toBeDefined()+ await f.execute(commandSchema.parse({ type: 'proposal.ask', conversationId: proposal.result.conversationId, personId: peer.sub,+ question: 'How long?', defaultAnswer: 'Seven days', deadline: now + 60_000 }), owner, f.lead)+ expect((await current(first.main)).asleep).toBeUndefined()+ expect((await current(second.main)).asleep).toBeDefined()+ const waiting = (await f.store.deliveries(peer, f.tab, first.main)).find(d => d.conversationId === first.swarmChat)!+ expect(waiting).toBeDefined()+ const claim = await f.store.delivery(peer, f.tab, first.main, waiting.id, { type: 'claim', claimId: randomUUID() })+ expect(claim).toMatchObject({ message: { source: { kind: 'proposal-notice' } } })+ })+})diff --git a/backend/src/superTabs/buddyNews.ts b/backend/src/superTabs/buddyNews.tsindex 90f224983..55d53c6c3 100644--- a/backend/src/superTabs/buddyNews.ts+++ b/backend/src/superTabs/buddyNews.ts@@ -78,10 +78,9 @@ export function shippedNotice(state: SuperTabState, group: Conversation, author:text: `News for your owner: #${group.number} "${group.title}", which they requested, shipped.` }}-/** The Buddies [messages] bring news to outside their own chat: what they were told relied on their person still reading- * there, so a write that sends news guards on those people and Buddies (parts/touches.ts). */+/** Every Buddy hearing input, in its own chat too: the agent guard meets a concurrent sleep (#3824), and the person's+ * guard meets loss of the membership that permits the delivery (parts/touches.ts). */export function buddiesHearing(state: SuperTabState, messages: readonly MessageDraft[]): Agent[] {- const ids = new Set(messages.flatMap(m => [...m.buddyRecipients ?? [],- ...m.recipients.filter(id => !state.conversations.find(c => c.id === m.conversationId)?.agentIds.includes(id))]))+ const ids = new Set(messages.flatMap(m => [...m.buddyRecipients ?? [], ...m.recipients]))return state.agents.filter(a => ids.has(a.id) && isBuddy(a))}diff --git a/backend/src/superTabs/buddySleep.test.ts b/backend/src/superTabs/buddySleep.test.tsnew file mode 100644index 000000000..84cced25f--- /dev/null+++ b/backend/src/superTabs/buddySleep.test.ts@@ -0,0 +1,134 @@+import { numberMessages } from './parts/commit.js'+import { describe, expect, it } from 'vitest'+import { createSuperTab, visibleState, type Agent } from './model.js'+import { openSwarmBuddyChat } from './buddies.js'+import { projectsOf } from './projects.js'+import { machine, NOW, config } from './crewKeep.test-support.js'+import { buddySleepCandidates, buddySleepManaged, sleepBuddies } from './buddySleep.js'++// #3824: dropping any check below could close a busy Buddy, an unswitched project's Buddy, or the wrong membership's.+function fixture() {+ const state = createSuperTab('tab', 'Work', { id: 'owner', email: '[email protected]' }, 'prod')+ state.projects = projectsOf(state).map(p => ({ ...p, boardMode: true }))+ const owner = state.people[0]!+ const chat = openSwarmBuddyChat(state, owner)+ chat.lastActivityAt = new Date(NOW - 3_600_000).toISOString()+ const buddy: Agent = { id: 'buddy', name: 'Code', machineId: 'mac', machineOwnerId: owner.id, contributorId: owner.id,+ membershipGeneration: owner.generation, hostGrant: null, harnessId: 'buddy-h', configuration: config,+ buddyOf: { personId: owner.id, generation: owner.generation }, buddyScope: 'swarm',+ startedSession: { creationId: 'created', sessionId: 'session', createdAt: new Date(NOW - 7_200_000).toISOString() } }+ state.agents.push(buddy)+ chat.agentIds.push(buddy.id)+ state.machines = [machine('mac')]+ const pool = state.machines[0]!+ pool.membershipGeneration = owner.generation+ Object.assign(pool.observation!, { runningHarnessIds: ['buddy-h'], idleBuddyHarnessIds: ['buddy-h'] })+ return { state, buddy, chat, pool, owner }+}++describe('server-owned Buddy sleep', () => {+ it('keeps private engine-idle proof out of member reads', () => {+ const f = fixture()+ const visible = visibleState(f.state, { kind: 'person', userId: f.owner.id, email: f.owner.email }, NOW)+ expect(visible.machines![0]!.observation).not.toHaveProperty('idleBuddyHarnessIds')+ })++ it('sleeps at one idle hour, once, and preserves identity and the session', () => {+ const f = fixture()+ expect(buddySleepCandidates(f.state, NOW - 1)).toEqual([])+ const candidates = buddySleepCandidates(f.state, NOW)+ expect(candidates.map(a => a.id)).toEqual(['buddy'])+ sleepBuddies(f.state, candidates, new Set(), NOW)+ expect(f.buddy).toMatchObject({ asleep: { since: NOW }, harnessId: 'buddy-h', buddyOf: { personId: 'owner', generation: f.owner.generation } })+ expect(buddySleepCandidates(f.state, NOW + 1)).toEqual([])+ })++ it.each(['queued', 'claimed', 'uncertain'])('a %s delivery prevents sleep', () => {+ const f = fixture()+ sleepBuddies(f.state, buddySleepCandidates(f.state, NOW), new Set(['buddy']), NOW)+ expect(f.buddy.asleep).toBeUndefined()+ })++ it.each(['unknown', 'working', 'stale', 'not-running'])('a %s engine reading is no idle proof', which => {+ const f = fixture()+ if (which === 'unknown') delete (f.pool.observation as unknown as { idleBuddyHarnessIds?: string[] }).idleBuddyHarnessIds+ if (which === 'working') Object.assign(f.pool.observation!, { idleBuddyHarnessIds: [] })+ if (which === 'stale') f.pool.observation!.receivedAt = NOW - 45_001+ if (which === 'not-running') f.pool.observation!.runningHarnessIds = []+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])+ })++ it('does not sleep during active work or a model switch', () => {+ const f = fixture()+ Object.assign(f.chat, { assignment: { agentId: 'buddy', status: 'working' } })+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])+ f.chat.assignment = null+ f.buddy.modelRequest = { id: 'request' } as NonNullable<Agent['modelRequest']>+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])+ })++ it('leaves an unswitched project and a Swarm Buddy reading mixed projects unchanged', () => {+ const f = fixture()+ delete f.state.projects![0]!.boardMode+ expect(buddySleepManaged(f.state, f.buddy)).toBe(false)+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])+ f.state.projects![0]!.boardMode = true+ f.state.projects!.push({ ...f.state.projects![0]!, id: 'other', boardMode: undefined })+ expect(buddySleepManaged(f.state, f.buddy)).toBe(false)+ })++ it('keeps a sleeping Buddy managed through switch-back and the ensuing wake', () => {+ const f = fixture()+ f.buddy.asleep = { since: NOW - 1_000 }+ delete f.state.projects![0]!.boardMode+ expect(buddySleepManaged(f.state, f.buddy)).toBe(true)+ numberMessages(f.state, [{ id: 'wake', conversationId: f.chat.id, replyTo: null, text: 'Continue', recipients: ['buddy'],+ author: { kind: 'person', id: f.owner.id, name: f.owner.email, membershipGeneration: f.owner.generation } }], NOW)+ expect(f.buddy.asleep).toBeUndefined()+ expect(buddySleepManaged(f.state, f.buddy)).toBe(true)+ delete f.buddy.crewWaking+ expect(buddySleepManaged(f.state, f.buddy)).toBe(false)+ })++ it.each(['old-membership', 'session', 'team', 'stopping'])('never sleeps a %s Buddy', which => {+ const f = fixture()+ if (which === 'old-membership') f.buddy.buddyOf!.generation = 'old'+ if (which === 'session') f.buddy.buddySession = { thread: 'thread', from: 0 }+ if (which === 'team') f.pool.observation!.sessionKind = 'team'+ if (which === 'stopping') f.buddy.workDecision = 'stop'+ expect(buddySleepManaged(f.state, f.buddy)).toBe(false)+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])+ })+})+++describe('authorized input wakes the same Buddy', () => {+ it.each(['person', 'proposal-question'])('wakes only the intended Buddy for %s input before agent-only filtering', kind => {+ const f = fixture()+ f.buddy.asleep = { since: NOW - 1_000 }+ const other = { ...structuredClone(f.buddy), id: 'other', harnessId: 'other-h' }+ f.state.agents.push(other)+ const own = kind === 'person'+ const message = { id: 'input', conversationId: own ? f.chat.id : 'lead', replyTo: null,+ author: { kind: 'person' as const, id: f.owner.id, name: f.owner.email, membershipGeneration: f.owner.generation },+ recipients: own ? ['buddy'] : [], ...own ? {} : { buddyRecipients: ['buddy'], source: { kind: 'agent-only' } }, text: 'Please answer' }+ numberMessages(f.state, [message], NOW)+ expect(f.buddy.asleep).toBeUndefined()+ expect(f.buddy).toMatchObject({ keptAt: NOW, downSince: new Date(NOW).toISOString(), crewWaking: { at: NOW, conversationId: message.conversationId },+ harnessId: 'buddy-h', buddyOf: { personId: f.owner.id, generation: f.owner.generation } })+ expect(other.asleep).toEqual({ since: NOW - 1_000 })+ numberMessages(f.state, [{ ...message, id: 'second' }], NOW + 1)+ expect(f.buddy.crewWaking!.at).toBe(NOW)+ expect(buddySleepCandidates(f.state, NOW + 3_599_999)).toEqual([])+ })++ it.each(['stale-person', 'private-chat'])('does not wake for %s input it cannot read', kind => {+ const f = fixture()+ f.buddy.asleep = { since: NOW - 1_000 }+ if (kind === 'stale-person') f.buddy.buddyOf!.generation = 'old'+ else f.chat.audience!.people[0]!.generation = 'old'+ numberMessages(f.state, [{ id: 'input', conversationId: f.chat.id, replyTo: null, text: 'No', recipients: ['buddy'],+ author: { kind: 'person', id: 'owner', name: 'owner', membershipGeneration: f.owner.generation } }], NOW)+ expect(f.buddy.asleep).toEqual({ since: NOW - 1_000 })+ })+})diff --git a/backend/src/superTabs/buddySleep.ts b/backend/src/superTabs/buddySleep.tsnew file mode 100644index 000000000..454850eaf--- /dev/null+++ b/backend/src/superTabs/buddySleep.ts@@ -0,0 +1,59 @@+import { activeWork, type Agent, type MessageDraft, type SuperTabState } from './model.js'+import { isBuddy, isBuddyChat, isSwarmBuddy } from './buddies.js'+import { switched } from './boardRights.js'+import { SLEEP_IDLE_MS } from './crewRules.js'+import { MACHINE_FRESH_MS } from './machines.js'+import { agentProjectId, canReadGroup, canReadProject, onTeamAccount, projectsOf } from './projects.js'+import { groupsOf, idleSince } from './tidy.js'+import { wakeCrewMember } from './crewKeep.js'+import { startWake } from './crewTimes.js'+import { buddiesHearing } from './buddyNews.js'++/** Only a current main Buddy in Board projects can rest (#3824). A Team close purges its resumable session data. */+export function buddySleepManaged(state: SuperTabState, agent: Agent): boolean {+ if (!isBuddy(agent) || agent.buddySession || agent.workDecision === 'stop' || agent.movedTo || onTeamAccount(state, agent)) return false+ const person = state.people.find(p => p.id === agent.buddyOf!.personId && p.generation === agent.buddyOf!.generation)+ if (!person) return false+ const reader = { kind: 'person' as const, userId: person.id, email: person.email }+ const home = state.conversations.find(c => isBuddyChat(c) && c.agentIds.includes(agent.id) && !c.archived && canReadGroup(state, reader, c))+ if (!home) return false+ // Keep an already resting Buddy resumable even if a project switches back to chat while it is asleep.+ if (agent.asleep || agent.crewWaking) return true+ const projects = projectsOf(state).filter(p => isSwarmBuddy(agent) ? canReadProject(state, reader, p) : p.id === agentProjectId(state, agent))+ return projects.length > 0 && projects.every(p => canReadProject(state, reader, p) && switched(p))+}++/** Quiet output is not idle proof: only the host's fresh, positive engine activity reading allows a sleep. */+export function buddySleepCandidates(state: SuperTabState, now: number): Agent[] {+ if (state.paused) return []+ return state.agents.filter(agent => {+ if (agent.asleep || agent.modelRequest || !buddySleepManaged(state, agent)) return false+ const pool = state.machines?.find(m => m.machineId === agent.machineId), reading = pool?.observation+ if (!pool || pool.paused || pool.removal || !reading || now - reading.receivedAt > MACHINE_FRESH_MS+ || !reading.runningHarnessIds.includes(agent.harnessId) || !reading.idleBuddyHarnessIds?.includes(agent.harnessId)) return false+ const groups = groupsOf(state, agent)+ if (groups.some(g => g.assignment?.agentId === agent.id && activeWork(g))) return false+ const since = idleSince(agent, groups)+ const homeActivity = groups.filter(isBuddyChat).flatMap(g => g.lastActivityAt ? [Date.parse(g.lastActivityAt)] : []).filter(Number.isFinite)+ return since !== undefined && now - Math.max(since, ...homeActivity) >= SLEEP_IDLE_MS+ })+}++/** The store checks open deliveries under the same guarded agent write before applying a candidate. */+export function sleepBuddies(_state: SuperTabState, candidates: Agent[], busy: ReadonlySet<string>, now: number): void {+ for (const agent of candidates) if (!busy.has(agent.id) && !agent.asleep) agent.asleep = { since: now }+}++/** Final, authorized recipients decide who wakes, including private notices omitted from the shown message counter. */+export function wakeBuddies(state: SuperTabState, message: MessageDraft, now: number): void {+ const group = state.conversations.find(c => c.id === message.conversationId)+ if (!group) return+ for (const buddy of buddiesHearing(state, [message])) {+ if (buddy.buddySession || !state.people.some(p => p.id === buddy.buddyOf!.personId && p.generation === buddy.buddyOf!.generation)+ || !canReadGroup(state, { kind: 'agent', agentId: buddy.id, machineOwnerId: buddy.machineOwnerId }, group)) continue+ if (wakeCrewMember(buddy, now)) {+ buddy.keptAt = now+ startWake(buddy, group.id, now)+ }+ }+}diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.tsindex befd3ada2..914dd82ec 100644--- a/backend/src/superTabs/machines.test.ts+++ b/backend/src/superTabs/machines.test.ts@@ -260,6 +260,16 @@ describe('a machine\'s reading as a report stores it (DB 2.5)', () => {expect(team).toMatchObject({ sessionKind: 'team', privacy: { mode: 'dedicated', seenAt: NOW } })})+ it('stores only running idle Buddies and makes changed proof run the full decision', () => {+ const proof = stored({ idleBuddyHarnessIds: ['a', 'a', 'not-running'] })+ expect(proof.idleBuddyHarnessIds).toEqual(['a'])+ expect(readingOnly(stored({}), proof)).toBe(false)+ const heartbeat = stored({}, NOW + 15_000)+ expect(heartbeat).not.toHaveProperty('idleBuddyHarnessIds')+ expect(readingOnly(proof, heartbeat)).toBe(false)+ expect(readingOnly(proof, stored({ idleBuddyHarnessIds: ['a'] }, NOW + 15_000))).toBe(true)+ })+it('names a start preparing only when this machine launched it and it neither runs nor failed', () => {const start = (extra: Record<string, unknown>) => ({ id: 's', request: { machineId: 'host' }, dispatched: true, ...extra }) as unknown as AgentStartexpect(preparableStart(start({}), 'host')).toBe(true)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 22d5e9bca..b3772ab9d 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -162,6 +162,8 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16quotaReasons: z.record(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), z.string().min(1).max(300)).refine(v => Object.keys(v).length <= 8).optional(),runningHarnessIds: z.array(z.string().max(160)).max(1000),stoppedHarnessIds: z.array(z.string().max(160)).max(1000),+ /** Running Buddy sessions positively idle in this reading; absent is unknown, never idle (#3824). */+ idleBuddyHarnessIds: z.array(z.string().max(160)).max(1000).optional(),/** Of the stopped ones, those this machine's idle cleanup closed (cli superTabs/cleanupCloses.ts): only such a session is* refused new work (closedAgents.ts sessionClosed), never one stopped by Change agent or a restart (review of #2953).* Absent from hosts before it. */@@ -235,7 +237,7 @@ export const refusableStart = (start: AgentStart, machineId: string): boolean =>*/export function storedObservation(pool: ContributedMachine, observation: MachineObservation,opts: { team: boolean; now: number; preparable: (startId: string) => boolean; refusable?: (startId: string) => boolean }): StoredReading {- const { privacy: reported, harnessProgress, harnessTokens, preparingStartIds, refusedStarts, profiles, ...reading } = observation+ const { privacy: reported, harnessProgress, harnessTokens, preparingStartIds, refusedStarts, profiles, idleBuddyHarnessIds, ...reading } = observationconst running = (id: string) => observation.runningHarnessIds.includes(id)const progress = harnessProgress && Object.fromEntries(Object.entries(harnessProgress).filter(([id]) => running(id)))const tokens = harnessTokens && Object.fromEntries(Object.entries(harnessTokens).filter(([id]) => running(id)))@@ -245,6 +247,7 @@ export function storedObservation(pool: ContributedMachine, observation: Machineconst privacy = observedPrivacy(pool.observation?.privacy, reported, opts.team, opts.now)const engines = contributedEngines(pool, observation)return { ...reading, quotas: observation.quotas.filter(q => engines.includes(q.engine)), receivedAt: opts.now,+ ...(idleBuddyHarnessIds ? { idleBuddyHarnessIds: [...new Set(idleBuddyHarnessIds.filter(running))] } : {}),...(profiles ? { profiles: profiles.filter(p => engines.includes(p.engine)) } : {}),sessionKind: opts.team ? 'team' : 'computer', ...(privacy ? { privacy } : {}), ...(progress ? { harnessProgress: progress } : {}),...(tokens ? { harnessTokens: tokens } : {}), ...(preparing ? { preparingStartIds: preparing } : {}),@@ -269,7 +272,8 @@ export function readingOnly(previous: StoredReading | undefined, next: StoredReaif (!previous || next.stoppedReservations?.length || next.refusedStarts?.length || previous.sessionKind !== next.sessionKind) return falseif (!sameSet(previous.runningHarnessIds, next.runningHarnessIds) || !sameSet(previous.stoppedHarnessIds, next.stoppedHarnessIds)|| !sameSet(previous.closedHarnessIds ?? [], next.closedHarnessIds ?? [])- || !sameSet(previous.preparingStartIds, next.preparingStartIds)) return false+ || !sameSet(previous.preparingStartIds, next.preparingStartIds)+ || !sameSet(previous.idleBuddyHarnessIds, next.idleBuddyHarnessIds)) return falseif (!previous.harnessProgress || !next.harnessProgress) return !previous.harnessProgress && !next.harnessProgressconst before = previous.harnessProgress, after = next.harnessProgressreturn sameSet(Object.keys(before), Object.keys(after)) && Object.entries(before).every(([id, at]) => after[id]! >= at)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 77e68f500..be13834c7 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -1160,6 +1160,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(// A failing privacy check's detail is its contributor's: an error from the check can name paths on their Mac. Everyone// else reads which item failed (machines.ts teamWorkRefusal).for (const pool of visible.machines ?? []) {+ // Engine idle proof is for server lifecycle decisions alone, never a member's activity feed (#3824).+ if (pool.observation) delete pool.observation.idleBuddyHarnessIdsconst privacy = pool.observation?.privacyif (privacy && 'detail' in privacy && !(actor.kind === 'person' && actor.userId === pool.contributorId)) delete (privacy as { detail?: string }).detail}diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex cc5af061a..ef627e159 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -1,6 +1,7 @@import type { Prisma } from '@prisma/client'import { agentOnly, conversation, fail, isLeads, type AgentStart, type Conversation, type MessageDraft, type SuperTabState } from '../model.js'import { autoJoinOn } from '../autoJoinDomain.js'+import { wakeBuddies } from '../buddySleep.js'import { split } from './shape.js'import { guardedWrite, PartConflict, plainHost, type HeadColumns, type HostColumns, type PartWrite } from './write.js'import type { GroupData, MachineData, Part, PartKind, SwarmParts } from './types.js'@@ -132,6 +133,7 @@ export function numberMessages(state: SuperTabState, messages: MessageDraft[], nconst sequence = (group.messageSeq ?? state.sequenceBase ?? 0) + 1group.messageSeq = sequencesequences.set(message.id, sequence)+ wakeBuddies(state, message, now)if (agentOnly(message.source, message.recipients)) continuegroup.lastMessageSequence = sequenceif (!message.thread || message.alsoInChat) {diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.tsindex 05cfb4537..0492e99ca 100644--- a/backend/src/superTabs/parts/touches.test.ts+++ b/backend/src/superTabs/parts/touches.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from '../commands.js'import { createSuperTab, type Actor } from '../model.js'+import { openSwarmBuddyChat } from '../buddies.js'import { touchesFor } from './touches.js'const HOLD = { kind: 'person', personId: 'owner', defaultAt: '2026-11-06T02:00:00.000Z' } as const@@ -132,3 +133,17 @@ describe('the parts a command touches (design section 1.2, column T)', () => {expect(has(touches, 'head', 'head')).toBe(true)})})+++it('guards an already awake Buddy hearing its own chat against a concurrent sleep', () => {+ const f = swarm(), a = f.group('A')+ const buddy = f.state.agents.find(agent => agent.id === a.worker)!+ buddy.buddyOf = { personId: 'owner', generation: f.state.people[0]!.generation }+ buddy.buddyScope = 'swarm'+ const chat = openSwarmBuddyChat(f.state, f.state.people[0]!)+ chat.agentIds.push(buddy.id)+ const touches = touchesFor({ type: 'message.send', conversationId: chat.id, text: 'Hi', replyTo: null, recipientIds: [] },+ owner, f.state, { state: f.state, messages: [{ id: 'input', conversationId: chat.id, text: 'Hi', replyTo: null,+ recipients: [buddy.id], author: { kind: 'person', id: 'owner', name: 'Owner', membershipGeneration: f.state.people[0]!.generation } }] })+ expect(has(touches, 'agent', buddy.id)).toBe(true)+})diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 9599b825c..542885d9a 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -46,7 +46,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStateif ('roleId' in command && command.roleId) head()if (command.type === 'agent.start' && command.request.roleId) head()- // News for a Buddy relies on its person still reading there (buddyNews.ts): their part guards it, as a person.tell's does.+ // Buddy input also guards an already awake recipient, so a concurrent sleep retries against that input (#3824).for (const buddy of buddiesHearing(effects.state, effects.messages)) { agent(buddy.id); member(buddy.buddyOf!.personId) }switch (command.type) {diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 3aec6a253..86b0a5709 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -310,6 +310,8 @@ export interface HostAgentRow {/** 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 | null+ /** Main Buddy whose session may rest and resume in place (#3824). */+ buddySleepManaged?: truejoinSwarm: booleanskillMode: 'default' | 'orchestration'role?: { id: string; name: string; kind: string; version: string; projectId: string } | null@@ -354,6 +356,8 @@ export interface HostPool {githubApp?: true/** The host may say what it launches beyond workers in its readings (leadStart.ts). */capabilitiesWanted?: true+ /** Asks for positive idle Buddy activity in fresh machine readings (#3824). */+ buddySleepWanted?: true}/** HTTP 426 on GET /api/super-tabs, /:tabId, /hosts/:m, /hosts/:m/pools and /hosts/:m/assignments. */diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.tsindex 492fa7ffc..435c344b5 100644--- a/backend/src/superTabs/read/hostRows.ts+++ b/backend/src/superTabs/read/hostRows.ts@@ -3,6 +3,7 @@* before parts (the store's old host reads, which this replaced), built from a reassembled state, with `revision`* replaced by `lastChangedAt` and the Leads conversation id added to agent rows.*/+import { buddySleepManaged } from '../buddySleep.js'import type { AuthUser } from '../../lib/ssoAuth.js'import { activeWork, agent, isLeads, SuperTabError, conversation, type Agent, type SuperTabState } from '../model.js'import { buddyChatOf, isSwarmBuddy, isSwarmBuddyChat } from '../buddies.js'@@ -85,6 +86,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:attention: waiting ? { assignmentId: waiting.id, status: waiting.status, result: waiting.result?.slice(0, 500) ?? null } : null,resume,agent: target,+ ...(buddySleepManaged(state, target) ? { buddySleepManaged: true as const } : {}),// A Buddy-only record is not the machine in the Swarm: the owner's Lead there still joins it, which makes the record an ordinary// machine (commands.ts machine.contribute ifMissing; security review 2 of #2234).// Not where machine.contribute would refuse it (#2637): a Buddy-only record is counted already, so it still joins.@@ -150,7 +152,7 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Auth...(githubApp ? { githubApp: true as const } : {}),// Asks the host to say what it launches beyond workers (machines.ts `capabilities`): a host never sends a field this// server did not ask for, so an older server, which would refuse every reading with it, never sees it.- capabilitiesWanted: true as const }+ buddySleepWanted: true as const, capabilitiesWanted: true as const }}function assignments(tabId: string, state: SuperTabState, machineId: string, user: AuthUser) {diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 00272e846..6aa485971 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -80,11 +80,12 @@ import { sessionRows } from './memberRows.js'import { RefusalMemory } from './dispatchRefusals.js'import { tasksHoldingMoves } from './ruleGuard.js'import { candidatesFor, dispatchRules, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type DispatchLookup, type DispatchRules, type Skip } from './dispatch.js'+import { buddySleepCandidates, sleepBuddies } from './buddySleep.js'import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'import { endedReply, taskLineChats } from './taskLine.js'import { owedAsk } from './timeChecks.js'import { ledgerGroupIds, settleReleases, type ReleaseFacts, type ReleaseRules, type SettledReleases } from './releases.js'-import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'+import { groupsOf, archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'@@ -4353,7 +4354,16 @@ export class SuperTabStore {const lines = taskLineChats(loaded.state)if (lines.length) loaded = loadedFrom(row, { ...observed, groups: [...new Map([...loaded.parts.groups,...await loadGroups(tx, tabId, 'key', { key: { $in: lines } })].map(g => [g.key, g])).values()] })+ const idleBuddies = loaded.state.agents.filter(a => a.machineId === machineId && isBuddy(a) && !a.buddySession+ && observation.idleBuddyHarnessIds?.includes(a.harnessId)+ && !loaded.state.conversations.some(c => isBuddyChat(c) && c.agentIds.includes(a.id))).map(a => a.id)+ if (idleBuddies.length) {+ const homes = await loadGroups(tx, tabId, 'agents', { agentIds: { $in: idleBuddies }, deleted: false,+ 'data.kind': { $in: ['buddy', 'swarm-buddy'] } })+ loaded = loadedFrom(row, { ...observed, groups: [...new Map([...loaded.parts.groups, ...homes].map(g => [g.key, g])).values()] })+ }const state = cloneData(loaded.state)+ const buddyTouches: Touch[] = []await this.hostFor(tx, user, machineId, owned, state)const pool = await strangerRefusal(state, user.sub, () => {const found = machineContribution(state, machineId)@@ -4374,7 +4384,7 @@ export class SuperTabStore {// when a task there is lost.const saved = async (rows: MessageDraft[] = []) => {const sequences = numberMessages(state, rows, now)- const touches = judgedMachines(loaded.state, state, rows).filter(t => t.key !== machineId)+ const touches = [...judgedMachines(loaded.state, state, rows).filter(t => t.key !== machineId), ...buddyTouches]await this.endRuns(tx, tabId, loaded.state, state)await recordAttempts(tx, tabId, loaded.state, state, now)await recordEvidence(tx, tabId, loaded.state, state, now)@@ -4430,6 +4440,19 @@ export class SuperTabStore {...sweep ? sweepLiveness(state, now, rulesFor) : [], ...crew ? applyCrewKeep(state, now, crew) : [],// A woken crew member this reading shows running again: its wake's timing row (crewTimes.ts, task #3462)....finishedWakes(state, now)]+ const sleepy = observation.idleBuddyHarnessIds?.length ? buddySleepCandidates(state, now).filter(a => a.machineId === machineId) : []+ const busy = new Set<string>()+ for (const agent of sleepy) {+ const pending = await readBy(tx, 'SuperTabDelivery', 'agentOpen', [+ { $match: { tabId, agentId: agent.id, status: { $in: [...OPEN_DELIVERY] } } }, { $limit: 1 }, { $project: { _id: 0, agentId: 1 } }])+ if (pending.length) busy.add(agent.id)+ }+ sleepBuddies(state, sleepy, busy, now)+ for (const agent of sleepy.filter(a => a.asleep)) {+ // New input and work meet the agent write; home activity, membership and project switch meet these guards.+ buddyTouches.push({ kind: 'head', key: 'head' }, { kind: 'member', key: agent.buddyOf!.personId },+ ...groupsOf(state, agent).map(g => ({ kind: 'group' as const, key: g.id })))+ }// The 30-second sweep also hands out work when the Swarm, as loaded here, has a free crew member and a task for it.if (sweep && this.hooks.dispatch && projectsOf(state).some(p => {const rules = rulesFor(p.id)diff --git a/cli/e2e/superTabSwarmBuddy.e2e.ts b/cli/e2e/superTabSwarmBuddy.e2e.tsindex cb92a785f..3372eae73 100644--- a/cli/e2e/superTabSwarmBuddy.e2e.ts+++ b/cli/e2e/superTabSwarmBuddy.e2e.ts@@ -1,16 +1,16 @@-/** A person's one Buddy started on their own machine in the Swarm, on the real native protocol: a private daemon, tmux and- * data dir, a fake Claude engine and the fake backend. It has no project, so nothing is cloned and no GitHub token is asked- * for, and the folder its start names is never made: 2026-11-02, each of those failed every such start while unit tests,- * which faked the steps either side, passed. */+/** A person's Buddy on the real native protocol: a private daemon, tmux and data dir, a fake Claude engine and backend.+ * Its home copies a local fixture project without a GitHub token. Sleep releases the engine and terminal; its person's+ * message resumes the same conversation and preserved folder. Server sleep/wake policy is tested through the real store. */import { execFileSync } from 'node:child_process'-import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'-import { join } from 'node:path'+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'import { afterEach, expect, it, onTestFailed } from 'vitest'import { LocalClient } from './harness/client.js'-import { until, type IsolatedDaemon } from './harness/daemon.js'+import { IsolatedDaemon, until } from './harness/daemon.js'import { FakeBackend } from './harness/fakeBackend.js'import { signedInDaemon } from './harness/fleet.js'import { overOldRoutes } from './harness/swarmReads.js'+import { isTeamDaemon } from '../src/superTabs/teamDaemon.js'const TAB = 'buddy-tab'const ME = { machineId: 'd3'.repeat(16), computerId: 'one-buddy-fixture', name: 'Buddy fixture', token: 'fixture-buddy-token', account: 'person', email: '[email protected]' }@@ -21,9 +21,11 @@ afterEach(async () => {await relay?.close(); relay = undefined})-it('starts in a folder of its own, from the checkouts here, with no token and nothing cloned', async () => {+// A Buddy is forbidden on a Team OS account even in an isolated daemon; this native flow needs an owner's account.+it.skipIf(isTeamDaemon())('releases an idle Buddy session and wakes the same conversation on its person’s message', async () => {const backend = await FakeBackend.start(); relay = backendbackend.addMachine(ME)+ backend.me = { id: ME.account, email: ME.email }// As a real engine does: it asks about a folder it has no answer for, in a terminal no Swarm view shows.const d = await signedInDaemon(backend, ME, { ANTHROPIC_API_KEY: 'fixture-only' }, undefined, true); daemon = dwriteFileSync(join(d.env.HOME!, '.claude.json'), '{}')@@ -32,27 +34,59 @@ it('starts in a folder of its own, from the checkouts here, with no token and nogit('init', '-q'); writeFileSync(join(project, 'README.md'), 'fixture\n'); git('add', '.'); git('commit', '-qm', 'fixture')const cwd = join(d.env.HOME!, 'harnesses', 'swarms', TAB)const pool = { machineId: ME.machineId, generation: 'grant-1', cwd, scope: 'swarm', engines: ['claude'], maxAgents: 2, paused: false }- const start: Record<string, any> = { id: 'start-buddy', poolGeneration: 'grant-1', creationId: 'super-start-buddy', dispatched: false, harnessId: null, error: null,+ const start: Record<string, any> = { id: 'start-buddy', poolGeneration: 'grant-1', creationId: 'super-start-buddy', machineOwnerId: 'person', contributorId: 'person', hostGrant: null, dispatched: false, harnessId: null, error: null,request: { conversationId: 'buddy-chat', machineId: ME.machineId, engine: 'claude', name: "person's Buddy", cwd: `${cwd}/.buddy-person`, worktree: false,requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false },buddyOf: { personId: 'person', generation: 'g' }, buddyScope: 'swarm', buddyProjects: [{ id: 'p1', name: 'API', cwd: project }] } }- const agents: Array<Record<string, any>> = [], asked: string[] = []+ const agents: Array<Record<string, any>> = [], asked: string[] = [], idleReports: string[][] = []+ let pending: { id: string; conversationId: string; status: string; claimId: string | null; message: Record<string, any> } | undefined+ let managed = falsebackend.superTabs = overOldRoutes(async (method, raw, body) => {const path = new URL(raw, backend.httpUrl).pathnameif (path.endsWith('/github-token')) { asked.push(path); throw Object.assign(new Error('This start has no project folder to prepare.'), { status: 404, code: 'NOT_FOUND' }) }- if (path.endsWith('/pools')) return { data: [{ tabId: TAB, machine: pool, projects: [], starts: [], buddyStarts: start.harnessId && start.poolSettled ? [] : [start], githubApp: true, harnessIds: agents.map(a => a.harnessId) }] }+ if (path.endsWith('/pools')) return { data: [{ tabId: TAB, machine: pool, projects: [], starts: [], buddyStarts: start.harnessId && start.poolSettled ? [] : [start], githubApp: true, buddySleepWanted: managed, harnessIds: agents.map(a => a.harnessId) }] }if (path.includes('/hosts/') && path.includes('/starts/')) {if (method === 'GET') return { data: start }const c = body.commandif (c.type === 'agent.startDispatch') start.dispatched = true- else if (c.type === 'agent.started') { start.harnessId = c.harnessId; agents.push({ id: 'buddy', machineId: ME.machineId, harnessId: c.harnessId, buddyScope: 'swarm', configuration: c.configuration }) }+ else if (c.type === 'agent.started') { start.harnessId = c.harnessId; agents.push({ id: 'buddy', machineId: ME.machineId, harnessId: c.harnessId, buddyOf: start.request.buddyOf, buddyScope: 'swarm', configuration: c.configuration }) }else if (c.type === 'agent.startSettled') start.poolSettled = trueelse if (c.type === 'agent.startFailed') start.error = c.errorreturn { data: { result: {} } }}+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: agents.map(agent => ({ tabId: TAB, agent, active: true, buddySleepManaged: managed, observers: [] })) }+ if (path.endsWith('/readings')) {+ for (const reading of body.readings ?? []) if (reading.observation.idleBuddyHarnessIds) idleReports.push(reading.observation.idleBuddyHarnessIds)+ return { data: { results: (body.readings ?? []).map((r: Record<string, any>) => ({ tabId: r.tabId, ok: true })) } }+ }if (path.includes('/hosts/')) return { data: [] }- if (path.includes('/machines/')) return { data: { revision: 1 } }- if (path === `/api/super-tabs/${TAB}`) return { data: { state: { id: TAB, agents, projects: [], conversations: [] }, revision: 1 } }+ if (path.includes('/machines/')) {+ if (body?.idleBuddyHarnessIds) idleReports.push(body.idleBuddyHarnessIds)+ return { data: { revision: 1 } }+ }+ if (path === `/api/super-tabs/${TAB}`) return { data: { state: { id: TAB, agents,+ projects: [{ id: 'p1', name: 'API', cwd: project }],+ conversations: [{ id: 'buddy-chat', kind: 'swarm-buddy', buddyOwnerId: 'person', agentIds: ['buddy'] }] }, revision: 1 } }+ if (path.endsWith('/commands') && body.command?.type === 'message.send') {+ expect(body.asAgentId).toBeUndefined()+ expect(body.command.conversationId).toBe('buddy-chat')+ // Model the server's authorized wake response here; the real store regression covers its transaction and rights.+ delete agents[0]!.asleep+ pending = { id: 'wake-delivery', conversationId: 'buddy-chat', status: 'queued', claimId: null,+ message: { id: 'wake-message', conversationId: 'buddy-chat', text: body.command.text,+ author: { kind: 'person', id: 'person', name: 'Person', membershipGeneration: 'g' } } }+ return { data: { result: { messageId: 'wake-message' } } }+ }+ if (path.endsWith('/conversations/buddy-chat/messages')) return { data: { messages: [] } }+ const delivery = /\/agents\/buddy\/deliveries(?:\/([^/]+))?$/.exec(path)+ if (delivery) {+ if (method === 'GET') return { data: delivery[1] ? pending : pending && pending.status !== 'delivered' ? [pending] : [] }+ expect(pending?.id).toBe(delivery[1])+ expect(body.claimId).toBe(pending!.claimId ?? body.claimId)+ if (body.type === 'claim') { pending!.claimId = body.claimId; return { data: { message: pending!.message } } }+ pending!.status = body.uncertain ? 'uncertain' : 'delivered'+ return { data: {} }+ }if (path.endsWith('/deliveries') || path.endsWith('/grids')) return { data: [] }throw new Error(`Unexpected request ${path}`)})@@ -71,4 +105,44 @@ it('starts in a folder of its own, from the checkouts here, with no token and noexpect(folders).toHaveLength(1)expect(existsSync(join(homes, folders[0]!, 'projects', 'API', 'README.md'))).toBe(true)expect(existsSync(start.request.cwd)).toBe(false)-})+ const row = async () => (await client!.request('agents_list', { includeStopped: true })).agents.find((a: Record<string, any>) => a.id === start.harnessId)+ const original = await until('the Buddy to bind its engine conversation', async () => {+ const agent = await row()+ return agent?.sessionId && agent.status === 'active' ? agent : null+ }, 60_000, 250)+ const marker = join(homes, folders[0]!, 'kept.txt')+ writeFileSync(marker, 'Buddy memory stays here')+ const processes = join(original.claudeHome ?? dirname(d.engineConfig.claudeProjectsDir), 'sessions')+ const originalPid = await until('the fixture engine process to be identified', () => {+ if (!existsSync(processes)) return null+ const match = readdirSync(processes).filter(file => file.endsWith('.json')).map(file => JSON.parse(readFileSync(join(processes, file), 'utf8')))+ .find(record => record.sessionId === original.sessionId && IsolatedDaemon.alive(record.pid))+ return match?.pid as number | undefined+ }, 15_000, 250)+ expect(original.tmuxPane).toBeTruthy()+ managed = true+ await until('fresh positive engine idle proof', () => idleReports.some(ids => ids.includes(start.harnessId)), 60_000, 250)+ agents[0]!.asleep = { since: Date.now() }+ await until('the sleeping Buddy to release its session', async () => (await row())?.status !== 'active' || null, 60_000, 250)+ await until('the engine process to exit and its terminal pane to be released', async () => {+ const panes = await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}').catch(() => '')+ return !IsolatedDaemon.alive(originalPid) && !panes.trim().split('\n').includes(original.tmuxPane) || null+ }, 30_000, 250)+ expect(readFileSync(marker, 'utf8')).toBe('Buddy memory stays here')+ const text = 'Wake up and keep the same draft memory'+ expect(await client.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/commands`,+ body: { operationId: 'person-wakes-buddy', command: { type: 'message.send', conversationId: 'buddy-chat', text, replyTo: null, recipientIds: [] } } }))+ .toMatchObject({ ok: true, value: { result: { messageId: 'wake-message' } } })+ const resumed = await until('the awake Buddy to resume through the host', async () => {+ const agent = await row()+ return agent?.status === 'active' ? agent : null+ }, 90_000, 250)+ expect(resumed.sessionId).toBe(original.sessionId)+ expect(resumed.cwd).toBe(original.cwd)+ expect(readFileSync(marker, 'utf8')).toBe('Buddy memory stays here')+ await until('the waking message to reach the resumed engine', () => pending?.status === 'delivered' || null, 60_000, 250)+ await until('the same conversation to record the waking message', async () => {+ const page = await client!.request('session_get', { sessionId: original.sessionId, limit: 100 })+ return page.events?.some((event: Record<string, any>) => event.type === 'user_message' && String(event.payload.content).includes(text)) || null+ }, 30_000, 250)+}, 240_000)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 774d35a73..2356bb5c4 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1019,7 +1019,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {resumeAgent: async (agentId) => lifecycle.resumeAgent(agentId),// What it may close and reopen is decided in this process, on what its host retains (superTabs/inCore/agents.ts)....(swarm ? { swarmAgents: (agentDeps) => swarm.createSwarmAgents({ ...agentDeps,- members: { leads: () => swarm.retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR) },+ members: { leads: () => swarm.retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR),+ sleepingBuddies: () => swarm.retainedSleepingBuddies(env.ADAPTER_DATA_DIR) },// On a Team daemon, an ended confidential member's session data goes (set below, with the Team daemon's policy).purgeEnded: async (agentId) => teamPurge ? teamPurge(agentId) : { skipped: true } }) } : {}),dsh: (session) => backendRef?.dshFrameProvider?.(session) ?? null,diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex 39dc05131..d71f81ba7 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -23,7 +23,9 @@ export const LEAD_SWITCHING_DETAIL = 'This Product Manager is already switching* waited 30 minutes). A window closes only its view; the machine's owner still stops it with Stop Harness. */export const BUDDY_PROTECTED_DETAIL = 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.'/** `changeId`: the Change agent switch this `now` close is part of, which its handoff was prepared for (superTabs/leadSwitch.ts). */-export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number; changeId?: string }+export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number; changeId?: string+ /** Internal idle-close authority, rechecked at physical stop boundaries. Never accepted from a client payload. */+ buddySleep?: () => boolean }/** `withoutConversation`: closed while still starting, before Harness could read its conversation, so none is kept. *//** `keptRunning`: a close refused for a session that keeps running on purpose (a Swarm Buddy): a window closes its view and* stops nothing, as it does for a Swarm pane (desktop app_state.dart `canStop`). */@@ -99,7 +101,7 @@ function stillStarting(s: RegisteredSession, at: number): boolean {/** What makes two requests the same one: the agent, the mode, and whether it holds only while no tab* shows the agent. A cleanup that finds the agent on screen again must not answer the person's own close. */function jobKey(request: AgentCloseRequest): string {- return JSON.stringify([request.agentId, request.mode, request.onlyIfHidden === true, request.onlyIfOriginalLaunch === true, request.expiresAt])+ return JSON.stringify([request.agentId, request.mode, request.onlyIfHidden === true, request.onlyIfOriginalLaunch === true, request.expiresAt, request.buddySleep !== undefined])}function matches(s: RegisteredSession | undefined, request: AgentCloseRequest, at: number): s is RegisteredSession {if (!s || (request.expiresAt !== undefined && request.expiresAt <= at) || (request.onlyIfOriginalLaunch && s.startedBy !== 'agent') || new Date(s.registeredAt).toISOString() !== request.createdAt) return false@@ -128,7 +130,8 @@ export interface CloseAgentServiceDeps {/** The `now` close naming switch [changeId] ended, [stopped] or not (superTabs/leadSwitch.ts `leadSwitchEnded`): the pass its* stop was given is gone either way. */leadSwitchEnded?(agentId: string, changeId: string, stopped: boolean): void- /** Whether the agent may be a Swarm Buddy (superTabs/retention.ts `mayBeBuddy`): a close never stops it. Stop Harness does. */+ /** Whether the agent may be a Swarm Buddy (superTabs/retention.ts `mayBeBuddy`): ordinary closes never stop it.+ * Only the internal idle sleep permit or Stop Harness may do so. */buddyProtected?(agentId: string): boolean/** Whether its pane shows a question the engine asks before any conversation: the folder's trust, or an MCP server the* folder brings (`trust_open`). */@@ -192,7 +195,7 @@ export class CloseAgentService {return Promise.resolve({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })}const buddy = this.deps.buddyProtected?.(request.agentId) === true- if (buddy && request.mode !== 'inspect') {+ if (buddy && request.mode !== 'inspect' && !(request.mode === 'idle' && typeof request.buddySleep === 'function' && request.buddySleep())) {return Promise.resolve({ error: 'BUDDY_PROTECTED', detail: BUDDY_PROTECTED_DETAIL, keptRunning: true })}// A job answers only a request of its own kind. When any job running for the agent answered every@@ -305,6 +308,7 @@ export class CloseAgentService {&& s && identity(s) === target&& (request.expiresAt === undefined || request.expiresAt > this.now())&& (!request.onlyIfOriginalLaunch || s.startedBy === 'agent')+ && (request.buddySleep === undefined || (request.mode === 'idle' && typeof request.buddySleep === 'function' && request.buddySleep()))&& (!request.onlyIfHidden || this.deps.openTabs?.isHidden(s)) ? s : undefined}try {diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex fd22910a7..f6c399af2 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'// Whether this process runs as a Harness Team account, which a Buddy is never prepared in (lib/swarmSkills.ts prepareBuddyFolder).// The tests set it, so they pass the same in an owner account, a Team account and CI: it reports an owner account unless a test says.const team = vi.hoisted(() => ({ value: false }))+vi.mock('./teamDaemon.js', async original => ({ ...await original<typeof import('./teamDaemon.js')>(), isTeamDaemon: () => team.value }))vi.mock('../team/config.js', async original => ({ ...await original<typeof import('../team/config.js')>(), isTeamAccount: () => team.value }))vi.mock('./buddyHome.js', async original => {const real = await original<typeof import('./buddyHome.js')>()@@ -4526,7 +4527,7 @@ describe('ending a Buddy\'s thread sessions', () => {await t.poll()await awake(t, BUDDY_SESSION_IDLE_MS + 60_000)expect(ends(t)).toEqual([])- t.core.agents.activity = vi.fn(async () => ({ harness: 'idle' })) as never+ t.core.agents.activity = vi.fn(async () => ({ harness: 'idle' as const })) as neverawait awake(t, 5 * 60_000)await vi.waitFor(() => expect(ends(t)).toHaveLength(1))})@@ -6337,3 +6338,72 @@ describe('the PM\'s turn on its list read', () => {expect(reads(t)).toEqual(['?turn=busy', '?turn=idle'])})})+++describe('a managed main Buddy sleeps and wakes (#3824)', () => {+ const buddyRow = (agent: Record<string, unknown> = {}, row: Record<string, unknown> = {}) => ({ tabId: 'tab', active: true, buddySleepManaged: true,+ agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' }, ...agent }, ...row })+ it('closes once without dropping its home and reopens that harness on wake without continuation text', async () => {+ const rows = [buddyRow({ asleep: { since: 1 } })]+ const t = lifeFixture(rows)+ const drop = vi.spyOn(CrewFolders.prototype, 'drop'), restore = vi.spyOn(CrewFolders.prototype, 'restore')+ try {+ t.live(true)+ await t.poll()+ await t.poll(1_000)+ expect(t.closeMember).toHaveBeenCalledTimes(1)+ expect(t.keepLeadAlive).not.toHaveBeenCalled()+ t.live(false)+ delete (rows[0]!.agent as Record<string, unknown>).asleep+ await t.poll(1_000)+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')+ expect(drop).not.toHaveBeenCalled()+ expect(restore).not.toHaveBeenCalled()+ expect(t.core.turns.deliver).not.toHaveBeenCalled()+ } finally { drop.mockRestore(); restore.mockRestore() }+ })+ it.each(['working', 'unknown'])('refuses to close a live Buddy that now reads %s', async activity => {+ const t = lifeFixture([buddyRow({ asleep: { since: 1 } })])+ t.live(true)+ t.core.agents.activity = vi.fn(async () => ({ harness: activity })) as never+ await t.poll()+ await t.poll(1_000)+ expect(t.closeMember).not.toHaveBeenCalled()+ t.core.agents.activity = vi.fn(async () => ({ harness: 'idle' as const }))+ await t.poll(1_000)+ expect(t.closeMember).toHaveBeenCalledTimes(1)+ })+ it('leaves unmanaged and thread Buddies and Team sessions awake', async () => {+ for (const row of [buddyRow({ asleep: { since: 1 } }, { buddySleepManaged: undefined }),+ buddyRow({ asleep: { since: 1 }, buddySession: { thread: 'root', from: 0 } }),+ buddyRow({ asleep: { since: 1 }, teamAccount: true })]) {+ const t = lifeFixture([row])+ t.live(true)+ await t.poll()+ expect(t.closeMember).not.toHaveBeenCalled()+ }+ })+ it('resumes the recorded managed harness after a host restart, with existing retry backoff', async () => {+ const t = lifeFixture([buddyRow()])+ await t.poll()+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')+ await t.poll(1_000)+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)+ const old = lifeFixture([buddyRow({}, { buddySleepManaged: undefined })])+ await old.poll()+ expect(old.keepLeadAlive).not.toHaveBeenCalled()+ })+ it('does not finish an in-flight idle check after a newer awake roster', async () => {+ const rows = [buddyRow({ asleep: { since: 1 } })], t = lifeFixture(rows)+ t.live(true)+ let finish!: (value: Record<string, 'idle'>) => void+ t.core.agents.activity = vi.fn(() => new Promise<Record<string, 'idle'>>(resolve => { finish = resolve }))+ await t.poll()+ delete (rows[0]!.agent as Record<string, unknown>).asleep+ await t.poll(1_000)+ expect(t.core.agents.activity).toHaveBeenCalledWith(['harness'])+ finish({ harness: 'idle' })+ await new Promise(resolve => setImmediate(resolve))+ expect(t.closeMember).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 7c839d375..b78190ca3 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -183,7 +183,7 @@ interface Journal { version: 1; machineId: string; entries: Record<string, Entry/** `skillMode` is the agent's project's skills; a row without it (an older backend, a project from before modes) is orchestration.* `roleName` and `instructions` name its project's instructions (backend read/hostRows.ts); an older backend sends neither. */interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string; switchLanded?: { id?: unknown; candidateAgentId?: unknown } }; skillMode?: unknown; lead?: unknown; role?: unknown- leadsConversationId?: unknown; roleName?: unknown; instructions?: unknown }+ buddySleepManaged?: true; leadsConversationId?: unknown; roleName?: unknown; instructions?: unknown }export interface SuperTabHostOptions {now?: () => number/** What restarts a Team agent stranded on an old relay grant (relayRecovery.ts), for a spec. */@@ -1277,10 +1277,12 @@ export class SuperTabHost {void this.crewRest(target, rest)continue}+ this.buddyRestChecks.delete(restKey)+ if (isBuddy(agent)) this.rested.delete(restKey)// Rested here, or dropped before this host restarted (its record is on disk): the folder comes back first.// One restore at a time, and the keep-alive below waits for it, so the session reopens in its folder, not a missing one.// A failed one waits CREW_RESTORE_RETRY_MS, so the keep-alive (which backs off itself) is never held back for good.- if (!this.restoring.has(restKey) && (this.restoreRetryAt.get(restKey) ?? 0) <= this.now() && (this.rested.delete(restKey)+ if (!isBuddy(agent) && !this.restoring.has(restKey) && (this.restoreRetryAt.get(restKey) ?? 0) <= this.now() && (this.rested.delete(restKey)|| ((target.agent as { crew?: unknown }).crew && this.crewFolders().remembers(target.tabId, target.agent.harnessId)))) {this.restoring.set(restKey, this.crewFolders().restore(target.tabId, target.agent.harnessId).catch(() => 'failed' as const).then(result => { if (result === 'failed') this.restoreRetryAt.set(restKey, this.now() + CREW_RESTORE_RETRY_MS); else this.restoreRetryAt.delete(restKey) })@@ -1295,7 +1297,11 @@ export class SuperTabHost {} else if (isCrewRow(row)) {// A project's crew is kept alive as its PM is (task #3397): reopened in place, then told to continue its task.leads.add(target.agent.harnessId)- if (!this.restoring.has(restKey)) this.keepAlive(target.agent.harnessId, true)+ if (!this.restoring.has(restKey)) this.keepAlive(target.agent.harnessId, 'crew')+ }+ else if (row.buddySleepManaged === true && isBuddy(agent) && !agent.buddySession && !agent.modelRequest) {+ leads.add(target.agent.harnessId)+ this.keepAlive(target.agent.harnessId, 'buddy')}// Never adopt another live session as a replacement for the recorded harness.if (!this.core.agents.byAgent(target.agent.harnessId) || !this.core.agents.terminalAvailable(target.agent.harnessId)) continue@@ -1457,6 +1463,7 @@ export class SuperTabHost {* off, so an engine that cannot start never spins. *//** Crew members closed for rest, by tab and harness, with what closed them: closed once per rest, and when one wakes, its* dropped folder comes back before its keep-alive reopens it (crewFolders.ts). */+ private readonly buddyRestChecks = new Map<string, symbol>()private readonly rested = new Map<string, 'sleep' | 'drop' | 'moving'>()/** A dropped folder being brought back, by the same key: its keep-alive waits for it (review of #3229). */private readonly restoring = new Map<string, Promise<unknown>>()@@ -1483,9 +1490,23 @@ export class SuperTabHost {private async crewRest(row: HostAgent, rest: 'sleep' | 'drop' | 'moving'): Promise<void> {const key = `${row.tabId}:${row.agent.harnessId}`if (this.rested.get(key) === rest) return+ const buddy = isBuddy(object(row.agent)), agent = object(row.agent)+ if (buddy && (row.buddySleepManaged !== true || agent.buddySession || agent.modelRequest || agent.teamAccount || isTeamDaemon() || rest !== 'sleep')) returnthis.rested.set(key, rest)+ const check = Symbol()+ if (buddy) this.buddyRestChecks.set(key, check)try {- if (this.core.agents.byAgent(row.agent.harnessId)) {+ const live = this.core.agents.byAgent(row.agent.harnessId)+ if (live) {+ if (buddy) {+ const activity = await this.core.agents.activity([row.agent.harnessId])+ if (this.stopped || this.buddyRestChecks.get(key) !== check) return+ const current = this.core.agents.byAgent(row.agent.harnessId)+ if (activity[row.agent.harnessId] !== 'idle' || current?.sessionId !== live.sessionId || current?.registeredAt !== live.registeredAt) {+ this.rested.delete(key)+ return+ }+ }const closed = await this.core.agents.closeMember?.(row.agent.harnessId)if (closed && 'error' in closed && closed.error) throw new Error(closed.error)}@@ -1493,11 +1514,12 @@ export class SuperTabHost {} catch (error) {// Tried again on the next roster: the server still says it rests.this.rested.delete(key)- this.log(`Crew rest: ${error instanceof Error ? error.message.slice(0, 80) : typeof error}`)- }+ this.log(`${buddy ? 'Buddy' : 'Crew'} rest: ${error instanceof Error ? error.message.slice(0, 80) : typeof error}`)+ } finally { if (this.buddyRestChecks.get(key) === check) this.buddyRestChecks.delete(key) }}- private keepAlive(harnessId: string, crew = false): void {+ private keepAlive(harnessId: string, kind: 'pm' | 'crew' | 'buddy' = 'pm'): void {+ const crew = kind === 'crew'const reopen = this.core.agents.keepLeadAliveif (!reopen) returnconst state = this.keepAlives.get(harnessId) ?? { running: false, failures: 0, retryAt: 0 }@@ -1525,7 +1547,7 @@ export class SuperTabHost {state.running = trueconst failed = (reason: string) => {state.retryAt = this.now() + Math.min(LEAD_RETRY_MAX_MS, LEAD_RETRY_MS * 2 ** state.failures++)- if (reason !== state.reason) this.log(`Could not reopen the ${crew ? 'crew member' : 'Product Manager'} ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)+ if (reason !== state.reason) this.log(`Could not reopen the ${kind === 'buddy' ? 'Buddy' : crew ? 'crew member' : 'Product Manager'} ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)state.reason = reason}void (async () => {diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.tsindex 9c521cd08..c9f5b5123 100644--- a/cli/src/superTabs/inCore.ts+++ b/cli/src/superTabs/inCore.ts@@ -20,7 +20,7 @@ export { createSwarmAgents } from './inCore/agents.js'export { SWARM_LAUNCH } from './inCore/launch.js'export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor, teamPurgeReport, withPurgeRetries } from './inCore/teamApps.js'export { typesWhileBusy } from './inCore/deliveries.js'-export { mayBeBuddy, retainedHarnesses, retainedLeads } from './retention.js'+export { mayBeBuddy, retainedHarnesses, retainedLeads, retainedSleepingBuddies } from './retention.js'export { recordCleanupClose } from './cleanupCloses.js'// A Product Manager switched from its pane (Change agent) is the one stop of a Lead its close guard and stop guard let through.export { leadCloseProtected, leadSwitchEnded, leadSwitching, mayBeLead } from './leadSwitch.js'diff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.tsindex 65d7ec4f7..efd1dff8c 100644--- a/cli/src/superTabs/inCore/agents.ts+++ b/cli/src/superTabs/inCore/agents.ts@@ -9,7 +9,7 @@ import { PURGE_RECORD_UNREADABLE } from './teamPurge.js'export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members, purgeEnded }: SwarmAgentDeps & {/** The Leads and crew (`leads`) and members this machine's Super Tab host keeps (superTabs/retention.ts). */- members: { leads(): Set<string>; harnesses(): Set<string> }+ members: { leads(): Set<string>; harnesses(): Set<string>; sleepingBuddies?(): Set<string> }/** On a Team daemon, deletes the session data of a confidential member the Swarm ended (inCore/teamApps.ts); absent elsewhere. */purgeEnded?: (agentId: string) => Promise<Record<string, unknown>>}): SwarmAgents {@@ -68,6 +68,16 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgentmember = creation?.state === 'created' && creation.agentId === agentId}if (!member) return { error: 'NOT_A_MEMBER' }+ // A server-managed Buddy sleeps only while the latest roster still asks, under the close service's idle fences.+ // This function stays in the core: no window or wire request can supply the non-serializable permit.+ if (members.sleepingBuddies?.().has(agentId)) {+ let revoked = false+ const buddySleep = () => {+ if (!members.sleepingBuddies?.().has(agentId)) revoked = true+ return !revoked+ }+ return closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'idle', buddySleep })+ }// The close itself refuses a session that changed during the receipt read.const closed = await closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'now' })return 'closed' in closed && closed.closed ? ended(agentId, closed) : closeddiff --git a/cli/src/superTabs/inCore/buddySleep.spec.ts b/cli/src/superTabs/inCore/buddySleep.spec.tsnew file mode 100644index 000000000..aebf16947--- /dev/null+++ b/cli/src/superTabs/inCore/buddySleep.spec.ts@@ -0,0 +1,103 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { CloseAgentService, type CloseAgentServiceDeps } from '../../lib/closeAgentService.js'+import { registry } from '../../lib/registry.js'+import { createSwarmAgents } from './agents.js'+import * as retention from '../retention.js'+import * as team from '../teamDaemon.js'++let dir: string, close: CloseAgentService+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'buddy-native-close-'))+ vi.spyOn(team, 'isTeamDaemon').mockReturnValue(false)+})+afterEach(() => {+ close?.dispose()+ for (const row of registry.list()) registry.removeAgent(row.agentId)+ vi.restoreAllMocks()+ rmSync(dir, { recursive: true, force: true })+})++// Keep the real Swarm authority, retention, close guard and idle recheck together. Faking closeMember hid the native+// refusal in #3824: the host correctly asked to sleep, but the ordinary Buddy close guard always kept it running.+function fixture(options: { phase?: 'activity' | 'checkpoint' | 'stop'; revoke?: 'wake' | 'corrupt'; activity?: 'working' | 'unknown' } = {}) {+ const row = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%88' }], cwd: dir })!+ Object.assign(row, { sessionId: 'kept-conversation', startedBy: 'agent' })+ const hostRow = (agent: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) => ({ tabId: 'tab', active: true, buddySleepManaged: true,+ agent: { harnessId: row.agentId, machineId: 'machine', buddyOf: { personId: 'person', generation: 'g' }, asleep: { since: 1 }, ...agent }, ...extra })+ const roster = (agent: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) => retention.retainContributions(dir, 'machine', [hostRow(agent, extra)])+ roster()+ const revoke = (phase: string) => {+ if (options.phase !== phase) return+ if (options.revoke === 'corrupt') writeFileSync(retention.retentionFile(dir), '{')+ else roster({ asleep: undefined })+ }+ const deps: CloseAgentServiceDeps = { registry,+ buddyProtected: id => retention.mayBeBuddy(dir, id),+ activity: async () => { revoke('activity'); return options.activity ?? 'idle' },+ checkpoint: async () => { revoke('checkpoint') },+ changed: () => {},+ stop: async (id, options) => {+ await options.checkpoint?.(row, 'before')+ await options.beforeStop?.(row)+ revoke('stop')+ if (options.current?.() === false) throw new Error('close authority revoked')+ registry.removeAgent(id)+ } }+ close = new CloseAgentService(deps)+ const purge = vi.fn(async () => ({ ok: true }))+ const swarm = createSwarmAgents({ byAgent: id => registry.byAgent(id), stoppedIds: () => [], closeAgent: request => close.request(request),+ members: { harnesses: () => retention.retainedHarnesses(dir), leads: () => retention.retainedLeads(dir),+ sleepingBuddies: () => retention.retainedSleepingBuddies(dir) }, purgeEnded: purge })+ return { row, roster, swarm, purge }+}++it('sleeps a server-managed idle Buddy through the real close guard, without deleting its conversation', async () => {+ const f = fixture()+ expect(await f.swarm.closeMember(f.row.agentId)).toEqual({ closed: true })+ expect(registry.byAgent(f.row.agentId)).toBeUndefined()+ expect(f.purge).not.toHaveBeenCalled()+})++it.each(['working', 'unknown'] as const)('preserves a Buddy whose last native activity is %s', async activity => {+ const f = fixture({ activity })+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: 'SESSION_NOT_IDLE' })+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)+})++it.each(['activity', 'checkpoint', 'stop'] as const)('a newer awake roster revokes sleep during %s', async phase => {+ const f = fixture({ phase, revoke: 'wake' })+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: expect.any(String) })+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)+})++it('an unreadable retention revokes sleep after the checkpoint', async () => {+ const f = fixture({ phase: 'checkpoint', revoke: 'corrupt' })+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: expect.any(String) })+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)+})++it.each([+ ['awake', { asleep: undefined }, {}],+ ['thread', { buddySession: { thread: 'root' } }, {}],+ ['model request', { modelRequest: { id: 'request' } }, {}],+ ['Team session', { teamAccount: true }, {}],+ ['unmanaged', {}, { buddySleepManaged: undefined }],+ ['stopping', {}, { stopRequested: true }],+] as const)('keeps a protected %s Buddy running', async (_name, agent, extra) => {+ const f = fixture()+ f.roster(agent, extra)+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: 'BUDDY_PROTECTED' })+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)+})++it('never sleeps a Buddy on a Team daemon or grants a normal window close the sleep permit', async () => {+ const f = fixture()+ const request = { agentId: f.row.agentId, sessionId: f.row.sessionId, createdAt: new Date(f.row.registeredAt).toISOString(), mode: 'idle' as const }+ expect(await close.request(request)).toMatchObject({ error: 'BUDDY_PROTECTED' })+ vi.mocked(team.isTeamDaemon).mockReturnValue(true)+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: 'BUDDY_PROTECTED' })+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)+})diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 20495c24b..50822418d 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -3065,3 +3065,68 @@ describe('a launched start whose engine stops on a screen', () => {expect(failures()).toEqual([])})})+++describe('fresh Buddy idle proof (#3824)', () => {+ const posts = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && c[2].includes('/machines/')).map(c => c[3] as Record<string, unknown>)+ function buddies() {+ const f = fixture()+ Object.assign(f.pool, { buddySleepWanted: true, starts: [], harnessIds: ['idle', 'busy', 'unknown', 'worker'] })+ f.core.agents.byAgent = vi.fn(id => ({ agentId: id, swarmSkill: { role: id === 'worker' ? 'worker' : 'buddy' } }) as never)+ f.core.agents.activity = vi.fn(async (ids: string[]) => Object.fromEntries(ids.map(id => [id, id === 'idle' ? 'idle' : id === 'busy' ? 'working' : 'unknown']))) as never+ return f+ }+ it('reports explicit idle alone in one bounded activity batch', async () => {+ const f = buddies()+ await f.machine.tick()+ expect(posts(f)[0]).toHaveProperty('idleBuddyHarnessIds', ['idle'])+ expect(f.core.agents.activity).toHaveBeenCalledTimes(1)+ expect(f.core.agents.activity).toHaveBeenCalledWith(['idle', 'busy', 'unknown'])+ })+ it('reads every Buddy past the core’s 64-session activity limit in bounded batches', async () => {+ const f = buddies(), ids = Array.from({ length: 100 }, (_, i) => `buddy-${i}`)+ Object.assign(f.pool, { harnessIds: ids })+ f.core.agents.activity = vi.fn(async (batch: string[]) => Object.fromEntries(batch.slice(0, 64).map(id => [id, 'idle']))) as never+ await f.machine.tick()+ expect(posts(f)[0]).toHaveProperty('idleBuddyHarnessIds', ids)+ expect(vi.mocked(f.core.agents.activity).mock.calls.map(([batch]) => batch.length)).toEqual([64, 36])+ // The report already checked these sessions; idle proof adds no per-session core round trips.+ expect(f.core.agents.stopped).toHaveBeenCalledTimes(ids.length)+ })+ it('does not ask for activity or send proof without the server request or running Buddies', async () => {+ const older = buddies()+ Object.assign(older.pool, { buddySleepWanted: undefined })+ await older.machine.tick()+ expect(posts(older)[0]).not.toHaveProperty('idleBuddyHarnessIds')+ expect(older.core.agents.activity).not.toHaveBeenCalled()+ const workers = fixture()+ Object.assign(workers.pool, { buddySleepWanted: true })+ await workers.machine.tick()+ expect(workers.core.agents.activity).not.toHaveBeenCalled()+ })+ it('never refreshes idle proof with an unchanged heartbeat', async () => {+ const f = buddies()+ f.pool.starts = [{ id: 'start', dispatched: false }]+ let finish!: () => void+ f.start.mockImplementation(() => new Promise(resolve => { finish = () => resolve({ ok: true }) }))+ const pass = f.machine.tick()+ await vi.waitFor(() => expect(f.start).toHaveBeenCalled())+ try {+ f.step(15_000)+ f.machine.beat()+ await vi.waitFor(() => expect(posts(f)).toHaveLength(2))+ expect(posts(f)[0]).toHaveProperty('idleBuddyHarnessIds', ['idle'])+ expect(posts(f)[1]).not.toHaveProperty('idleBuddyHarnessIds')+ expect(f.core.agents.activity).toHaveBeenCalledTimes(1)+ } finally { finish(); await pass }+ })+ it('shares one activity read across Swarms on the same machine', async () => {+ const f = buddies(), original = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => path.includes('/hosts/host/changes')+ ? hostForm([], { pools: [f.pool, { ...f.pool, tabId: 'other' }] }) : original(core, method, path, body))+ await f.machine.tick()+ expect(posts(f)).toHaveLength(2)+ expect(posts(f).every(p => (p.idleBuddyHarnessIds as string[])?.join() === 'idle')).toBe(true)+ expect(f.core.agents.activity).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 072c720f6..edb7ef5d2 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -559,6 +559,18 @@ export class ContributedMachines {// Every Swarm's reading first, sent in one call (DB roadmap 2.5), then each Swarm's starts.const looked: Array<{ row: Record<string, unknown>; pool: Record<string, unknown>; pending: ReturnType<typeof startsOf> }> = []const due: Reading[] = []+ // One activity batch for this machine's Buddies, shared across its Swarms and only on a fresh report (#3824).+ let buddyActivity: Promise<Record<string, 'working' | 'idle' | 'unknown'>> | undefined+ const readBuddyActivity = async (): Promise<Record<string, 'working' | 'idle' | 'unknown'>> => {+ const ids = [...new Set(pools.filter(row => row.buddySleepWanted === true).flatMap(row =>+ Array.isArray(row.harnessIds) ? row.harnessIds.filter(identifier) : []))]+ .filter(id => this.core.agents.byAgent(id)?.swarmSkill?.role === 'buddy').slice(0, 1000)+ // byAgent is the live registry; each pool already checks stopped sessions before it builds its running list.+ // The core accepts 64 activity IDs per request (core/experimentQueries.ts); more must not remain awake forever.+ const states: Record<string, 'working' | 'idle' | 'unknown'> = {}+ for (let offset = 0; offset < ids.length; offset += 64) Object.assign(states, await this.core.agents.activity(ids.slice(offset, offset + 64)))+ return states+ }// The sessions the idle cleanup closed, read once a pass: only those the backend refuses work (review of #2953).const cleaned = began >= this.closedRefusedUntil ? cleanupClosed(this.core.dataDir, began) : new Set<string>()for (const row of pools) {@@ -598,6 +610,7 @@ export class ContributedMachines {pending.map(start => start.id).sort(), [...preparing].sort(), refusedStarts.map(r => r.startId).sort(),// A privacy result that changes (a home folder opened again) is sent at once, not on the next beat.privacy ? [privacy.mode, 'passed' in privacy ? privacy.passed : null, 'item' in privacy ? privacy.item : null] : null,+ row.buddySleepWanted === true,typeof row.localGrid === 'string' ? modelsStamp : null])const last = this.published.get(String(row.tabId))// A model still starting is read again every pass until the grid lists it, so the panel shows it live at once.@@ -665,8 +678,14 @@ export class ContributedMachines {// every reading with it.// Only to a backend that asks for capabilities, as it is new enough to know the field: an older one refuses it.const profiles = row.capabilitiesWanted === true && began >= this.profilesRefusedUntil ? await this.profiles(local, engines, allowances) : []+ const idleBuddies: Record<string, string> | null = row.buddySleepWanted === true+ ? await (buddyActivity ??= readBuddyActivity().catch(error => {+ this.log(`Could not read Buddy activity: ${error instanceof Error ? error.name : typeof error}`)+ return {}+ })) : nullconst observation = { generation: pool.generation, tools: reportedTools, ...(Object.keys(tokens).length ? { harnessTokens: tokens } : {}),...(Object.keys(quotaReasons).length ? { quotaReasons } : {}),+ ...(idleBuddies ? { idleBuddyHarnessIds: running.filter(id => idleBuddies[id] === 'idle').slice(0, 1000) } : {}),...(profiles.length ? { profiles } : {}),...(row.capabilitiesWanted === true ? { capabilities: CAPABILITIES } : {}),...(preparing.length ? { preparingStartIds: preparing } : {}),@@ -910,9 +929,9 @@ export class ContributedMachines {return lost}- /** What [beat] sends again for a Swarm: the reading the backend took, without whether folders hold uncommitted work. */+ /** What [beat] sends again for a Swarm: the reading the backend took, without folder or Buddy idle proof; an unchanged heartbeat cannot vouch for either. */private taken(tab: string, body: Record<string, unknown>) {- const { harnessUncommitted: _fresh, ...kept } = body+ const { harnessUncommitted: _fresh, idleBuddyHarnessIds: _idle, ...kept } = bodythis.lastSent.set(tab, { path: `/api/super-tabs/${tab}/machines/${this.machineId}`, body: kept, at: this.deps.now() })}@@ -924,7 +943,8 @@ export class ContributedMachines {*/private async sendAlone({ tab, observation, localModels }: Reading, began: number, refused?: SuperTabHostError): Promise<void> {const path = `/api/super-tabs/${tab}/machines/${this.machineId}`- const { closedHarnessIds: _closed, ...unclosed } = observation+ const { idleBuddyHarnessIds: _idle, ...withoutIdle } = observation+ const { closedHarnessIds: _closed, ...unclosed } = withoutIdleconst { refusedStarts: _refusedStarts, ...unrefused } = unclosedconst { profiles: _profiles, ...unprofiled } = unrefusedconst { quotaReasons: _reasons, ...unreasoned } = unprofiled@@ -938,7 +958,7 @@ export class ContributedMachines {// A backend before `starting` refuses it: it gets the models the grid lists, as before, not none at all.const listedOnly = localModels?.some(m => m.starting)? [{ ...withoutPrivacy, localModels: localModels.filter(m => !m.starting) }] : []- const attempts = [...('closedHarnessIds' in observation ? [observation] : []), ...('refusedStarts' in unclosed ? [unclosed] : []), ...('profiles' in unrefused ? [unrefused] : []), ...('quotaReasons' in unprofiled ? [unprofiled] : []), ...('harnessTokens' in unreasoned ? [unreasoned] : []), ...('preparingStartIds' in untokened ? [untokened] : []),+ const attempts = [...('idleBuddyHarnessIds' in observation ? [observation] : []), ...('closedHarnessIds' in withoutIdle ? [withoutIdle] : []), ...('refusedStarts' in unclosed ? [unclosed] : []), ...('profiles' in unrefused ? [unrefused] : []), ...('quotaReasons' in unprofiled ? [unprofiled] : []), ...('harnessTokens' in unreasoned ? [unreasoned] : []), ...('preparingStartIds' in untokened ? [untokened] : []),...('harnessUncommitted' in unprepared ? [unprepared] : []),...('readiness' in known ? [known] : []), ready, ...('harnessProgress' in ready ? [withoutProgress] : []),...('privacy' in withoutProgress ? [withoutPrivacy] : []), ...listedOnly,diff --git a/cli/src/superTabs/retention.spec.ts b/cli/src/superTabs/retention.spec.tsindex 4a3aae523..9ed8483f2 100644--- a/cli/src/superTabs/retention.spec.ts+++ b/cli/src/superTabs/retention.spec.ts@@ -206,3 +206,19 @@ it('keeps a crew member with no open group, past the lapse, and names it among texpect([...retainedHarnesses(dir, now)]).toEqual(['pm'])expect([...retainedLeads(dir)]).toEqual(['pm'])})+++it('grants resume only to server-managed main Buddies and revokes it on stop or removal (#3824)', () => {+ const dir = root()+ const buddy = (id: string, extra: Record<string, unknown> = {}, agent: Record<string, unknown> = {}) => row(id,+ { agent: { harnessId: id, machineId: 'machine', buddyOf: { personId: 'peer', generation: 'g' }, ...agent }, ...extra })+ retainContributions(dir, 'machine', [buddy('managed', { buddySleepManaged: true }), buddy('old'),+ buddy('thread', { buddySleepManaged: true }, { buddySession: { thread: 'root' } }),+ buddy('stopping', { buddySleepManaged: true, stopRequested: true })])+ expect([...retainedLeads(dir)]).toEqual(['managed'])+ expect(mayBeBuddy(dir, 'managed')).toBe(true)+ retainContributions(dir, 'machine', [buddy('managed', { stopRequested: true }), buddy('old')])+ expect([...retainedLeads(dir)]).toEqual([])+ retainContributions(dir, 'machine', [])+ expect([...retainedHarnesses(dir)]).toEqual([])+})diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.tsindex d69ad4c32..54f982165 100644--- a/cli/src/superTabs/retention.ts+++ b/cli/src/superTabs/retention.ts@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, utimesSync,import { dirname, join } from 'node:path'import { isCrewRow } from './crew.js'import { identifier, object } from './wire.js'+import { isTeamDaemon } from './teamDaemon.js'/** `leads`: the Leads of active projects here, which never lapse (owner, 2026-10-23: the Lead of an active project is never* stopped in any case). Absent in a file from before Leads were kept.@@ -18,8 +19,10 @@ import { identifier, object } from './wire.js'* `assigned`: when the host first received each assignment its harnesses hold, epoch ms. Such a harness is in `harnesses`* while it holds it and for ASSIGNED_GRACE_MS after it came, whatever its groups (task #2744). Absent in older files.* `crew`: its project's crew here (crew.ts isCrewRow, task #3397), kept as Leads are: in no open group and past the lapse,- * and reopened by the core when gone. Absent in older files. */-interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[]; crew?: string[]; buddies?: string[]; assigned?: Record<string, number> }+ * and reopened by the core when gone. Absent in older files.+ * `wakeableBuddies`: only main Buddies the server manages for sleep (#3824); ordinary Buddies gain no resume authority.+ * `sleepingBuddies`: the subset its latest roster puts to sleep, revoking the internal close permit when awake. */+interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[]; crew?: string[]; buddies?: string[]; wakeableBuddies?: string[]; sleepingBuddies?: string[]; assigned?: Record<string, number> }export const retentionFile = (dataDir: string) => join(dataDir, 'super-tabs', 'retained.json')export const RETENTION_LAPSE_MS = 7 * 24 * 60 * 60_000const REFRESH_MS = 60 * 60_000@@ -34,6 +37,8 @@ function read(file: string): Retention {if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)|| (value.leads !== undefined && (!Array.isArray(value.leads) || !value.leads.every(identifier)))|| (value.crew !== undefined && (!Array.isArray(value.crew) || !value.crew.every(identifier)))+ || (value.wakeableBuddies !== undefined && (!Array.isArray(value.wakeableBuddies) || !value.wakeableBuddies.every(identifier)))+ || (value.sleepingBuddies !== undefined && (!Array.isArray(value.sleepingBuddies) || !value.sleepingBuddies.every(identifier)))|| (value.buddies !== undefined && (!Array.isArray(value.buddies) || !value.buddies.every(identifier)))|| (value.assigned !== undefined && !Object.entries(object(value.assigned)).every(([id, at]) => identifier(id) && Number.isFinite(at)))) {throw new Error('Super Tab retention is unreadable. Automatic cleanup is paused.')@@ -49,10 +54,21 @@ export function retainedHarnesses(dataDir: string, now = Date.now()): Set<stringreturn new Set(read(file).harnesses)}-/** The sessions here the host may reopen, the Leads and the crew: only those a valid roster named. The core reads it as its+/** The sessions here the host may reopen, the Leads, crew and managed main Buddies: only those a valid roster named. The core reads it as its* Leads (core/main.ts, inCore/agents.ts keepLeadAlive), so a crew member reopens exactly as a Lead does. */export function retainedLeads(dataDir: string): Set<string> {- try { const kept = read(retentionFile(dataDir)); return new Set([...kept.leads ?? [], ...kept.crew ?? []]) } catch { return new Set() }+ try { const kept = read(retentionFile(dataDir)); return new Set([...kept.leads ?? [], ...kept.crew ?? [], ...kept.wakeableBuddies ?? []]) } catch { return new Set() }+}++/** Only the server's current sleep instruction grants an idle close, never a window's Close or a Team purge. A new+ * awake roster revokes it even while checkpointing. Missing, lapsed or unreadable authority grants no sleep. */+export function retainedSleepingBuddies(dataDir: string, now = Date.now()): Set<string> {+ try {+ if (isTeamDaemon()) return new Set()+ const file = retentionFile(dataDir)+ if (now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return new Set()+ return new Set(read(file).sleepingBuddies ?? [])+ } catch { return new Set() }}/** Whether a stop may reach a Lead, for the core's guard, which fails closed (the review of #1635): with no file this@@ -88,7 +104,7 @@ export function retainContributions(dataDir: string, machineId: string, rows: un// file and another identity's entry. Unchanged rosters only refresh the lapse clock.let previous: Retention | null = nulltry { if (existsSync(file)) previous = read(file) } catch { /* rebuilt below */ }- const ids = new Set<string>(), leads = new Set<string>(), crew = new Set<string>(), buddies = new Set<string>()+ const ids = new Set<string>(), leads = new Set<string>(), crew = new Set<string>(), buddies = new Set<string>(), wakeableBuddies = new Set<string>(), sleepingBuddies = new Set<string>()for (const item of rows) {const row = object(item), agent = object(row.agent)if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue@@ -100,7 +116,13 @@ export function retainContributions(dataDir: string, machineId: string, rows: un}// A Buddy is in no open group, yet waits for its person however long (backend tidy.ts). Only the server marks one (its// agent's buddyOf, set when a person adds their Buddy); a row that ends it carries no agent record, so it is no Buddy.- if (identifier(object(agent.buddyOf).personId)) buddies.add(agent.harnessId)+ if (identifier(object(agent.buddyOf).personId)) {+ buddies.add(agent.harnessId)+ if (row.buddySleepManaged === true && !agent.buddySession && row.stopRequested !== true) {+ wakeableBuddies.add(agent.harnessId)+ if (agent.asleep && !agent.modelRequest && !agent.teamAccount) sleepingBuddies.add(agent.harnessId)+ }+ }if (row.lead === true) leads.add(agent.harnessId)// One whose stop is asked for is no crew the core may reopen (security review 1 of #3222).else if (isCrewRow(row) && row.stopRequested !== true) crew.add(agent.harnessId)@@ -115,7 +137,8 @@ export function retainContributions(dataDir: string, machineId: string, rows: un}for (const [id, at] of Object.entries(before)) if (!(id in assigned) && now - at < ASSIGNED_GRACE_MS) assigned[id] = atfor (const id of Object.keys(assigned)) ids.add(id)- const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort(), ...(crew.size ? { crew: [...crew].sort() } : {}), buddies: [...buddies].sort(),+ const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort(), ...(crew.size ? { crew: [...crew].sort() } : {}), buddies: [...buddies].sort(), ...(wakeableBuddies.size ? { wakeableBuddies: [...wakeableBuddies].sort() } : {}),+ ...(sleepingBuddies.size ? { sleepingBuddies: [...sleepingBuddies].sort() } : {}),assigned: Object.fromEntries(Object.entries(assigned).sort(([a], [b]) => a.localeCompare(b))) }if (previous && JSON.stringify(previous) === JSON.stringify(next)) {if (now - statSync(file).mtimeMs > REFRESH_MS) utimesSync(file, new Date(now), new Date(now))diff --git a/docs/plans/2026-11-06-buddy-sleep-plan.md b/docs/plans/2026-11-06-buddy-sleep-plan.mdnew file mode 100644index 000000000..27f966904--- /dev/null+++ b/docs/plans/2026-11-06-buddy-sleep-plan.md@@ -0,0 +1,111 @@+# Idle Buddies sleep and wake implementation plan++> Implement natively, task by task, with a committed failing test before each production change and one independent review of the finished branch.++**Goal:** Idle Buddies release their running sessions after an hour and resume for their person's message or an authorized question about their proposal.++**Architecture:** Reuse the server-owned agent `asleep` mark and the host's existing rest/resume path. A bounded optional machine report proves which Buddy sessions are idle; the server checks the report, project switch, current identity, idle time, active work and pending deliveries. Numbering an authorized message wakes its Buddy recipients in the same guarded write. A host rechecks engine activity before rest and reopens a managed Buddy only after the server clears its asleep mark.++**Tech Stack:** TypeScript, existing Prisma/MongoDB parts transactions, Vitest, fake CLI core and real local MongoDB integration tests.++**Spec:** `docs/plans/2026-11-06-buddy-board-final-spec.md`, Many Buddies and Phase 2; task #3824.++## Global Constraints++- Projects not switched behave as today. Server enforces rights and identity remains the person's.+- One hour idle (`SLEEP_IDLE_MS`), same as crew. A busy Buddy never closes.+- Only the main Buddy sleeps here; thread-session lifecycle remains its existing host path.+- A Swarm-wide Buddy may sleep only when all projects its person can read are switched; this avoids changing an unswitched project's Buddy behavior. A project Buddy requires its project switched.+- Team-account sessions stay awake: their current close destroys the data a resume needs (existing crew safeguard). No changes to Team purge or identity.+- Preserve the Buddy home and engine conversation during rest. Long-term folder cleanup is not part of this task's memory/quota lifecycle; no new deletion path.+- No new collections, indexes, runtime dependencies, timers or whole-state polling. Optional fields are backend-first and absent on older reports.+- Keep each completed task pushed. Automatic PR CI runs the whole suites; locally run affected checks only.++## Design++- Growth: one bounded idle-session list on an existing machine part, replaced per report; existing asleep field on the agent, cleared on wake/removal. No content or credentials stored.+- Concurrency: the report's sleep decision guards Buddy, home group, member and project parts; every authorized delivery guards its Buddy even when already awake, meeting concurrent sleep. Pending deliveries checked by the existing tab/agent/status index. A host checks live engine state before closing.+- Read cost: one existing machine observation, one batched core activity read for main Buddy sessions on that machine, and an indexed existence read only for sleep candidates. No screen or transcript read added.+- Scale: existing Buddy cap and 1,000-session report bound; measure pure decision and host call count at 10x. No per-Buddy polling loop.+- Compatibility: the pool asks for the optional idle field, so old servers never receive it. An old host has no idle proof and sleeps no Buddy. Existing clients already understand asleep agents for crew.+- Migration/rollback: no migration; absent proof means awake. Once awake, a managed Buddy resumes using existing engine state. Preserve management for a sleeping Buddy if its project switches back, so its next message still wakes it.+- Audience/identity: use current Buddy owner generation and existing recipient permission checks; never change machineOwnerId, contributorId or Buddy ownership.+- Failure: missing/unknown/stale activity is not idle. A failed close retries through existing logged rest handling; a failed reopen uses existing bounded backoff.+- Platforms: backend and CLI on macOS/Linux/Windows; no UI or process-launch implementation changes.++## Review Focus++1. A long-running or unknown engine turn must not be stopped even with an old server roster (Task 3).+2. A person leaving/rejoining or a project still using chat cannot gain a wake or be put to sleep under another identity (Tasks 1/2).+3. A queued/claimed/uncertain delivery prevents sleep; a simultaneous new message must conflict with the sleep decision (Tasks 1/2).+4. A stale unchanged heartbeat cannot refresh idle proof; a new message just before sleep cannot be erased (Tasks 1/3).+5. Two Buddies of one person remain separate; a question wakes only its intended recipient, and a host restart resumes the recorded session (Tasks 2/3).++### Task 1: Server decides idle Buddy sleep++**Files:** create `backend/src/superTabs/buddySleep.ts` and `.test.ts`; modify `machines.ts`, `read/hostRows.ts`, `store.ts`; test `integration/superTabBuddies.test.ts` and relevant machine observations.++**Interfaces:** `buddySleepManaged(state, agent): boolean`; `buddySleepCandidates(state, now): Agent[]`; `sleepBuddies(state, candidates, busy, now): void`. Optional `MachineObservation.idleBuddyHarnessIds: string[]` holds running sessions explicitly idle in that fresh report; pool `buddySleepWanted` opts a host into reporting. Host agent row `buddySleepManaged` grants retention/resume of that main Buddy.++- [x] Commit failing tests for the one-hour boundary, current owner generation, switched/unswitched/mixed projects, main vs thread sessions, unknown/stale/working proof, pending delivery and active task.+- [x] Watch targeted tests fail for missing sleep behavior.+- [x] Implement the pure eligibility/decision and report plumbing; reuse existing asleep mark. Filter report IDs against running sessions; unchanged reports compare the idle set too. Read pending delivery existence for candidates only and guard all state used by sleep.+- [x] Run affected units and the focused real-store sleep case; commit passing implementation and push.++### Task 2: Authorized input wakes the intended Buddy atomically++**Files:** modify `backend/src/superTabs/parts/commit.ts`, `parts/touches.ts`, `buddySleep.ts`; test `buddySleep.test.ts`, `parts/touches.test.ts`, `integration/superTabBuddies.test.ts`.++**Interfaces:** `wakeBuddies(state, message, now): void`, called by `numberMessages` before agent-only rows are skipped. Uses final message recipients and buddyRecipients, with the existing Buddy read checks; clears asleep, renews keptAt/downSince, records startWake for existing timing telemetry.++- [x] Commit failing tests: own-person message and authorized proposal question wake one sleeping main Buddy; another Buddy stays asleep; stale ownership/private source is refused by real command/claim rights; repeated input stays idempotent and a new wake gets a full idle hour.+- [x] Watch them fail before implementation.+- [x] Implement the shared wake before saving messages; guard every recipient Buddy's part even when already awake, so concurrent sleep retries. Do not change delivery rights or authors.+- [x] Run changed units and focused real-store wake/rights cases; commit and push.++### Task 3: CLI reports idle and closes/resumes safely++**Files:** modify `cli/src/superTabs/machines.ts`, `host.ts`, `retention.ts`; test `machines.spec.ts`, `host.spec.ts`, `retention.spec.ts`.++**Interfaces:** a pool asking `buddySleepWanted` receives only running Buddy harnesses that `core.agents.activity` explicitly reports idle. Strip this field from repeated heartbeat bodies. Retention holds a bounded `wakeableBuddies` list for server-managed, non-stopping main Buddies; `retainedLeads` admits only that recorded list to existing core resume authority.++- [x] Commit failing tests for positive/unknown/working activity; one batch, no call without Buddies; old-server omission; repeated heartbeat strips proof; sleep closes once, preserves home, refuses busy/unknown/Team; wake and host restart reopen same session without replaying input; ordinary/unswitched Buddies unchanged.+- [x] Watch focused CLI tests fail.+- [x] Implement minimal report/retention/host changes; check live idle again immediately before sleep and preserve existing failure backoff. Managed awake Buddies use keepAlive without crew continuation text.+- [x] Run affected backend and CLI tests/typechecks. Record same-workload call counts and timing; commit and push, publish red/green evidence and mark ready.+++## Validation notes++- Server decision tests were committed at `4afea00e5`, real-store report/delivery tests at `82c0943fb`, and private-report tests at `07a1dd3e3`, before server implementation `8cf3ee094`. Wake tests `f60e62746` preceded `7cddf82f5`. CLI tests `8aa1cea7d` preceded `8aba589cc`.+- The 100-session report failed at 64 returned IDs (`89f70cee3`) before bounded batches (`c0bbe860a`); the duplicate-core-call regression (`134fdc518`) failed at 200 calls before the live-registry fix (`8fcb70b65`).+- Card-question regression `04e567e33` uses #3817's commands. It passed on the temporary combination and failed at the wake assertion with only `wakeBuddies` withheld. After #3387 landed at `50f524878`, main merged cleanly at `b34197e01`; all three #3824 real-store regressions pass on this branch, including the PM question waking the original proposal sender while the newer default stays asleep.+- Final validation after merging main: the three focused #3824 real-store regressions pass; 102 units in `buddySleep`, `machines`, `parts/touches` and `proposalCards` pass; 678 CLI checks in `machines`, `host`, `retention` and `buddyHome` pass. Backend and CLI typechecks are clean. No source edits were needed after the automatic merge.+- 344 affected backend units pass, plus the two extra report/switch-back regressions. The three affected CLI files pass (651 checks); the report file passes again after the scale fix (199 checks). Both typechecks pass. Real-store sleep and input-race cases pass; open-delivery reads use the existing agent/status index, 0 documents examined and at most 3 keys for the empty probe. The broader report integration file passes (32 checks).+- One broadened Buddy integration run found an accidental clock replacement in another fixture; corrected at `057840ae5`, and that case passes. Its failure is not product red evidence.+- The isolated native Buddy test is present, preserving the Buddy folder and exact engine conversation across sleep/wake. This machine is a Team OS account: product policy refuses Buddy starts here even with isolated homes. The run stopped before starting a Buddy, and does not count as native sleep/wake evidence. The test now explicitly requires an owner account; independent Mac/Linux native verification remains with the test steps.+- Synthetic same-workload report timing, macOS Node 22, 30 measured fresh passes after 5 warmups: 50 Buddies p95 0.378 ms before / 0.374 ms after; 500 Buddies p95 2.841 / 2.791 ms. Activity requests: 0 before, 1/8 after, each at most 64 IDs; no new per-session core calls, no activity request on a quiet pass or heartbeat. This excludes actual engine/IPC latency.+- Message numbering adds under 0.01 ms of median CPU at 500 agents in the synthetic workload. Pure candidate selection at 500 agents/homes is p95 9.71 ms; indexed database probes are candidate-only. These are local synthetic measurements, not production latency or native memory measurements.++### Native test follow-up++### Task 4: Connect server sleep authority to the native close guard++**Files:** `cli/src/superTabs/retention.ts`, `inCore/agents.ts`, `inCore.ts`, `cli/src/lib/closeAgentService.ts`, `cli/src/core/main.ts`; regression `cli/src/superTabs/inCore/buddySleep.spec.ts`.++**Interfaces:** retain only the server's sleeping, managed main Buddies as a bounded optional list. An internal, non-serializable close permit reads that authority again at each stop boundary. The Swarm uses an idle close for these Buddies, never the ordinary forced member close or confidential purge. Window closes retain their existing protection.++- [x] Commit a regression composing real retention, Swarm member authority and the close service; watch idle sleep fail at the Buddy guard. Cover wake/corruption revocation, active work, Team/thread/model-request/stopping/unmanaged exclusions and ordinary window protection.+- [x] Implement the narrow permit and wiring; preserve the existing idle/checkpoint/session identity fences.+- [x] Run affected checks/typecheck and record red/green evidence. Native resource-release and message-wake acceptance still requires a successful owner-account workflow receipt.++The corrected-owner native run `42225258676` at `4da69f02f` reached launch and positive idle proof, then failed to close the sleeping Buddy (0 passed, 1 failed, 0 skipped). Host unit fakes had hidden the real close service's Buddy protection; wake was not reached.++Regression `9a1dff300` failed in the real close guard (3 failed, 11 passed). With the internal idle permit, all 14 regression cases pass; the affected retention, Swarm agent and close-service files total 147 passing tests. Host and architecture files pass 459 checks. CLI TypeScript passes; the core gate passes 3,316 tests in 202 files with 100% statement/branch/function/line coverage. The new authority is an optional bounded list in the existing atomic retention file, discarded on wake, removal or old clients' rewrites; absent/corrupt/lapsed authority and Team daemons grant no sleep. No database, network or process-launch contract changes. No new idle timer, activity poll or per-session core request.++- The Mac tester independently passed six focused host checks and twenty server checks at `ddd9e37c0`; no behavior fault was found. Native resource-release evidence was missing on the Team OS account.+- Extended `cli/e2e/superTabSwarmBuddy.e2e.ts` to require the original engine PID to exit and its tmux pane to disappear, then send the person’s message through the owner request path and verify delivery in the resumed conversation. The engine conversation ID, folder and marker must survive. The fake backend models the server response; real server authorization/wake remains covered by the store regressions.+- The CLI end-to-end workflow now runs that scenario explicitly on its existing macOS owner-account runner and requires one pass with no skips, preserving the JSON receipt. Linux already discovers the scenario in its full end-to-end inventory. River will dispatch the workflow once at the final head.+- Scenario TypeScript check and workflow YAML validation pass locally. Native execution remains skipped on this Team account; no native pass is claimed until the workflow receipt arrives. No production source changed in this follow-up.++- Owner-account workflow run `42220472896` at `075ff078b`: the native Mac scenario failed before Buddy launch (0 passed, 1 failed, 0 skipped). The fake backend omitted its signed-in-owner response, so the real own-machine guard refused the unidentified owner. Added the fixture owner response; scenario TypeScript check passes. This failure supplies no sleep/wake or resource-release evidence. The remote head remains held for the original run; a corrected-head native receipt is still required.