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
Swarm Team account: keep the purge hold through the backend's save, and refuse the purge while its record can't be read (#2142)
0xken151b091c3e538d
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 5eb224f29..4bfaa2ecd 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -775,6 +775,45 @@ describe('a project\'s Product Manager on a teammate\'s Team machine', () => {cwd: '/team/lead', worktree: true, requirements } })).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_HELD' })})+ // Review of #2142: the hold outlives its removal through the store's saves and loads, and only its host's confirmed close,+ // sent once its session data is deleted, releases it (commands.ts agent.sessionClosed).+ it('stays held for its project after its removal until its host confirms the close, across saves and loads', async () => {+ const f = await fixture()+ const projectId = String((await run(f.tab, { type: 'project.create', name: 'App', visibility: 'public', brief: '' })).result.projectId)+ await run(f.tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', scope: 'swarm', engines: ['codex'], maxAgents: 4 }, person)+ const generation = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.machine.generation+ await store.observeMachine(team, f.tab, 'team-mac', capable(generation))+ await run(f.tab, { type: 'agent.remove', agentId: f.builder })+ const startId = String((await run(f.tab, { type: 'lead.start', projectId, machineId: 'team-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' })).result.startId)+ await hostRun(f.tab, { type: 'agent.startDispatch', startId })+ const harnessId = `team-pm-${randomUUID()}`+ const pm = String((await hostRun(f.tab, { type: 'agent.started', startId, harnessId, configuration: config })).result.agentId)+ await hostRun(f.tab, { type: 'agent.startSettled', startId, warning: null })+ // A Product Manager leaves with its project.+ await run(f.tab, { type: 'project.delete', projectId })+ const start = () => run(f.tab, { type: 'agent.start', request: { conversationId: f.teamGroup, machineId: 'team-mac', engine: 'codex', name: 'Builder',+ cwd: '/team/lead', worktree: true, requirements } }).then(() => 'started', (error: { code?: string }) => error.code)+ // Each command loads the Swarm from its stored parts: the hold is there each time.+ expect(await start()).toBe('TEAM_ACCOUNT_HELD')+ expect(await start()).toBe('TEAM_ACCOUNT_HELD')+ // No one else confirms it: not the Swarm's owner, nor anyone for another session.+ await expect(run(f.tab, { type: 'agent.sessionClosed', agentId: pm, harnessId })).rejects.toMatchObject({ code: 'NOT_FOUND' })+ await expect(run(f.tab, { type: 'agent.sessionClosed', agentId: pm, harnessId: 'another' }, team)).rejects.toMatchObject({ code: 'NOT_FOUND' })+ expect(await start()).toBe('TEAM_ACCOUNT_HELD')+ // Nor the Mac's owner from an ordinary sign-in, which shares the Team session's person but is not its host, with no+ // purge run (both security reviews of 0a181c00c), even once that sign-in resets the account row's Team mark.+ const ordinary = () => run(f.tab, { type: 'agent.sessionClosed', agentId: pm, harnessId }, person).then(() => 'closed', (error: { code?: string }) => error.code)+ expect({ forged: await ordinary(), after: await start() }).toEqual({ forged: 'TEAM_HOST_ONLY', after: 'TEAM_ACCOUNT_HELD' })+ const row = (await db.machine.findFirst({ where: { machineId: 'team-mac' } }))!+ const restore = () => db.machine.update({ where: { machineId: 'team-mac' }, data: { sessionKind: row.sessionKind, hostMachineId: row.hostMachineId } })+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { sessionKind: 'computer', hostMachineId: null } })+ onTestFinished(async () => { await restore() })+ expect({ forged: await ordinary(), after: await start() }).toEqual({ forged: 'TEAM_HOST_ONLY', after: 'TEAM_ACCOUNT_HELD' })+ await restore()+ await run(f.tab, { type: 'agent.sessionClosed', agentId: pm, harnessId }, team)+ expect(await start()).not.toBe('TEAM_ACCOUNT_HELD')+ })+it('is refused on the teammate\'s personal Mac even while the Swarm does not yet require Team accounts', async () => {const f = await fixture()const projectId = String((await run(f.tab, { type: 'project.create', name: 'App', visibility: 'private', brief: '' })).result.projectId)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 977e2e5ed..5fda4b551 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1324,6 +1324,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('TEAM_ACCOUNT_BUSY', 'This machine\'s Harness Team account runs other projects\' agents, so it cannot host this Product Manager now.', 409)}}+ // A confidential session removed from a Team account stays held until its host confirms its data deleted: added back,+ // even to the project it is held for, the hold would end with its private chats still there (review of #2142).+ if (!existing && state.closingSessions?.some(c => c.machineId === command.machineId && c.harnessId === command.harnessId && c.heldFor)) {+ fail('TEAM_ACCOUNT_HELD', 'This session held people\'s private chats and is being deleted from this machine\'s Harness Team account, so it cannot be added back.', 403)+ }if (!existing) reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)// Added back before its host closed it: the session stays open.if (!existing) dropClosing(state, c => c.machineId !== command.machineId || c.harnessId !== command.harnessId)diff --git a/backend/src/superTabs/leadStart.test.ts b/backend/src/superTabs/leadStart.test.tsindex e772a5a22..e3970ddca 100644--- a/backend/src/superTabs/leadStart.test.ts+++ b/backend/src/superTabs/leadStart.test.ts@@ -434,6 +434,23 @@ describe('a Team account hosting a Product Manager', () => {expect(web.start().result.startId).toBeTruthy()})+ it('keeps a removed confidential session from being added back while its data is being deleted (review of #2142)', () => {+ const f = swarm(), { web } = other(f)+ const startId = f.lead('mate-mac').result.startId as string+ const contribution = { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null }+ const pm = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, { contribution }).result.agentId as string+ f.run({ type: 'agent.startSettled', startId, warning: null }, owner, { contribution })+ f.run({ type: 'project.delete', projectId: f.app.projectId })+ // Even into the very project it is held for: adding it back dropped the hold, its private chats still on the account.+ f.state.closingSessions![0]!.heldFor = web.projectId+ const add = () => f.run({ type: 'agent.add', conversationId: web.conversationId, machineId: 'mate-team', harnessId: 'pm', name: 'PM',+ configuration: config, lead: false }, mate, { contribution })+ expect(refusal(add)?.code).toBe('TEAM_ACCOUNT_HELD')+ expect(f.state.closingSessions).toEqual([expect.objectContaining({ agentId: pm, harnessId: 'pm', heldFor: web.projectId })])+ f.run({ type: 'agent.sessionClosed', agentId: pm, harnessId: 'pm' }, mate)+ expect(refusal(add)).toBeNull()+ })+it('leaves the project owner\'s own machine as it is', () => {const f = swarm()f.lead('owner-mac')diff --git a/backend/src/superTabs/parts/shape.test.ts b/backend/src/superTabs/parts/shape.test.tsindex b8bf85d92..0de9387cd 100644--- a/backend/src/superTabs/parts/shape.test.ts+++ b/backend/src/superTabs/parts/shape.test.ts@@ -58,6 +58,13 @@ describe('splitting a Swarm into parts', () => {expect(machines[3]!.data!.cleanups).toEqual([{ removalId: 'r1', machineOwnerId: 'u1' }])})+ it('keeps a removed confidential session\'s hold on its Team account through a save and a load (review of #2142)', () => {+ // Dropped here, the account was free for another project's work on the next read, before its data was deleted.+ const held = { agentId: 'pm', machineId: 'team-mac', harnessId: 'h-pm', machineOwnerId: 'u2', heldFor: 'p1', since: 900, noticed: true as const }+ const state = { ...legacy(), closingSessions: [held, { agentId: 'gone', machineId: 'third', harnessId: 'h-gone', machineOwnerId: 'u1' }] }+ expect(reassemble(split(state, { tabId: 'tab1', version: 500, now: 1000 })).closingSessions).toEqual(state.closingSessions)+ })+it('keeps the progress out of the head and turns it into a watermark: every group carries its report sequence', () => {const parts = split(legacy(), { tabId: 'tab1', version: 500, now: 1000 })expect((parts.head.data!.projects![0] as Record<string, unknown>).progress).toBeUndefined()diff --git a/backend/src/superTabs/parts/shape.ts b/backend/src/superTabs/parts/shape.tsindex 61d1bd0b0..b64a17dde 100644--- a/backend/src/superTabs/parts/shape.ts+++ b/backend/src/superTabs/parts/shape.ts@@ -36,7 +36,8 @@ function machineParts(state: SuperTabState): Map<string, MachineData> {for (const pool of state.machines ?? []) of(pool.machineId).contribution = poolfor (const { machineId, harnessId, generation, renewed } of state.harnessReservations ?? []) of(machineId).reservations.push({ harnessId, generation, renewed })for (const { machineId, harnessId } of state.releasedHarnesses ?? []) of(machineId).released.push(harnessId)- for (const { machineId, agentId, harnessId, machineOwnerId } of state.closingSessions ?? []) of(machineId).closingSessions.push({ agentId, harnessId, machineOwnerId })+ // With its Team account hold (`heldFor`, `since`, `noticed`): dropped here, the account was free on the next read (review of #2142).+ for (const { machineId, ...closing } of state.closingSessions ?? []) of(machineId).closingSessions.push(closing)for (const { machineId, ...cleanup } of state.machineCleanups ?? []) of(machineId).cleanups.push(cleanup)return machines}@@ -119,7 +120,7 @@ export function reassemble(parts: SwarmParts, { share = false }: { share?: booleconst contributed: ContributedMachine[] = machines.flatMap(m => m.contribution ? [m.contribution] : [])const reservations = flat(m => m.reservations.map(r => ({ machineId: m.machineId, ...r })))const released = flat(m => m.released.map(harnessId => ({ machineId: m.machineId, harnessId })))- const closing = flat(m => m.closingSessions.map(c => ({ agentId: c.agentId, machineId: m.machineId, harnessId: c.harnessId, machineOwnerId: c.machineOwnerId })))+ const closing = flat(m => m.closingSessions.map(c => ({ ...c, machineId: m.machineId })))const cleanups: MachineCleanup[] = flat(m => m.cleanups.map(c => ({ machineId: m.machineId, ...c })))const list = <K extends typeof LISTS[number]>(key: K, items: NonNullable<SuperTabState[K]>) => {if (items.length || present.has(key)) state[key] = copy(items)diff --git a/backend/src/superTabs/parts/types.ts b/backend/src/superTabs/parts/types.tsindex 876e58a6f..574c19700 100644--- a/backend/src/superTabs/parts/types.ts+++ b/backend/src/superTabs/parts/types.ts@@ -45,7 +45,7 @@ export interface MachineData {reservations: Array<{ harnessId: string; generation: string; renewed: boolean }>/** Harnesses a host proved stopped, oldest first, at most RELEASED_CAP. */released: string[]- closingSessions: Array<{ agentId: string; harnessId: string; machineOwnerId: string }>+ closingSessions: Array<Omit<NonNullable<SuperTabState['closingSessions']>[number], 'machineId'>>cleanups: Array<{ removalId: string; machineOwnerId: string; requestedAt?: string }>}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex b920ccd4b..4e54abf4a 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1006,6 +1006,14 @@ export class SuperTabStore {}if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)if (team !== null && !hostMachineId) this.teamCommand(original, team, user, command)+ // A Team account's session is closed by its own team session: the Mac's owner is its machine owner too, and from an+ // ordinary sign-in confirmed it, ending its hold with its data still there. A held one is on a Team account by+ // definition, whatever the account row says now (review of #2142).+ if (command.type === 'agent.sessionClosed' && team === null) {+ const closing = original.closingSessions?.find(c => c.agentId === command.agentId && c.harnessId === command.harnessId && c.machineOwnerId === user.sub)+ if (closing) await this.notTeamMachine(user, () => tx.machine.findFirst({ where: { machineId: closing.machineId, userId: user.sub,+ autonomousEnv: user.autonomousEnv, ...machineAlive } }), !!closing.heldFor || teamByRecord(original, closing.machineId))+ }// Accepting a Swarm's invitation from outside its Workspace makes the person a guest of the Workspace first (design, Roles).if (command.type === 'invite.accept' && !hostMachineId && original.workspaceId) {const email = user.email.trim().toLowerCase()diff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.tsindex df72f3654..eea023b0b 100644--- a/cli/src/superTabs/inCore/agents.ts+++ b/cli/src/superTabs/inCore/agents.ts@@ -5,6 +5,7 @@* receipt names it (`closeMember`). The core offers these only while the Swarm is on (core/api.ts `swarmAgents`).*/import type { SwarmAgentDeps, SwarmAgents } from '../../core/api.js'+import { PURGE_RECORD_UNREADABLE } from './teamPurge.js'export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members, purgeEnded }: SwarmAgentDeps & {/** The Leads and members this machine's Super Tab host keeps (superTabs/retention.ts). */@@ -20,7 +21,8 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgentconst said = await purgeEnded(agentId).catch((error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }))if (typeof said.error !== 'string') return closedconst detail = typeof (said as Record<string, unknown>).detail === 'string' ? (said as Record<string, unknown>).detail as string : said.error- console.warn(`[super-tabs] could not delete the session data of ${agentId}: ${detail}`)+ // An unreadable record was said once, where it was kept; its host logs each refused retry (review of #2142).+ if (said.error !== PURGE_RECORD_UNREADABLE) console.warn(`[super-tabs] could not delete the session data of ${agentId}: ${detail}`)return { error: 'PURGE_FAILED', detail }}return {diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.tsindex ec140c58f..729d86d77 100644--- a/cli/src/superTabs/inCore/teamPurge.spec.ts+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts@@ -2,7 +2,8 @@ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeimport { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it, vi } from 'vitest'-import { createConfidentialPurge, purgeRecord, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'+import { createSwarmAgents } from './agents.js'+import { UNREADABLE_DETAIL, createConfidentialPurge, purgeRecord, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'// A confidential session the Swarm ended for good in a Harness Team account (#895): its data in the Team user's shared// engine homes goes, and the account stays held until a sweep finds nothing of it (security re-checks of #2089).@@ -248,9 +249,45 @@ describe('the purge of a confidential session the Swarm ended', () => {})})+// Security re-check 1 of 147777f54: with its record unreadable, a retry for a session already gone answered 'skipped', and its+// close released the account. While the record cannot be read, no purge is answered: the close fails, the hold stays.+describe('a purge while its record cannot be read', () => {+ it('is refused, the session gone or not, so the close fails and the account stays held until a person clears it', async () => {+ const home = dir(), file = join(home, 'super-tabs', 'team-purges.json')+ mkdirSync(join(home, 'super-tabs'), { recursive: true })+ writeFileSync(file, '{')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const record = purgeRecord(file)+ const purge = vi.fn(async () => ({ ok: true }))+ const refusal = { error: 'PURGE_RECORD_UNREADABLE', detail: UNREADABLE_DETAIL }+ for (const session of [() => null, (id: string) => ({ agentId: id, sessionId: 'pm-session', registeredAt: 5, engine: 'claude', cwd: CWD })]) {+ expect(await createConfidentialPurge({ confidential: () => true, home, session, purge, record })('pm')).toEqual(refusal)+ }+ expect(purge).not.toHaveBeenCalled()+ // Said once, where it was kept.+ expect(warn.mock.calls.map(([line]) => String(line))).toEqual([`[super-tabs] the record of purges still to finish could not be read; kept aside at ${file}.unreadable until its owner clears it`])+ warn.mockRestore()+ })++ it('is said once, with the path only, however often its close is refused and retried (review of #2142)', async () => {+ const home = dir(), file = join(home, 'super-tabs', 'team-purges.json')+ mkdirSync(join(home, 'super-tabs'), { recursive: true })+ writeFileSync(file, '{')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const purgeEnded = createConfidentialPurge({ confidential: () => true, home, session: () => null, purge: async () => ({ ok: true }), record: purgeRecord(file) })+ const agents = createSwarmAgents({ byAgent: () => null, stoppedIds: () => [], closeAgent: async () => ({ closed: true }), purgeEnded,+ members: { leads: () => new Set(), harnesses: () => new Set() } } as never)+ // Each refused close fails, so its host retries and the account stays held; the host logs what it was told.+ for (let n = 0; n < 2; n++) expect(await agents.closeMember('pm')).toEqual({ error: 'PURGE_FAILED', detail: UNREADABLE_DETAIL })+ expect(warn.mock.calls.map(([line]) => String(line))).toEqual([`[super-tabs] the record of purges still to finish could not be read; kept aside at ${file}.unreadable until its owner clears it`])+ warn.mockRestore()+ })+})+describe('the record of purges still to finish', () => {it('keeps them across restarts, and says when it cannot be read, so the account stays held (teamApps.ts)', async () => {const file = join(dir(), 'team-purges.json')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})const record = purgeRecord(file)record.put(target())record.put(target({ pastes: ['abc'] }))@@ -276,7 +313,45 @@ describe('the record of purges still to finish', () => {expect(purgeRecord(file).unknown()).toBe(true)rmSync(`${file}.unreadable.1`)expect(purgeRecord(file).unknown()).toBe(false)- writeFileSync(file, '{"pm": 3}')- expect([purgeRecord(file).get('pm'), purgeRecord(file).unknown()]).toEqual([undefined, false])+ warn.mockRestore()+ })++ it('sets a record of the wrong shape aside too, never dropping the purges it may name (security review 2 of #2142)', async () => {+ const { rmSync } = await import('node:fs')+ const file = join(dir(), 'team-purges.json')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const entry = JSON.stringify(target())+ for (const saved of ['3', 'null', '[]', '{"pm": 3}', `{"other": ${entry}}`, `{"pm": ${entry.replace('"engine":"claude"', '"engine":4')}}`,+ `{"pm": ${entry.replace('"cwd":', '"cwd":7,"was":')}}`, `{"pm": ${entry.replace('}', ',"pastes":[1]}')}}`]) {+ writeFileSync(file, saved)+ expect([purgeRecord(file).unknown(), readFileSync(`${file}.unreadable`, 'utf8')]).toEqual([true, saved])+ rmSync(`${file}.unreadable`)+ }+ // A record as this daemon writes it, older ones without codexHome included, is read as before.+ writeFileSync(file, `{"pm": ${entry.replace(',"codexHome":null', '')}}`)+ expect([purgeRecord(file).get('pm'), purgeRecord(file).unknown()]).toEqual([{ ...target(), codexHome: undefined }, false])+ warn.mockRestore()+ })++ it('names where it was kept on every start while it is there, since the refusal points to the log (security review 2 of #2142)', async () => {+ const { rmSync } = await import('node:fs')+ const file = join(dir(), 'super-tabs', 'team-purges.json')+ mkdirSync(join(file, '..'))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const said = (paths: string) => `[super-tabs] the record of purges still to finish could not be read; kept aside at ${paths} until its owner clears it`+ writeFileSync(file, '{')+ purgeRecord(file)+ purgeRecord(file)+ writeFileSync(file, '[')+ purgeRecord(file)+ for (let n = 2; n <= 10; n++) writeFileSync(`${file}.unreadable.${n}`, '{')+ purgeRecord(file)+ // Cleared, it says nothing.+ for (const n of ['', '.1', ...Array.from({ length: 9 }, (_, i) => `.${i + 2}`)]) rmSync(`${file}.unreadable${n}`)+ purgeRecord(file)+ const aside = `${file}.unreadable`+ expect(warn.mock.calls.map(([line]) => String(line))).toEqual([said(aside), said(aside), said(`${aside}, ${aside}.1`),+ said([aside, ...Array.from({ length: 10 }, (_, i) => `${aside}.${i + 1}`)].join(', '))])+ warn.mockRestore()})})diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.tsindex 203bf7a74..516c0d7d8 100644--- a/cli/src/superTabs/inCore/teamPurge.ts+++ b/cli/src/superTabs/inCore/teamPurge.ts@@ -37,9 +37,14 @@ export function purgeRecord(file: string) {const load = (): Map<string, PurgeTarget> => {if (!existsSync(file)) return new Map()try {- const saved = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>+ const saved: unknown = JSON.parse(readFileSync(file, 'utf8'))+ // One of another shape is set aside as well, never read as fewer purges than it names (security review 2 of #2142).+ if (!saved || typeof saved !== 'object' || Array.isArray(saved)) throw new Error('not a record')const held = new Map<string, PurgeTarget>()- for (const [id, entry] of Object.entries(saved)) if (entry && typeof entry === 'object' && (entry as PurgeTarget).agentId === id) held.set(id, entry as PurgeTarget)+ for (const [id, entry] of Object.entries(saved)) {+ if (!isTarget(id, entry)) throw new Error('not a purge')+ held.set(id, entry)+ }return held} catch {let free = aside@@ -48,7 +53,17 @@ export function purgeRecord(file: string) {return new Map()}}+ /** The records kept aside, in the order they were. No folder yet: no record was ever kept here, let alone kept aside. */+ const keptAsideFiles = (): string[] => existsSync(dirname(file)) ? readdirSync(dirname(file))+ .filter(name => name === basename(aside) || name.startsWith(`${basename(aside)}.`))+ .map(name => [Number(name.slice(basename(aside).length + 1)) || 0, join(dirname(file), name)] as const)+ .sort(([a], [b]) => a - b).map(([, path]) => path) : []+ const keptAside = (): boolean => existsSync(aside) || keptAsideFiles().length > 0const state = { held: load() }+ // Said once per start, where each is kept, path only: the refusal points here, and its owner clears it by hand (the PR's+ // risk note; security review 2 of #2142).+ const kept = keptAsideFiles()+ if (kept.length) console.warn(`[super-tabs] the record of purges still to finish could not be read; kept aside at ${kept.join(', ')} until its owner clears it`)const save = () => {mkdirSync(dirname(file), { recursive: true, mode: 0o700 })writeFileSync(`${file}.next`, JSON.stringify(Object.fromEntries(state.held)), { mode: 0o600 })@@ -57,13 +72,23 @@ export function purgeRecord(file: string) {return {pending: (): PurgeTarget[] => [...state.held.values()],get: (agentId: string): PurgeTarget | undefined => state.held.get(agentId),- unknown: (): boolean => existsSync(aside) || readdirSync(dirname(file)).some(name => name.startsWith(`${basename(aside)}.`)),+ unknown: keptAside,put(target: PurgeTarget): void { state.held.set(target.agentId, target); save() },drop(agentId: string): void { if (state.held.delete(agentId)) save() },}}export type PurgeRecord = ReturnType<typeof purgeRecord>+const nameOrNull = (value: unknown) => value === null || typeof value === 'string'+/** An entry as `put` writes it; `codexHome` absent in records from before Codex PMs had homes of their own. */+function isTarget(id: string, entry: unknown): entry is PurgeTarget {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false+ const target = entry as Record<string, unknown>+ return target.agentId === id && nameOrNull(target.sessionId) && nameOrNull(target.cwd) && typeof target.engine === 'string'+ && (target.codexHome === undefined || nameOrNull(target.codexHome))+ && (target.pastes === undefined || (Array.isArray(target.pastes) && target.pastes.every(paste => typeof paste === 'string')))+}+/** Claude Code's folder name for a project folder: every character but a letter or digit made a dash. */const claudeSlug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')const SESSION = /^[A-Za-z0-9_-]{1,160}$/@@ -199,6 +224,11 @@ export async function sweepForSession(home: string, target: PurgeTarget, pastes:return null}+/** A purge refused while the record is kept aside; the close that gets it does not say so again (inCore/agents.ts). */+export const PURGE_RECORD_UNREADABLE = 'PURGE_RECORD_UNREADABLE'+export const UNREADABLE_DETAIL = "This machine's record of purges still to finish could not be read and was kept aside, as the daemon's log says at "+ + "each start. The account stays held until its owner clears it as #2142's risk note says, by file names only."+/*** The purge of [agentId]'s data, once the Swarm ended it for good, when it was confidential: kept in [record] before the* first deletion and dropped once the sweep finds nothing. A retry finishes from the record, the session gone or not.@@ -212,6 +242,10 @@ export function createConfidentialPurge(deps: {record: PurgeRecord}): (agentId: string) => Promise<Record<string, unknown>> {return async agentId => {+ // With its record unreadable, which purges are still to finish is not known: none is answered, not even a 'skipped' for a+ // session already gone, so the close fails and the backend keeps the account held until a person clears the record. Its+ // path was logged once, when it was kept aside; this answer, logged on every retry, names neither it nor the agent.+ if (deps.record.unknown()) return { error: PURGE_RECORD_UNREADABLE, detail: UNREADABLE_DETAIL }const session = deps.session(agentId)let target = deps.record.get(agentId)if (!target) {