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
fix(super-tabs): unreadable shared purge files held by kind, with no path; the Buddy guard refuses a harness list that does not come (#2389)
harness-for-autonomous[bot]49be3bac3a9a
diff --git a/cli/src/superTabs/buddyPane.spec.ts b/cli/src/superTabs/buddyPane.spec.tsindex d6b9c4cd4..7d0da1ad3 100644--- a/cli/src/superTabs/buddyPane.spec.ts+++ b/cli/src/superTabs/buddyPane.spec.ts@@ -116,8 +116,35 @@ it('finds the pane\'s harness and asks whether it is a Buddy, the one way the guexpect(await asked(swarm(true), '%42', [900, 1])).toEqual({ answer: 'not in its pane', requests: ['agents_list', 'terminal_info'] })// Without the command's parents (the usage wording), its pane is not checked, as before.expect(await asked(swarm(true), '%42', 'none')).toEqual({ answer: 'buddy', requests: ['agents_list', 'super_tabs'] })+ // No list of this computer's harnesses, as an error reply: it cannot say, and nothing more is asked.+ const noList = daemon(swarm(true)), listed = noList.request.getMockImplementation()!+ noList.request.mockImplementation(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list' ? { error: 'SERVICE_FAILED' } : listed(type, payload))+ expect(await paneBuddy(noList, '%42', 'machine', ancestors)).toBe('unsure')+ expect(noList.request.mock.calls.map(([type]) => type)).toEqual(['agents_list'])// The Swarm is on but cannot say for this harness.for (const failed of [{ error: 'SERVICE_FAILED' }, { ok: true }, { ok: true, buddy: 'yes' }]) expect((await asked(() => failed)).answer).toBe('unsure')// A request that fails is the caller's to read: the guard refuses, the usage wording reads it as no Buddy.await expect(paneBuddy(daemon(() => { throw new Error('daemon gone') }), '%42', 'machine', ancestors)).rejects.toThrow('daemon gone')})++// Security review of #2384: nothing pinned that a failed read of this computer's harnesses in the pane check refuses; read as+// "no harness here", it would let a Buddy's pane go on. It rejects, and the CLI runs nothing (cli.ts unlessBuddy).+it('refuses when the pane check cannot read this computer\'s harnesses, and lets go of the daemon', async () => {+ const d = daemon(swarm(true))+ const request = d.request.getMockImplementation()!+ d.request.mockImplementation(async (type: string, payload: Record<string, unknown> = {}) => {+ if (type === 'agents_list') throw new Error('Harness did not answer agents_list in time. Try again.')+ return request(type, payload)+ })+ await expect(buddyRefusal(d.deps, 'darwin')).rejects.toThrow('Harness did not answer agents_list in time.')+ expect(d.request).not.toHaveBeenCalledWith('super_tabs', expect.objectContaining({ harnessId: expect.anything() }), expect.anything())+ expect(d.close).toHaveBeenCalledOnce()+ // An answer with no list is no answer either (review of #2389): an error reply was taken for "no harness here", and the+ // command ran. A list with no harness in the pane is nobody's pane.+ for (const reply of [{ error: 'SERVICE_FAILED' }, {}, { agents: 'none' }]) {+ d.request.mockImplementation(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list' ? reply : request(type, payload))+ expect(await buddyRefusal(d.deps, 'darwin'), JSON.stringify(reply)).toBe('Harness could not confirm whether this harness is a Buddy just now, so it did not run this. Try again in a moment.')+ }+ d.request.mockImplementation(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list' ? { agents: [] } : request(type, payload))+ expect(await buddyRefusal(d.deps, 'darwin')).toBeNull()+})diff --git a/cli/src/superTabs/buddyPane.ts b/cli/src/superTabs/buddyPane.tsindex 6bfaafdcf..7d4d41489 100644--- a/cli/src/superTabs/buddyPane.ts+++ b/cli/src/superTabs/buddyPane.ts@@ -40,12 +40,15 @@ export async function buddiesHere(daemon: DaemonLike): Promise<boolean | null> {* Whether the harness running in [pane] is a Buddy, by this computer's launch record (service.ts `buddyCheck`, what turns its* guard on): the one way this guard and the CLI's usage wording (command.ts `buddyHere`) ask it (review of #2379). With the* command's [ancestors], a harness whose own pane, as the daemon reads it, is not among them is never asked about. A request- * that fails is thrown, for each caller to read as it does: this guard refuses, the wording takes it for no Buddy.+ * that fails is thrown, and a list of harnesses that does not come is `unsure`, for each caller to read as it does: this+ * guard refuses, the wording takes it for no Buddy.*/export async function paneBuddy(daemon: DaemonLike, pane: string, machineId: string, ancestors?: number[]): Promise<'buddy' | 'not a buddy' | 'no harness' | 'not in its pane' | 'unsure'> {const listed = await daemon.request('agents_list')- const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], pane, machineId)+ // An answer with no list is no answer: an error reply read as "no harness here" let a Buddy's pane go on (review of #2389).+ if (!Array.isArray(listed.agents)) return 'unsure'+ const caller = callerOf(listed.agents as Frame[], pane, machineId)if (!caller) return 'no harness'if (!await inDaemonPane(daemon, caller.agentId, ancestors)) return 'not in its pane'const answer = await daemon.request('super_tabs', { action: 'buddyCheck', harnessId: caller.agentId }, 10_000)diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 74910ba2a..1aa5192b3 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -3092,6 +3092,66 @@ describe('closing the sessions the backend ends', () => {} finally { chmodSync(join(claude, 'projects'), 0o755); rmSync(home, { recursive: true, force: true }) }})+ // Re-check 2 of 68ec6f0: a Buddy's transcript folder that could not be listed, or one of its own transcripts that could not+ // be read, was skipped, and with no sweep after it the cleanup marked itself done and left the person's transcript for good.+ it.each(['folder', 'transcript'] as const)('fails an ended Buddy\'s cleanup by a fixed code when its transcript %s cannot be read, and finishes it later', async unread => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')+ const folder = join(worktrees, 'openharness', 'buddy-session'), transcripts = join(claude, 'projects', folder.replace(/[^A-Za-z0-9]/g, '-'))+ const locked = unread === 'folder' ? transcripts : join(transcripts, 'own.jsonl')+ try {+ mkdirSync(folder, { recursive: true })+ mkdirSync(transcripts, { recursive: true })+ writeFileSync(join(transcripts, 'own.jsonl'), JSON.stringify({ cwd: folder }))+ chmodSync(locked, 0o000)+ const t = lifeFixture([ended()], { claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })+ t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: null, engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)+ await t.poll()+ await vi.waitFor(() => expect(t.log).toHaveBeenCalledWith('Could not remove an ended Buddy session\'s Claude Code traces yet: agent agent, TRANSCRIPTS_UNREAD'))+ const said = t.log.mock.calls.flat().join('\n')+ expect(said).not.toContain(home)+ expect(said).not.toContain('Kept another folder\'s transcripts')+ // Not done: its end is not acknowledged, and the journal still says what to scrub.+ expect(t.commands).toEqual([])+ expect(Object.keys(t.saved().scrubs ?? {})).toEqual(['agent'])+ chmodSync(locked, unread === 'folder' ? 0o755 : 0o644)+ await t.poll(60_000)+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(existsSync(transcripts)).toBe(false)+ expect(t.saved().scrubs).toBeUndefined()+ } finally { if (existsSync(locked)) chmodSync(locked, 0o755); rmSync(home, { recursive: true, force: true }) }+ })++ // Re-check of 8c0b019: a todos or config backups folder that could not be listed was read as empty, and with no sweep after+ // it the cleanup marked itself done and left the Buddy's todo file and its folder in the backups for good.+ it.each([['todos', 'TODOS_UNREAD'], ['backups', 'CONFIG_BACKUPS_UNREAD']] as const)(+ 'fails an ended Buddy\'s cleanup by a fixed code when its %s folder cannot be listed, and finishes it later', async (sub, code) => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')+ const folder = join(worktrees, 'openharness', 'buddy-session'), locked = join(claude, sub)+ const todo = join(claude, 'todos', 'buddy-sid-agent-buddy-sid.json'), backup = join(claude, 'backups', '.claude.json.backup.1')+ try {+ mkdirSync(folder, { recursive: true })+ mkdirSync(join(claude, 'todos'), { recursive: true })+ mkdirSync(join(claude, 'backups'), { recursive: true })+ writeFileSync(todo, '[]')+ writeFileSync(backup, JSON.stringify({ projects: { [folder]: {}, '/elsewhere': {} } }))+ chmodSync(locked, 0o000)+ const t = lifeFixture([ended()], { claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })+ t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: 'buddy-sid', engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)+ await t.poll()+ await vi.waitFor(() => expect(t.log).toHaveBeenCalledWith(`Could not remove an ended Buddy session's Claude Code traces yet: agent agent, ${code}`))+ expect(t.log.mock.calls.flat().join('\n')).not.toContain(home)+ // Not done: its end is not acknowledged, and the journal still says what to scrub.+ expect(t.commands).toEqual([])+ expect(Object.keys(t.saved().scrubs ?? {})).toEqual(['agent'])+ chmodSync(locked, 0o755)+ await t.poll(60_000)+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(existsSync(todo)).toBe(false)+ expect(JSON.parse(readFileSync(backup, 'utf8')).projects).toEqual({ '/elsewhere': {} })+ expect(t.saved().scrubs).toBeUndefined()+ } finally { if (existsSync(locked)) chmodSync(locked, 0o755); rmSync(home, { recursive: true, force: true }) }+ })+// A machine with no worktrees folder made no Buddy worktree, and an id that is not one is logged as such, never as itself.it('drops every saved scrub when this machine has no worktrees folder, and never logs an id that is not one', async () => {const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), worktrees = join(home, 'harnesses', 'worktrees')diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex e3fa982c4..7c5acd47f 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -18,7 +18,7 @@ import { noticeReason, WithheldDeliveries } from './withheld.js'import { attentionOf } from './attention.js'import { prepareContribution, prepareTeamContribution } from './contribution.js'import { homedir, hostname } from 'node:os'-import { recordsOtherFolder, scrubClaudeSession, type PurgeTarget } from './inCore/teamPurge.js'+import { recordsOtherFolder, scrubClaudeSession, type PurgeTarget, type ScrubTold } from './inCore/teamPurge.js'import { replacementObservations } from './replacements.js'import { TerminalHost } from './terminal.js'import { LimitResume } from './limitResume.js'@@ -180,6 +180,13 @@ function buddyWorktree(cwd: string, worktrees: string): boolean {}/** A Claude Code session id: a saved one of another shape is dropped (security review 2 of #2375). */const CLAUDE_SESSION = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+/** The fixed code an ended Buddy's cleanup fails with for each kind of folder or file it could not read: never its path. */+const UNREAD_CODES: Record<Exclude<ScrubTold, 'shared'>, string> = {+ unread: 'TRANSCRIPTS_UNREAD',+ unreadTodos: 'TODOS_UNREAD',+ unreadBackups: 'CONFIG_BACKUPS_UNREAD',+}+/** Whether [sessionId] is [folder]'s session: no prompt history line names it with another project, and no transcript of* it records another folder. A person's own session id beside a Buddy's worktree took their history, a paste, file history* and debug log (security review 2 of #2375). A file that cannot be read is no answer: the scrub fails and is tried again. */@@ -1084,9 +1091,15 @@ export class SuperTabHost {const scrub = await this.ownScrub(agent.id, agent.harnessId, state.scrub).catch(() => { throw new Error(`Could not remove an ended Buddy session's Claude Code traces yet: agent ${agent.id}, SCRUB_FAILED`) })if (scrub) {- await scrubClaudeSession(this.claudeHome, scrub, [], undefined,- () => this.log(`Kept another folder's transcripts that share a Buddy session's transcript folder: agent ${agent.id}`))- .catch(() => { throw new Error(`Could not remove an ended Buddy session's Claude Code traces yet: agent ${agent.id}, SCRUB_FAILED`) })+ const unread = new Set<string>()+ await scrubClaudeSession(this.claudeHome, scrub, [], undefined, what => {+ if (what === 'shared') this.log(`Kept another folder's transcripts that share a Buddy session's transcript folder: agent ${agent.id}`)+ else unread.add(UNREAD_CODES[what])+ }).catch(() => { throw new Error(`Could not remove an ended Buddy session's Claude Code traces yet: agent ${agent.id}, SCRUB_FAILED`) })+ // No sweep follows a Buddy's cleanup: a transcript folder or transcript it could not read would be left behind for good+ // once this marked itself done (re-check 2 of 68ec6f0), and so would its todo file or its folder in a config backup+ // (re-check of 8c0b019). It fails, by fixed codes, and is tried again.+ if (unread.size) throw new Error(`Could not remove an ended Buddy session's Claude Code traces yet: agent ${agent.id}, ${[...unread].join(', ')}`)}state.scrubbed = trueif (this.journal.scrubs?.[agent.id]) {diff --git a/cli/src/superTabs/inCore/agents.spec.ts b/cli/src/superTabs/inCore/agents.spec.tsindex 06a27da0f..1735b1d09 100644--- a/cli/src/superTabs/inCore/agents.spec.ts+++ b/cli/src/superTabs/inCore/agents.spec.ts@@ -99,12 +99,21 @@ describe('the Swarm\'s agents, as the core lets it close and reopen them', () =>harnesses.mockReturnValue(new Set())expect(await swarm.closeMember('live')).toEqual({ error: 'NOT_A_MEMBER' })expect(purgeEnded).toHaveBeenCalledTimes(2)- purgeEnded.mockRejectedValueOnce(new Error('EIO'))- expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'EIO' })+ // A thrown failure is said by its kind alone, in the log and the answer: its message may name a path (security review 2+ // of #2389).+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ purgeEnded.mockRejectedValueOnce(Object.assign(new Error("EACCES: permission denied, scandir '/Users/team/.claude/projects/-secret-folder'"), { code: 'EACCES' }))+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'EACCES' })+ purgeEnded.mockRejectedValueOnce(new TypeError('/Users/team/.claude/projects/-secret-folder is not a thing'))+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'TypeError' })+ purgeEnded.mockRejectedValueOnce('/Users/team/.claude/projects/-secret-folder: disk full')+ expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'unknown failure' })+ expect(warned.mock.calls.map(([line]) => String(line))).toEqual(['EACCES', 'TypeError', 'unknown failure']+ .map(kind => `[super-tabs] could not delete the session data of absent: ${kind}`))+ } finally { warned.mockRestore() }purgeEnded.mockResolvedValueOnce({ error: 'SCRUB_INCOMPLETE', detail: 'Something still names the session: /x' } as never)expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'Something still names the session: /x' })- purgeEnded.mockRejectedValueOnce('disk full')- expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'disk full' })purgeEnded.mockResolvedValueOnce({ error: 'NOT_FOUND' } as never)expect(await swarm.closeMember('absent')).toEqual({ error: 'PURGE_FAILED', detail: 'NOT_FOUND' })// A close that failed deletes nothing: the session is still there.diff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.tsindex eea023b0b..90e05ff56 100644--- a/cli/src/superTabs/inCore/agents.ts+++ b/cli/src/superTabs/inCore/agents.ts@@ -18,7 +18,10 @@ export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent* (security re-check 1 and 2 of #2089). The close's own answer when there is nothing to delete or it went. */const ended = async <T>(agentId: string, closed: T): Promise<T | { error: 'PURGE_FAILED'; detail: string }> => {if (!purgeEnded) return closed- const said = await purgeEnded(agentId).catch((error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }))+ // A thrown failure by its kind alone, its code or its class: its message may name a path, which went into the daemon's+ // log and the close's answer (security review 2 of #2389).+ const said = await purgeEnded(agentId).catch((error: unknown) => ({ error: error instanceof Error+ ? typeof (error as NodeJS.ErrnoException).code === 'string' ? (error as NodeJS.ErrnoException).code! : error.name : 'unknown failure' }))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// An unreadable record was said once, where it was kept; its host logs each refused retry (review of #2142).diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.tsindex ef236c7b5..cbcdbb1c9 100644--- a/cli/src/superTabs/inCore/teamPurge.spec.ts+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts@@ -3,7 +3,25 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it, vi } from 'vitest'import { createSwarmAgents } from './agents.js'-import { SHARED_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, purgeRecord, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'+import { OWN_LEFT, SHARED_LEFT, SWEEP_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, purgeRecord, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'++/** A folder that goes between the sweep's listing of its parent and its own read: removed just before that read. */+const vanish = vi.hoisted(() => ({ path: '' }))+/** A folder whose next listing fails with [code], as the system says it, path and all. */+const fail = vi.hoisted(() => ({ path: '', code: '' }))+vi.mock('node:fs/promises', async importOriginal => {+ const fs = await importOriginal<typeof import('node:fs/promises')>()+ const readdir = (async (path: Parameters<typeof fs.readdir>[0], ...rest: unknown[]) => {+ if (vanish.path && path === vanish.path) { vanish.path = ''; await fs.rm(path, { recursive: true, force: true }) }+ if (fail.path && path === fail.path) {+ const code = fail.code+ fail.path = ''+ throw Object.assign(new Error(`${code}: could not list, scandir '${String(path)}'`), { code })+ }+ return (fs.readdir as (...args: unknown[]) => unknown)(path, ...rest)+ }) as typeof fs.readdir+ return { ...fs, readdir }+})// 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).@@ -77,6 +95,75 @@ describe('scrubbing a Claude Code session from the Team user\'s shared home', ()expect(shares).toHaveBeenCalledTimes(1)})+ // Security review 1 of 58b035e: a transcript folder that could not be listed counted as empty and went whole. A permissions+ // error carried its path into the daemon's log, and a passing one (too many open files) deleted other folders' transcripts+ // unread. Only a folder that is not there is empty.+ it('keeps a transcript folder it cannot list, whatever the error, and the sweep holds the account by its kind', async () => {+ const { home, shared, folder } = sharedFolder()+ const theirs = join(shared, 'theirs.jsonl')+ writeFileSync(theirs, JSON.stringify({ cwd: '/Users/me/harnesses/worktrees-old/notes' }))+ const ours = target({ sessionId: null, cwd: folder })+ for (const code of ['EMFILE', 'EACCES', 'EIO']) {+ Object.assign(fail, { path: shared, code })+ await scrubClaudeSession(home, ours, [])+ expect(existsSync(theirs), code).toBe(true)+ Object.assign(fail, { path: shared, code })+ const held = await sweepForSession(home, ours, [])+ expect(held, code).toBe(left('unreadFolder'))+ expect(held).not.toContain(home)+ }+ // The system's own refusal, as a Team account meets it.+ chmodSync(shared, 0o000)+ try {+ await scrubClaudeSession(home, ours, [])+ expect(await sweepForSession(home, ours, [])).toBe(left('unreadFolder'))+ } finally { chmodSync(shared, 0o700) }+ expect(existsSync(theirs)).toBe(true)+ // One gone since its parent was listed is nothing of the session's.+ vanish.path = shared+ expect(await sweepForSession(home, ours, [])).toBeNull()+ })++ // Re-check of 68ec6f0 (Lark): the sweep's walk read a folder it could not list as empty, so whatever of the session was in+ // it went unseen and the purge finished. Only a folder that is not there is empty; any other holds the account by its kind.+ it('holds the account on any folder of the engines\' homes the sweep cannot list, by its kind, and passes one that went', async () => {+ const { home, claude } = teamHome()+ const ours = target()+ rmSync(join(claude, 'projects', SLUG), { recursive: true })+ // Everything else of the session gone, its file history left in a folder the sweep cannot list.+ for (const path of [join(claude, 'history.jsonl'), join(home, '.claude.json'), ...['backups', 'session-env', 'todos', 'debug', 'paste-cache'].map(name => join(claude, name))]) {+ rmSync(path, { recursive: true, force: true })+ }+ const history = join(claude, 'file-history')+ expect(existsSync(join(history, 'pm-session'))).toBe(true)+ chmodSync(history, 0o000)+ const held = await sweepForSession(home, ours, []).finally(() => chmodSync(history, 0o700))+ expect(held).toBe(SWEEP_LEFT.unlistedFolder)+ expect(held).not.toContain(home)+ // A passing error holds it too, on the projects folder or the home itself: what the folder holds is not known.+ rmSync(history, { recursive: true })+ for (const path of [join(claude, 'projects'), claude]) {+ Object.assign(fail, { path, code: 'EMFILE' })+ expect(await sweepForSession(home, ours, []), path).toBe(SWEEP_LEFT.unlistedFolder)+ }+ // A folder gone since its parent was listed holds nothing, and neither does an engine's home that is not there.+ mkdirSync(join(claude, 'gone'))+ vanish.path = join(claude, 'gone')+ rmSync(join(home, '.codex'), { recursive: true })+ expect(await sweepForSession(home, ours, [])).toBeNull()+ })++ // Security review 1 of 58b035e: an account held by what could not be read named no next step. Each says what to fix, with+ // no path, and that the purge then finishes on its own next try (host.ts endSession retries it).+ it('tells the owner what to fix for each unreadable kind, and that the purge then finishes', () => {+ for (const said of [...(['unreadFolder', 'unreadMemory', 'unreadTranscript'] as const).map(left), OWN_LEFT.unreadTranscript, SWEEP_LEFT.unlistedFolder, SWEEP_LEFT.unreadFile]) {+ expect(said).toMatch(/could not be read: its owner (finds it \([^)]+\) and )?makes it readable for the Team account, and the purge finishes on its next try$/)+ }+ // With no path to name, what holds the account says where to look (re-check of 8c0b019).+ expect(SWEEP_LEFT.unlistedFolder).toContain('search the Team account\'s Claude Code and Codex homes for folders it can\'t read')+ expect(SWEEP_LEFT.unreadFile).toContain('search the Team account\'s Claude Code and Codex homes for files it can\'t read')+ })+// Security review 2 of #2385, P3: a transcript that records no working folder is no proof it is the session's; it stays,// and the sweep refuses it.it('keeps a transcript of a shared transcript folder that records no working folder, or both', async () => {@@ -135,6 +222,33 @@ describe('scrubbing a Claude Code session from the Team user\'s shared home', ()expect(existsSync(join(claude, 'todos', 'pm-session2-agent-pm-session2.json'))).toBe(true)})+ // Re-check of 8c0b019: a todos or config backups folder that could not be listed was read as empty, and a Buddy's cleanup,+ // which no sweep follows, finished with its todo file and its folder in the backups left. Only one that is not there is+ // empty; any other is told by its kind alone, whatever the error, and what it holds stays.+ it('tells its caller when its todos or config backups folder cannot be listed, by kind, and keeps what is in it', async () => {+ for (const [sub, kind] of [['todos', 'unreadTodos'], ['backups', 'unreadBackups']] as const) {+ for (const code of ['EMFILE', 'EACCES']) {+ const { home, claude } = teamHome(), told = vi.fn()+ Object.assign(fail, { path: join(claude, sub), code })+ await scrubClaudeSession(home, target(), [], undefined, told)+ expect(told.mock.calls, `${sub} ${code}`).toEqual([[kind]])+ expect(existsSync(join(claude, 'todos', 'pm-session-agent-pm-session.json'))).toBe(sub === 'todos')+ expect(readFileSync(join(claude, 'backups', '.claude.json.backup.1793236000000'), 'utf8').includes(`"${CWD}"`)).toBe(sub === 'backups')+ // Listed again, it finishes, and says nothing.+ told.mockClear()+ await scrubClaudeSession(home, target(), [], undefined, told)+ expect(told).not.toHaveBeenCalled()+ expect(await sweepForSession(home, target(), [])).toBeNull()+ rmSync(home, { recursive: true, force: true })+ }+ }+ // One that is not there is empty.+ const { home, claude } = teamHome(), told = vi.fn()+ for (const sub of ['todos', 'backups']) rmSync(join(claude, sub), { recursive: true })+ await scrubClaudeSession(home, target(), [], undefined, told)+ expect(told).not.toHaveBeenCalled()+ })+it('removes every file and entry its session or folder names, and keeps every other session\'s', async () => {const { home, claude } = teamHome()expect(await scrubClaudeSession(home, target())).toEqual(['abc123'])@@ -180,22 +294,37 @@ describe('scrubbing a Claude Code session from the Team user\'s shared home', ()})describe('the sweep for what a scrub left', () => {- it('finds the session or folder where Claude Code and Codex write its own data, and nowhere else', async () => {+ // Re-check 2 of 68ec6f0: what the sweep found was named by its path, the Team home's and all. It names its kind.+ it('finds the session or folder where Claude Code and Codex write its own data, and nowhere else, by its kind', async () => {const { home, claude } = teamHome()await scrubClaudeSession(home, target())appendFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ display: 'late', project: CWD, sessionId: 'pm-session' })}\n`)- expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'history.jsonl'))+ expect(await sweepForSession(home, target(), [])).toBe(SWEEP_LEFT.claudeHistory)await scrubClaudeSession(home, target())writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'written again')- expect(await sweepForSession(home, target(), ['abc123'])).toBe(join(claude, 'paste-cache', 'abc123.txt'))+ expect(await sweepForSession(home, target(), ['abc123'])).toBe(SWEEP_LEFT.paste)writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), '')await scrubClaudeSession(home, target(), ['abc123'])mkdirSync(join(claude, 'new-feature', 'pm-session'), { recursive: true })- expect(await sweepForSession(home, target(), ['abc123'])).toBe(join(claude, 'new-feature', 'pm-session'))+ expect(await sweepForSession(home, target(), ['abc123'])).toBe(SWEEP_LEFT.claudeNamed)mkdirSync(join(claude, 'later', SLUG), { recursive: true })- expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'later', SLUG))+ expect(await sweepForSession(home, target(), [])).toBe(SWEEP_LEFT.claudeNamed)writeFileSync(join(home, '.codex', 'history.jsonl'), '{"session_id":"pm-session"}')- expect(await sweepForSession(home, target({ cwd: null }), [])).toBe(join(home, '.codex', 'history.jsonl'))+ expect(await sweepForSession(home, target({ cwd: null }), [])).toBe(SWEEP_LEFT.codexHistory)+ rmSync(join(home, '.codex', 'history.jsonl'))+ for (const left of ['new-feature', 'later']) rmSync(join(claude, left), { recursive: true })+ mkdirSync(join(home, '.codex', 'sessions', 'pm-session'), { recursive: true })+ expect(await sweepForSession(home, target({ cwd: null }), [])).toBe(SWEEP_LEFT.codexNamed)+ rmSync(join(home, '.codex', 'sessions'), { recursive: true })+ // A history or config that cannot be read holds it, as a folder that cannot be listed does.+ for (const file of [join(claude, 'history.jsonl'), join(home, '.codex', 'history.jsonl'), join(home, '.claude.json')]) {+ writeFileSync(file, '')+ chmodSync(file, 0o000)+ const held = await sweepForSession(home, target(), []).finally(() => chmodSync(file, 0o600))+ expect(held, file).toBe(SWEEP_LEFT.unreadFile)+ }+ Object.assign(fail, { path: join(claude, 'backups'), code: 'EMFILE' })+ expect(await sweepForSession(home, target(), [])).toBe(SWEEP_LEFT.unlistedFolder)expect(await sweepForSession(dir(), target(), [])).toBeNull()})@@ -217,6 +346,15 @@ describe('the sweep for what a scrub left', () => {expect(await sweepForSession(home, ours, [])).toBe(left('memory'))rmSync(join(memory, 'deep'), { recursive: true })expect(await sweepForSession(home, ours, [])).toBeNull()+ // A transcript folder with no other folder's transcript in it is not said to be shared (re-check 2 of 68ec6f0).+ rmSync(join(shared, 'theirs.jsonl'))+ writeFileSync(join(shared, 'mine.jsonl'), transcript(folder))+ expect(await sweepForSession(home, ours, [])).toBe(OWN_LEFT.transcript)+ chmodSync(join(shared, 'mine.jsonl'), 0o000)+ expect(await sweepForSession(home, ours, []).finally(() => chmodSync(join(shared, 'mine.jsonl'), 0o600))).toBe(OWN_LEFT.unreadTranscript)+ expect(OWN_LEFT.transcript + OWN_LEFT.unreadTranscript + left('unreadFolder') + left('folder')).not.toContain('shares')+ rmSync(join(shared, 'mine.jsonl'))+ writeFileSync(join(shared, 'theirs.jsonl'), transcript(OTHER, call(OTHER, 'Write', { file_path: join(memory, 'theirs.md') })))// A transcript of its folder, one of both folders, or one that records none; anything else in the folder.for (const [name, text] of [['a.jsonl', transcript(folder)], ['b.jsonl', `${transcript(OTHER)}\n${JSON.stringify({ cwd: `${folder}/src` })}`], ['c.jsonl', transcript(null)]]) {writeFileSync(join(shared, name), text)@@ -228,6 +366,17 @@ describe('the sweep for what a scrub left', () => {expect(await sweepForSession(home, ours, []), name).toBe(left('other'))rmSync(join(shared, name), { recursive: true })}+ // A memory folder gone between the listing and its read is no memory folder.+ vanish.path = memory+ expect(await sweepForSession(home, ours, [])).toBeNull()+ expect(existsSync(memory)).toBe(false)+ mkdirSync(memory)+ // A transcript that cannot be read fails it by its kind: the read's own error named its path (review of #2389).+ chmodSync(join(shared, 'theirs.jsonl'), 0o000)+ const unread = await sweepForSession(home, ours, []).finally(() => chmodSync(join(shared, 'theirs.jsonl'), 0o600))+ // Its only other transcript unread, nothing says another folder shares it.+ expect(unread).toBe(OWN_LEFT.unreadTranscript)+ expect(unread).not.toContain(home)// A memory folder linked elsewhere is never followed, and fails it.rmSync(memory, { recursive: true })mkdirSync(join(home, 'elsewhere'))@@ -235,22 +384,21 @@ describe('the sweep for what a scrub left', () => {expect(await sweepForSession(home, ours, [])).toBe(left('other'))const { unlinkSync } = await import('node:fs')unlinkSync(memory)- // Its session's name inside the folder still fails it, by its path; so does the folder once no other is left, a file of+ // Its session's name inside the folder still fails it, by its kind; so does the folder once no other is left, a file of// its name, and one that cannot be read.writeFileSync(join(shared, 'theirs', 'pm-session.txt'), '')- expect(await sweepForSession(home, ours, [])).toBe(join(shared, 'theirs', 'pm-session.txt'))+ expect(await sweepForSession(home, ours, [])).toBe(SWEEP_LEFT.claudeNamed)rmSync(join(shared, 'theirs'), { recursive: true })expect(await sweepForSession(home, ours, [])).toBeNull()rmSync(join(shared, 'theirs.jsonl'))expect(await sweepForSession(home, ours, [])).toBe(left('folder'))rmSync(shared, { recursive: true })writeFileSync(shared, '')- expect(await sweepForSession(home, ours, [])).toBe(shared)+ expect(await sweepForSession(home, ours, [])).toBe(SWEEP_LEFT.claudeNamed)rmSync(shared)expect(await sweepForSession(home, ours, [])).toBeNull()mkdirSync(shared, { mode: 0o000 })- expect(await sweepForSession(home, ours, [])).toBe(left('folder'))- chmodSync(shared, 0o700)+ expect(await sweepForSession(home, ours, []).finally(() => chmodSync(shared, 0o700))).toBe(left('unreadFolder'))})})@@ -267,8 +415,8 @@ describe('a scrub and sweep with part of a session unknown', () => {await scrubClaudeSession(home, target())expect(readFileSync(join(home, '.claude.json'), 'utf8')).toBe('null')writeFileSync(join(claude, 'backups', '.claude.json.backup.1'), 'a copy that is no JSON, naming "' + CWD + '"')- expect(await sweepForSession(home, target(), [])).toBe(join(claude, 'backups', '.claude.json.backup.1'))- expect(await sweepForSession(home, target({ sessionId: '../x' }), [])).toBe(join(claude, 'backups', '.claude.json.backup.1'))+ expect(await sweepForSession(home, target(), [])).toBe(SWEEP_LEFT.config)+ expect(await sweepForSession(home, target({ sessionId: '../x' }), [])).toBe(SWEEP_LEFT.config)// With no folder, nothing of the config is its; with neither, nothing is.expect(await sweepForSession(home, target({ cwd: null }), ['../bad'])).toBeNull()expect(await sweepForSession(home, target({ cwd: null, sessionId: null }), [])).toBeNull()@@ -336,7 +484,7 @@ describe('the purge of a confidential session the Swarm ended', () => {const ended = createConfidentialPurge({ confidential: id => id === 'pm', home, session: s.session, purge: s.purge, record: s.record })// Something the scrub does not know of still names the session: the purge fails and the session stays in its record.mkdirSync(join(claude, 'new-feature', 'pm-session'), { recursive: true })- expect(await ended('pm')).toEqual({ error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${join(claude, 'new-feature', 'pm-session')}` })+ expect(await ended('pm')).toEqual({ error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${SWEEP_LEFT.claudeNamed}` })expect(s.calls.map(c => c.mode)).toEqual(['inspect', 'delete'])expect(s.record.pending()).toEqual([{ agentId: 'pm', sessionId: 'pm-session', cwd: CWD, engine: 'claude', codexHome: null, pastes: ['abc123'] }])// The retry, its stopped entry gone: it scrubs and sweeps again from the record (a history line written since included).@@ -368,7 +516,21 @@ describe('the purge of a confidential session the Swarm ended', () => {expect(['pm-session.jsonl', 'theirs.jsonl', 'memory/MEMORY.md', 'memory/theirs.md'].map(name => existsSync(join(shared, name)))).toEqual([false, true, true, true])const restarted = createConfidentialPurge({ confidential: () => true, home, session: s.session, purge: s.purge, record: purgeRecord(join(home, 'super-tabs', 'team-purges.json')) })expect(await restarted('pm')).toMatchObject({ error: 'SCRUB_INCOMPLETE' })+ // A memory folder that cannot be read holds it too, named by its kind: the read's own error carried the folder's path into+ // the daemon's log (security review of #2385).+ chmodSync(memory, 0o000)+ const unread = await restarted('pm').finally(() => chmodSync(memory, 0o700))+ expect(unread).toEqual({ error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${left('unreadMemory')}` })+ expect(JSON.stringify(unread)).not.toContain(home)+ expect(purgeRecord(join(home, 'super-tabs', 'team-purges.json')).pending()).toHaveLength(1)rmSync(memory, { recursive: true })+ // So does another folder's transcript that cannot be read: kept, never deleted unread, and named by its kind alone.+ chmodSync(join(shared, 'theirs.jsonl'), 0o000)+ const unreadTranscript = await restarted('pm').finally(() => chmodSync(join(shared, 'theirs.jsonl'), 0o600))+ expect(unreadTranscript).toEqual({ error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${OWN_LEFT.unreadTranscript}` })+ expect(JSON.stringify(unreadTranscript)).not.toContain(home)+ expect(existsSync(join(shared, 'theirs.jsonl'))).toBe(true)+ expect(purgeRecord(join(home, 'super-tabs', 'team-purges.json')).pending()).toHaveLength(1)expect(await restarted('pm')).toEqual({ ok: true })expect(existsSync(join(shared, 'theirs.jsonl'))).toBe(true)})@@ -391,7 +553,7 @@ describe('the purge of a confidential session the Swarm ended', () => {rmSync(join(claude, 'paste-cache', 'abc123.txt'), { recursive: true })writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'left behind')const sweep = await sweepForSession(home, s.record.get('pm')!, s.record.get('pm')!.pastes!)- expect(sweep).toBe(join(claude, 'paste-cache', 'abc123.txt'))+ expect(sweep).toBe(SWEEP_LEFT.paste)expect(await ended('pm')).toEqual({ ok: true })})diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.tsindex 161e6800a..942262ac7 100644--- a/cli/src/superTabs/inCore/teamPurge.ts+++ b/cli/src/superTabs/inCore/teamPurge.ts@@ -13,7 +13,7 @@* reviewed purge drops the session from the stopped catalog, so a retry after a failed sweep had nothing left to scrub from.* Everything here reads and writes asynchronously: a Team home holds gigabytes of transcripts, and this runs in the core.*/-import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, type Dirent } from 'node:fs'import { readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'import { basename, dirname, join } from 'node:path'import { createInterface } from 'node:readline'@@ -90,6 +90,14 @@ function isTarget(id: string, entry: unknown): entry is PurgeTarget {&& (target.pastes === undefined || (Array.isArray(target.pastes) && target.pastes.every(paste => typeof paste === 'string')))}+/** What a scrub tells its caller: another folder's transcripts share its transcript folder, or what it could not read and+ * left, by kind alone. */+export type ScrubTold = 'shared' | 'unread' | 'unreadTodos' | 'unreadBackups'+/** [dir]'s names; null when it is there but cannot be listed. Only a folder that is not there is empty: read as empty, an+ * unlistable todos or backups folder let a Buddy's cleanup, which no sweep follows, finish and leave its todo file and its+ * folder in the backups (re-check of 8c0b019). The error itself is dropped, as its message names the path. */+const listed = (dir: string) => readdir(dir).catch((error: NodeJS.ErrnoException) => error.code === 'ENOENT' ? [] as string[] : null)+/** 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}$/@@ -155,8 +163,9 @@ export async function recordsOtherFolder(file: string, folder: string): Promise<} finally { lines.close() }}-/** Whether the transcript [file] records [folder] or a folder inside it as its working folder (`own`), and another (`other`). */-async function foldersOf(file: string, folder: string): Promise<{ own: boolean; other: boolean }> {+/** Whether the transcript [file] records [folder] or a folder inside it as its working folder (`own`), and another (`other`);+ * `unread` when it could not be read, whose error would name its path (review of #2389). */+async function foldersOf(file: string, folder: string): Promise<{ own: boolean; other: boolean; unread?: true }> {const found = { own: false, other: false }const lines = createInterface({ input: createReadStream(file, 'utf8'), crlfDelay: Infinity })try {@@ -166,7 +175,7 @@ async function foldersOf(file: string, folder: string): Promise<{ own: boolean;try { cwd = (JSON.parse(line) as { cwd?: unknown } | null)?.cwd } catch { continue }if (typeof cwd === 'string') found[cwd === folder || cwd.startsWith(`${folder}/`) ? 'own' : 'other'] = true}- } finally { lines.close() }+ } catch { return { own: false, other: false, unread: true } } finally { lines.close() }return found}@@ -177,13 +186,22 @@ async function foldersOf(file: string, folder: string): Promise<{ own: boolean;* and 2 of #2385: a Bash append, a subagent, a transcript Claude Code pruned, `Notes.md` on a Mac), and the Team purge's* sweep holds the account while one is there. A transcript that records no folder, or both, stays too, for the sweep to refuse.*/-async function removeTranscripts(dir: string, folder: string, onShared?: () => void): Promise<void> {- const transcripts = new Map<string, { own: boolean; other: boolean }>()- for (const name of (await readdir(dir).catch(() => [] as string[])).filter(name => name.endsWith('.jsonl'))) {+async function removeTranscripts(dir: string, folder: string, told?: (what: ScrubTold) => void): Promise<void> {+ // Only a folder that is not there is empty. One that cannot be listed stays whole, and its caller is told, by that word+ // alone: read as empty it went whole, its error's path into the log, or another folder's transcripts unread on a passing+ // error such as too many open files (security reviews 1 and 2 of 58b035e). The Team purge's sweep then holds the account;+ // a Buddy's cleanup, which has no sweep, fails and is tried again (host.ts endSession).+ const names = await readdir(dir).catch((error: NodeJS.ErrnoException) => error.code === 'ENOENT' ? [] : null)+ if (!names) { told?.('unread'); return }+ const transcripts = new Map<string, Awaited<ReturnType<typeof foldersOf>>>()+ for (const name of names.filter(name => name.endsWith('.jsonl'))) {transcripts.set(name, await foldersOf(join(dir, name), folder))}- if (![...transcripts.values()].some(transcript => transcript.other)) { await rm(dir, { recursive: true, force: true }); return }- onShared?.()+ // One that could not be read may be another folder's: it and the folder stay, and its caller is told.+ const values = [...transcripts.values()]+ if (values.some(transcript => transcript.unread)) told?.('unread')+ if (!values.some(transcript => transcript.other || transcript.unread)) { await rm(dir, { recursive: true, force: true }); return }+ if (values.some(transcript => transcript.other)) told?.('shared')for (const [name, { own, other }] of transcripts) {if (!own || other) continueawait rm(join(dir, name), { force: true })@@ -196,40 +214,80 @@ async function removeTranscripts(dir: string, folder: string, onShared?: () => v* folders and never [folder], their own folders, and an empty memory folder or none; anything else, a memory file above all,* or the folder itself once no other folder's transcript is left, fails it, closed. */async function leftInSharedFolder(dir: string, folder: string): Promise<string | null> {- const entries = (await readdir(dir, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name))+ // One that cannot be listed holds it by its kind; one gone since its parent was listed holds nothing.+ let entries: Dirent[]+ try { entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name)) } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? null : SHARED_LEFT.unreadFolder+ }+ const read = new Map<string, Awaited<ReturnType<typeof foldersOf>>>()+ for (const entry of entries.filter(entry => entry.isFile() && entry.name.endsWith('.jsonl'))) read.set(entry.name, await foldersOf(join(dir, entry.name), folder))+ // Said to be shared only when another folder's transcript is there (re-check 2 of 68ec6f0).+ const kinds = [...read.values()].some(transcript => transcript.other) ? SHARED_LEFT : OWN_LEFTconst transcripts = new Set<string>()- for (const entry of entries.filter(entry => entry.isFile() && entry.name.endsWith('.jsonl'))) {- const { own, other } = await foldersOf(join(dir, entry.name), folder)- if (own || !other) return SHARED_LEFT.transcript- transcripts.add(entry.name.slice(0, -'.jsonl'.length))+ for (const [name, { own, other, unread }] of read) {+ if (unread) return kinds.unreadTranscript+ if (own || !other) return kinds.transcript+ transcripts.add(name.slice(0, -'.jsonl'.length))}if (!transcripts.size) return SHARED_LEFT.folderfor (const entry of entries) {if (entry.isFile() && entry.name.endsWith('.jsonl')) continueif (entry.isDirectory() && entry.name === 'memory') {- if ((await readdir(join(dir, entry.name))).length) return SHARED_LEFT.memory+ // One that cannot be read fails it too, by its kind: the read's own error named its path (security review of #2385). One+ // gone since the listing is none.+ const memory = await readdir(join(dir, entry.name)).catch((error: NodeJS.ErrnoException) => error.code === 'ENOENT' ? [] : null)+ if (!memory) return SHARED_LEFT.unreadMemory+ if (memory.length) return SHARED_LEFT.memory} else if (!entry.isDirectory() || !transcripts.has(entry.name)) return SHARED_LEFT.other}return null}+/** What a held account's owner does about what could not be read: nothing names its path, and the host tries the purge again+ * by itself (host.ts endSession), so fixing it is the whole of it (security review 1 of 58b035e). [find]: where to look, when+ * its kind alone does not say (re-check of 8c0b019). */+const makeReadable = (find?: string) =>+ `could not be read: its owner ${find ? `finds it (${find}) and ` : ''}makes it readable for the Team account, and the purge finishes on its next try`+const MAKE_READABLE = makeReadable()/** What a failed sweep says of its shared transcript folder, in place of a path. */export const SHARED_LEFT = {transcript: 'a transcript in its transcript folder, which another folder shares, that records its folder or none',memory: 'a memory file in its transcript folder, which another folder shares: its owner checks it and removes what is not the other folder\'s',+ unreadFolder: `its transcript folder, which ${MAKE_READABLE}`,+ unreadMemory: `a memory folder in its transcript folder, which another folder shares, that ${MAKE_READABLE}`,+ unreadTranscript: `a transcript in its transcript folder, which another folder shares, that ${MAKE_READABLE}`,other: 'something in its transcript folder, which another folder shares, that is not another folder\'s transcript',folder: 'its transcript folder',}+/** The same, for a transcript folder no other folder's transcript is in. */+export const OWN_LEFT = {+ transcript: 'a transcript in its transcript folder that records its folder or none',+ unreadTranscript: `a transcript in its transcript folder that ${MAKE_READABLE}`,+}+/** What the sweep names of what it found or could not read, in place of a path: one held the Team home's, and could name another+ * folder (re-check 2 of 68ec6f0). */+export const SWEEP_LEFT = {+ claudeHistory: 'a line of Claude Code\'s prompt history that names its session or its folder',+ codexHistory: 'a line of Codex\'s prompt history that names its session or its folder',+ paste: 'a paste Claude Code kept from one of its prompts',+ config: 'its folder in Claude Code\'s config, or in a backup of it',+ claudeNamed: 'a file or folder in Claude Code\'s home named for its session or its folder',+ codexNamed: 'a file or folder in Codex\'s home named for its session or its folder',+ unreadFile: `a file in the Team account's Claude Code or Codex home that ${makeReadable('search the Team account\'s Claude Code and Codex homes for files it can\'t read')}`,+ unlistedFolder: `a folder in the Team account's Claude Code or Codex home that ${makeReadable('search the Team account\'s Claude Code and Codex homes for folders it can\'t read')}`,+}/*** Removes from the Team user's shared Claude Code home ([home]/.claude, [home]/.claude.json and its backups) what Claude* Code keeps of the session: its prompt history lines and the pastes they kept ([pastes] from an earlier attempt too), its* project folder with its transcripts and memory (only the transcripts that record its folder alone when another folder's- * share it, [onShared]),+ * share it, and [told] 'shared'; [told] 'unread' when its transcript folder or one of its transcripts could not be read, and+ * stays),* its file history, todos, session environment and debug log, and its folder's entry and repository paths in the config- * and in every backup of it. The pastes its history named, for the record.+ * and in every backup of it ([told] 'unreadTodos' or 'unreadBackups' when that folder could not be listed). The pastes its+ * history named, for the record.*/export async function scrubClaudeSession(home: string, target: PurgeTarget, pastes: readonly string[] = [],- onPastes?: (pastes: string[]) => void, onShared?: () => void): Promise<string[]> {+ onPastes?: (pastes: string[]) => void, told?: (what: ScrubTold) => void): Promise<string[]> {const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : nullconst folder = folderOf(target)if (!sessionId && !folder) return []@@ -257,18 +315,20 @@ export async function scrubClaudeSession(home: string, target: PurgeTarget, pastreturn kept.length ? `${kept.join('\n')}\n` : ''})for (const hash of new Set([...pastes, ...found])) if (SESSION.test(hash)) await rm(join(claude, 'paste-cache', `${hash}.txt`), { force: true })- if (folder) await removeTranscripts(join(claude, 'projects', claudeSlug(folder)), folder, onShared)+ if (folder) await removeTranscripts(join(claude, 'projects', claudeSlug(folder)), folder, told)if (sessionId) {for (const sub of ['file-history', 'session-env']) await rm(join(claude, sub, sessionId), { recursive: true, force: true })await rm(join(claude, 'debug', `${sessionId}.txt`), { force: true })- const todos = await readdir(join(claude, 'todos')).catch(() => [] as string[])+ const todos = await listed(join(claude, 'todos'))+ if (!todos) told?.('unreadTodos')// `<session>-agent-<agent>.json`: by prefix alone, a one-character id took every todo starting with it (security review 2 of #2375).- for (const name of todos) if (name.startsWith(`${sessionId}-agent-`)) await rm(join(claude, 'todos', name), { force: true })+ for (const name of todos ?? []) if (name.startsWith(`${sessionId}-agent-`)) await rm(join(claude, 'todos', name), { force: true })}if (folder) {await rewriteIfUnchanged(join(home, '.claude.json'), text => withoutFolder(text, folder))- const backups = await readdir(join(claude, 'backups')).catch(() => [] as string[])- for (const name of backups) await rewriteIfUnchanged(join(claude, 'backups', name), text => withoutFolder(text, folder))+ const backups = await listed(join(claude, 'backups'))+ if (!backups) told?.('unreadBackups')+ for (const name of backups ?? []) await rewriteIfUnchanged(join(claude, 'backups', name), text => withoutFolder(text, folder))}return [...new Set(found)]}@@ -286,32 +346,43 @@ export async function sweepForSession(home: string, target: PurgeTarget, pastes:const claude = join(home, '.claude'), codex = join(home, '.codex')const quoted = [...sessionId ? [`"${sessionId}"`] : [], ...folder ? [`"${folder}"`, `"${folder}/`] : []]const names = (path: string) => quoted.some(q => path.includes(q))- for (const history of [join(claude, 'history.jsonl'), join(codex, 'history.jsonl')]) {- const text = await readFile(history, 'utf8').catch(() => '')- if (names(text)) return history+ // Only what is not there is empty: anything else that cannot be read holds the account, by its kind. Read as empty, an+ // unreadable projects folder let the account go with the session's transcript in it (re-checks 1 and 2 of 68ec6f0).+ const gone = (error: NodeJS.ErrnoException) => error.code === 'ENOENT'+ const read = (path: string) => readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => gone(error) ? '' : null)+ for (const [history, kind] of [[join(claude, 'history.jsonl'), SWEEP_LEFT.claudeHistory], [join(codex, 'history.jsonl'), SWEEP_LEFT.codexHistory]]) {+ const text = await read(history)+ if (text === null) return SWEEP_LEFT.unreadFile+ if (names(text)) return kind}- for (const hash of pastes) if (SESSION.test(hash) && existsSync(join(claude, 'paste-cache', `${hash}.txt`))) return join(claude, 'paste-cache', `${hash}.txt`)+ for (const hash of pastes) if (SESSION.test(hash) && existsSync(join(claude, 'paste-cache', `${hash}.txt`))) return SWEEP_LEFT.pasteif (folder) {- const configs = [join(home, '.claude.json'), ...(await readdir(join(claude, 'backups')).catch(() => [] as string[])).map(name => join(claude, 'backups', name))]- for (const config of configs) if ((await readFile(config, 'utf8').catch(() => '')).includes(`"${folder}"`)) return config+ const backups = await readdir(join(claude, 'backups')).catch((error: NodeJS.ErrnoException) => gone(error) ? [] : null)+ if (!backups) return SWEEP_LEFT.unlistedFolder+ for (const config of [join(home, '.claude.json'), ...backups.map(name => join(claude, 'backups', name))]) {+ const text = await read(config)+ if (text === null) return SWEEP_LEFT.unreadFile+ if (text.includes(`"${folder}"`)) return SWEEP_LEFT.config+ }}const slug = folder ? claudeSlug(folder) : null, projects = join(claude, 'projects')- const walk = async (path: string): Promise<string | null> => {- const entries = await readdir(path, { withFileTypes: true }).catch(() => [])+ const walk = async (path: string, named: string): Promise<string | null> => {+ let entries: Dirent[]+ try { entries = await readdir(path, { withFileTypes: true }) } catch (error) { return gone(error as NodeJS.ErrnoException) ? null : SWEEP_LEFT.unlistedFolder }for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {const child = join(path, entry.name)- if (sessionId && entry.name.includes(sessionId)) return child+ if (sessionId && entry.name.includes(sessionId)) return namedif (entry.name === slug) {// Its transcript folder outlives the scrub when another folder's transcripts share it ('/' and '.' both become '-'),// and its name alone held the account for good (follow-up to security review 2 of #2375).- const left = path === projects && entry.isDirectory() ? await leftInSharedFolder(child, folder!) : child+ const left = path === projects && entry.isDirectory() ? await leftInSharedFolder(child, folder!) : namedif (left) return left}- if (entry.isDirectory()) { const found = await walk(child); if (found) return found }+ if (entry.isDirectory()) { const found = await walk(child, named); if (found) return found }}return null}- for (const root of [claude, codex]) { const found = await walk(root); if (found) return found }+ for (const [root, named] of [[claude, SWEEP_LEFT.claudeNamed], [codex, SWEEP_LEFT.codexNamed]]) { const found = await walk(root, named); if (found) return found }return null}