Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): a Buddy scrub reloaded after a restart names only a worktree of this machine (#2375)

harness-for-autonomous[bot]d4a9e1944913
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 2e64c7198..90c001bf1 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -1,6 +1,6 @@
import { spawnSync } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
-import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { prepareSwarmSkill } from '../lib/swarmSkills.js'
@@ -2875,7 +2875,7 @@ describe('closing the sessions the backend ends', () => {
JSON.stringify({ sessionId: 'buddy-sid', project: folder, pastedContents: { 1: { contentHash: 'ownpaste' } } }),
JSON.stringify({ sessionId: 'other-sid', project: other, pastedContents: { 1: { contentHash: 'theirpaste' } } }),
].join('\n') + '\n')
- const t = lifeFixture([ended()], { claudeHome: home })
+ const t = lifeFixture([ended()], { claudeHome: home, 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.commands).toHaveLength(1))
@@ -2891,28 +2891,223 @@ describe('closing the sessions the backend ends', () => {
// Security re-check 2 of #2345: what to scrub was known only in memory, so a host restarted between the close and the scrub
// left the transcript for good. It is written to the journal before the close, and the restarted host scrubs from there.
it('still scrubs an ended Buddy session\'s traces when its host restarts between the close and the scrub', async () => {
- const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude')
- const folder = '/work/worktrees/openharness/buddy-session', slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')
+ const folder = join(worktrees, 'openharness', 'buddy-session'), slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')
try {
+ mkdirSync(folder, { recursive: true })
mkdirSync(join(claude, 'projects', slug(folder)), { recursive: true })
writeFileSync(join(claude, 'projects', slug(folder), 'x.jsonl'), 'transcript')
- const t = lifeFixture([ended()], { claudeHome: home })
- t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: 'buddy-sid', engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)
+ const t = lifeFixture([ended()], { claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })
+ const sid = '33333333-3333-4333-8333-333333333333'
+ t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: sid, engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)
// The first host's close never returns: it stops before the scrub.
t.closeMember.mockImplementation(() => new Promise(() => {}))
await t.poll()
- expect(t.saved().scrubs).toEqual({ agent: { agentId: 'agent', sessionId: 'buddy-sid', cwd: folder, engine: 'claude', codexHome: null } })
+ expect(t.saved().scrubs).toEqual({ agent: { agentId: 'agent', sessionId: sid, cwd: folder, engine: 'claude', codexHome: null } })
t.host.stop()
// Restarted: the session is no longer registered here, and the close goes through.
t.core.agents.byAgent = vi.fn(() => undefined as never)
t.closeMember.mockImplementation(async () => ({ closed: true as const }))
- const again = t.open({ claudeHome: home })
+ const again = t.open({ claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })
await again.tick()
await vi.waitFor(() => expect(existsSync(join(claude, 'projects', slug(folder)))).toBe(false))
await vi.waitFor(() => expect(t.saved().scrubs).toBeUndefined())
} finally { rmSync(home, { recursive: true, force: true }) }
})
+ // Follow-up to security review 1 of #2345: a reloaded target was trusted for any absolute folder, so a hand-edited or
+ // corrupted journal could point the scrub at another folder's Claude Code transcripts. Only a Buddy worktree's is kept:
+ // `<worktrees>/<repository>/<leaf>` as written and once its symlinks are resolved, or one already removed from there.
+ it('scrubs after a restart only a saved folder in this machine\'s worktrees, never one outside, through a symlink or with ..', async () => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')
+ const slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')
+ const mine = join(home, 'code', 'mine'), repository = join(worktrees, 'openharness')
+ const cwds: Record<string, string> = {
+ real: join(repository, 'buddy-session'),
+ removed: join(repository, 'removed-session'),
+ outside: mine,
+ symlinked: join(repository, 'link-out'),
+ dangling: join(repository, 'link-gone'),
+ dotted: `${repository}/../../../code/mine`,
+ dottedInside: `${repository}/../openharness/buddy-session`,
+ shallow: repository,
+ deep: join(repository, 'buddy-session', 'sub'),
+ into: join(home, 'code', 'link-in'),
+ relative: 'harnesses/worktrees/openharness/buddy-session',
+ }
+ try {
+ mkdirSync(join(cwds.real, 'sub'), { recursive: true })
+ mkdirSync(mine, { recursive: true })
+ symlinkSync(mine, cwds.symlinked)
+ symlinkSync(cwds.real, cwds.into)
+ symlinkSync(join(home, 'code', 'gone'), cwds.dangling)
+ for (const cwd of new Set([...Object.values(cwds), mine])) {
+ mkdirSync(join(claude, 'projects', slug(cwd)), { recursive: true })
+ writeFileSync(join(claude, 'projects', slug(cwd), 'x.jsonl'), 'transcript')
+ }
+ const rows = Object.keys(cwds).map(id => ended({ agent: { id, harnessId: `h-${id}`, machineId: 'machine-1' } }))
+ const t = lifeFixture(rows, { claudeHome: home, worktrees })
+ t.host.stop()
+ // A journal as this host writes it, each target hand-edited to another folder but for the real and the removed one.
+ const scrubs = Object.fromEntries(Object.entries(cwds).map(([agentId, cwd]) => [agentId, { agentId, sessionId: null, cwd, engine: 'claude', codexHome: null }]))
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), JSON.stringify({ ...t.saved(), scrubs }))
+ t.core.agents.byAgent = vi.fn(() => undefined as never)
+ const again = t.open({ claudeHome: home, worktrees, startReceipt: harnessId => `super-${cwds[harnessId.slice(2)].split('/').pop()}` })
+ expect(Object.keys(t.saved().scrubs).sort()).toEqual(['real', 'removed'])
+ for (const id of ['outside', 'symlinked', 'dangling', 'dotted', 'dottedInside', 'shallow', 'deep', 'into', 'relative']) {
+ expect(t.log).toHaveBeenCalledWith(`Dropped a saved Buddy session scrub this host did not write: agent ${id}`)
+ }
+ // By agent id only: no folder of any of them is logged.
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain(home)
+ await again.tick()
+ await vi.waitFor(() => expect(t.commands).toHaveLength(rows.length))
+ await vi.waitFor(() => expect(t.saved().scrubs).toBeUndefined())
+ expect(existsSync(join(claude, 'projects', slug(cwds.real)))).toBe(false)
+ expect(existsSync(join(claude, 'projects', slug(cwds.removed)))).toBe(false)
+ for (const id of ['outside', 'symlinked', 'dangling', 'dotted', 'dottedInside', 'shallow', 'deep', 'into', 'relative']) {
+ expect(existsSync(join(claude, 'projects', slug(cwds[id]), 'x.jsonl'))).toBe(true)
+ }
+ expect(existsSync(join(claude, 'projects', slug(mine), 'x.jsonl'))).toBe(true)
+ } finally { rmSync(home, { recursive: true, force: true }) }
+ })
+
+ // Security review 2 of #2375: the saved session id was trusted, so a person's own session id beside a real worktree took
+ // their prompt history, a paste, file history and debug log. It is used only when nothing ties it to another folder: a
+ // history line with another project, or a transcript in another folder's transcript folder. The folder's cleanup stays.
+ it('keeps a person\'s own session when a saved scrub names its id, and still removes the worktree\'s transcripts', async () => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')
+ const slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')
+ const folder = join(worktrees, 'openharness', 'buddy-session'), mine = join(home, 'code', 'mine')
+ // Theirs by a history line; theirs by a transcript in their own folder's transcript folder, with no history line.
+ const byHistory = '11111111-1111-4111-8111-111111111111', byTranscript = '22222222-2222-4222-8222-222222222222'
+ try {
+ mkdirSync(folder, { recursive: true })
+ for (const sub of ['paste-cache', 'todos', 'debug', `projects/${slug(folder)}`, `projects/${slug(mine)}`]) mkdirSync(join(claude, sub), { recursive: true })
+ writeFileSync(join(claude, 'projects', slug(folder), 'own.jsonl'), JSON.stringify({ cwd: folder }))
+ writeFileSync(join(claude, 'projects', slug(mine), `${byTranscript}.jsonl`), JSON.stringify({ cwd: mine }))
+ writeFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ sessionId: byHistory, project: mine, pastedContents: { 1: { contentHash: 'theirpaste' } } })}\n`)
+ writeFileSync(join(claude, 'paste-cache', 'theirpaste.txt'), 'secret')
+ for (const id of [byHistory, byTranscript]) {
+ mkdirSync(join(claude, 'file-history', id), { recursive: true })
+ writeFileSync(join(claude, 'debug', `${id}.txt`), 'debug')
+ writeFileSync(join(claude, 'todos', `${id}-agent-${id}.json`), '[]')
+ }
+ const rows = ['history', 'transcript'].map(id => ended({ agent: { id, harnessId: `h-${id}`, machineId: 'machine-1' } }))
+ const t = lifeFixture(rows, { claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })
+ t.host.stop()
+ const scrubs = { history: { agentId: 'history', sessionId: byHistory, cwd: folder, engine: 'claude', codexHome: null },
+ transcript: { agentId: 'transcript', sessionId: byTranscript, cwd: folder, engine: 'claude', codexHome: null } }
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), JSON.stringify({ ...t.saved(), scrubs }))
+ t.core.agents.byAgent = vi.fn(() => undefined as never)
+ const again = t.open({ claudeHome: home, worktrees, startReceipt: () => 'super-buddy-session' })
+ await again.tick()
+ await vi.waitFor(() => expect(t.saved().scrubs).toBeUndefined())
+ expect(existsSync(join(claude, 'projects', slug(folder)))).toBe(false)
+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toContain(byHistory)
+ expect(existsSync(join(claude, 'paste-cache', 'theirpaste.txt'))).toBe(true)
+ expect(existsSync(join(claude, 'projects', slug(mine), `${byTranscript}.jsonl`))).toBe(true)
+ for (const id of [byHistory, byTranscript]) {
+ for (const kept of [`file-history/${id}`, `debug/${id}.txt`, `todos/${id}-agent-${id}.json`]) expect(existsSync(join(claude, kept)), kept).toBe(true)
+ }
+ for (const id of ['history', 'transcript']) expect(t.log).toHaveBeenCalledWith(`Kept another folder's session that a Buddy session scrub named: agent ${id}`)
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain(home)
+ } finally { rmSync(home, { recursive: true, force: true }) }
+ })
+
+ // Security review 1 of #2375: any Harness worktree passed, so a saved entry naming a person's own Desktop worktree or another
+ // agent's, both in the same folder, took every transcript, history line and config entry of it. Only the worktree named
+ // for this agent's own Swarm start is scrubbed (its name, or with -2, -3), and with no start receipt, none is.
+ it('scrubs only the worktree of the agent\'s own Swarm start, never another agent\'s or a person\'s', async () => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude'), worktrees = join(home, 'harnesses', 'worktrees')
+ const slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-'), repository = join(worktrees, 'openharness')
+ // Each agent's own start is `own`; the folder each saved entry names.
+ const cwds: Record<string, string> = {
+ own: join(repository, 'own'), taken: join(repository, 'own-2'),
+ otherAgent: join(repository, 'other-start'), person: join(repository, 'my-feature'), prefix: join(repository, 'own-x'), noReceipt: join(repository, 'own-3'),
+ }
+ try {
+ for (const cwd of new Set(Object.values(cwds))) {
+ mkdirSync(cwd, { recursive: true })
+ mkdirSync(join(claude, 'projects', slug(cwd)), { recursive: true })
+ writeFileSync(join(claude, 'projects', slug(cwd), 'x.jsonl'), JSON.stringify({ cwd }))
+ }
+ const rows = Object.keys(cwds).map(id => ended({ agent: { id, harnessId: `h-${id}`, machineId: 'machine-1' } }))
+ const startReceipt = (harnessId: string) => harnessId === 'h-noReceipt' ? null : 'super-own'
+ const t = lifeFixture(rows, { claudeHome: home, worktrees, startReceipt })
+ t.host.stop()
+ const scrubs = Object.fromEntries(Object.entries(cwds).map(([agentId, cwd]) => [agentId, { agentId, sessionId: null, cwd, engine: 'claude', codexHome: null }]))
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), JSON.stringify({ ...t.saved(), scrubs }))
+ t.core.agents.byAgent = vi.fn(() => undefined as never)
+ const again = t.open({ claudeHome: home, worktrees, startReceipt })
+ await again.tick()
+ await vi.waitFor(() => expect(t.commands).toHaveLength(rows.length))
+ await vi.waitFor(() => expect(t.saved().scrubs).toBeUndefined())
+ expect([cwds.own, cwds.taken].map(cwd => existsSync(join(claude, 'projects', slug(cwd))))).toEqual([false, false])
+ for (const cwd of [cwds.otherAgent, cwds.person, cwds.prefix, cwds.noReceipt]) expect(existsSync(join(claude, 'projects', slug(cwd), 'x.jsonl')), cwd).toBe(true)
+ for (const id of ['otherAgent', 'person', 'prefix', 'noReceipt']) {
+ expect(t.log).toHaveBeenCalledWith(`Dropped a Buddy session scrub that names no worktree of its own start: agent ${id}`)
+ }
+ expect(t.log).not.toHaveBeenCalledWith('Dropped a Buddy session scrub that names no worktree of its own start: agent own')
+ expect(t.log).not.toHaveBeenCalledWith('Dropped a Buddy session scrub that names no worktree of its own start: agent taken')
+ } finally { rmSync(home, { recursive: true, force: true }) }
+ })
+
+ // Security review 2 of #2375: a saved session id is a Claude Code session's, a UUID; another is dropped on reload, the folder kept.
+ it('drops a saved session id that is not a UUID on reload, and keeps the folder\'s scrub', async () => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), worktrees = join(home, 'harnesses', 'worktrees')
+ const folder = join(worktrees, 'openharness', 'buddy-session')
+ try {
+ mkdirSync(folder, { recursive: true })
+ const t = lifeFixture([], { claudeHome: home, worktrees })
+ t.host.stop()
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), JSON.stringify({ ...t.saved(), scrubs: {
+ agent: { agentId: 'agent', sessionId: 'a', cwd: folder, engine: 'claude', codexHome: null } } }))
+ t.open({ claudeHome: home, worktrees })
+ expect(t.saved().scrubs).toEqual({ agent: { agentId: 'agent', sessionId: null, cwd: folder, engine: 'claude', codexHome: null } })
+ expect(t.log).toHaveBeenCalledWith('Dropped the session id of a saved Buddy session scrub: agent agent')
+ } finally { rmSync(home, { recursive: true, force: true }) }
+ })
+
+ // Security review 2 of #2375: a failed scrub logged its raw error, which names the transcript folder's path.
+ it('logs a failed scrub as a fixed code, never its path, and scrubs on a later try', async () => {
+ 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, '-'))
+ try {
+ mkdirSync(folder, { recursive: true })
+ mkdirSync(transcripts, { recursive: true })
+ writeFileSync(join(transcripts, 'own.jsonl'), JSON.stringify({ cwd: folder }))
+ chmodSync(join(claude, 'projects'), 0o555)
+ 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, SCRUB_FAILED'))
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain(home)
+ expect(t.commands).toEqual([])
+ chmodSync(join(claude, 'projects'), 0o755)
+ await t.poll(60_000)
+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))
+ expect(existsSync(transcripts)).toBe(false)
+ } finally { chmodSync(join(claude, 'projects'), 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')
+ try {
+ const t = lifeFixture([], { claudeHome: home, worktrees })
+ t.host.stop()
+ const cwd = join(worktrees, 'openharness', 'buddy-session')
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), JSON.stringify({ ...t.saved(), scrubs: {
+ agent: { agentId: 'agent', sessionId: null, cwd, engine: 'claude', codexHome: null },
+ '../not an id': { agentId: '../not an id', sessionId: null, cwd, engine: 'claude', codexHome: null } } }))
+ t.open({ claudeHome: home, worktrees })
+ expect(t.saved().scrubs).toBeUndefined()
+ expect(t.log).toHaveBeenCalledWith('Dropped a saved Buddy session scrub this host did not write: agent agent')
+ expect(t.log).toHaveBeenCalledWith('Dropped a saved Buddy session scrub this host did not write: an unreadable agent id')
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain('not an id')
+ } finally { rmSync(home, { recursive: true, force: true }) }
+ })
+
// Diego, 10-30: removing an agent or deleting its project left its worktree to the weekly sweep, up to a week later. It goes
// once its close is acknowledged, under the stopped worker's own rules (machines.ts removeStoppedWorktree).
it('removes the ended session\'s worktree only once its close is acknowledged, and a failed removal is only logged', async () => {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 4b2a1431f..e3fa982c4 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -6,8 +6,9 @@ import { configurationObservation } from './configuration.js'
import { NativeRecorder, nativeJournalFile } from './native.js'
import { attachedFiles, attachmentsOf } from './attachments.js'
import { createHash, randomUUID } from 'node:crypto'
-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
+import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
+import { readdir, readFile } from 'node:fs/promises'
+import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'
import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'
import { shellQuote } from '../orchestrator/prompts.js'
import { agentCommandPrefix, fullCommandPrefix } from './shortCommand.js'
@@ -17,13 +18,15 @@ import { noticeReason, WithheldDeliveries } from './withheld.js'
import { attentionOf } from './attention.js'
import { prepareContribution, prepareTeamContribution } from './contribution.js'
import { homedir, hostname } from 'node:os'
-import { scrubClaudeSession, type PurgeTarget } from './inCore/teamPurge.js'
+import { recordsOtherFolder, scrubClaudeSession, type PurgeTarget } from './inCore/teamPurge.js'
import { replacementObservations } from './replacements.js'
import { TerminalHost } from './terminal.js'
import { LimitResume } from './limitResume.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
import { UPDATE_REQUIRED } from './readContract.js'
+import { projectsRoot } from '../lib/projectFolder.js'
+import { worktreeFolderName } from '../lib/agentNames.js'
type Json = Record<string, unknown>
// A Buddy is told its commands without --agent: the pane it runs in says who it is (command.ts callerOf), and its guard
@@ -141,6 +144,9 @@ export interface SuperTabHostOptions {
startReceipt?: (harnessId: string) => string | null
/** The home whose Claude Code data an ended Buddy session's own traces are removed from; this user's, unless a spec says. */
claudeHome?: string
+ /** Harness's worktrees folder, where every Buddy session's folder is (lib/gitProject.ts): a scrub the journal saved names
+ * only a folder there. This user's, unless a spec says. */
+ worktrees?: string
/** The machine's host form and Swarm reads, shared with the service's other readers (superTabs/service.ts). */
sources?: SwarmSources
/** What the contributed-machine executor reaches the local daemon with (superTabs/machines.ts), for a spec. */
@@ -150,6 +156,48 @@ export interface SuperTabHostOptions {
const defaultAgentCommand = (core: CoreApi, machineId: string) => agentCommandPrefix(core.daemon, machineId,
() => readAuthSession()?.machineId || computerId())
export const hostJournalFile = (dataDir: string, machineId: string) => join(dataDir, 'super-tabs', `host-${machineId}.json`)
+/** Whether [cwd] is a folder this host records a Buddy session's scrub for: a worktree, `<worktrees>/<repository>/<leaf>`
+ * (lib/gitProject.ts; the backend starts every Buddy session in one), as written and once its symlinks are resolved, so
+ * neither a `..` nor a link leads the scrub to another folder's transcripts (follow-up to security review 1 of #2345). One
+ * already removed still is: its missing part cannot lead anywhere, and its traces must still go. */
+function buddyWorktree(cwd: string, worktrees: string): boolean {
+ const leafOf = (root: string, path: string) => { const parts = relative(root, path).split(sep); return parts.length === 2 && parts.every(p => p && p !== '..') }
+ try {
+ const home = realpathSync(worktrees)
+ if (!isAbsolute(cwd) || normalize(cwd) !== cwd || cwd.endsWith(sep) || !(leafOf(worktrees, cwd) || leafOf(home, cwd))) return false
+ // The deepest part of it that is there, resolved; a part that is not there at all (lstat: not even a dangling link) is kept as named.
+ let found = cwd
+ const missing: string[] = []
+ for (;;) {
+ try { found = realpathSync(found); break } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || lstatSync(found, { throwIfNoEntry: false })) return false
+ missing.unshift(basename(found))
+ found = dirname(found)
+ }
+ }
+ return leafOf(home, join(found, ...missing))
+ } catch { return false }
+}
+/** 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
+/** 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. */
+async function sessionOfFolder(home: string, sessionId: string, folder: string): Promise<boolean> {
+ const claude = join(home, '.claude'), own = (cwd: unknown) => cwd === folder || (typeof cwd === 'string' && cwd.startsWith(`${folder}/`))
+ const missing = (error: NodeJS.ErrnoException) => { if (error?.code === 'ENOENT') return null; throw error }
+ for (const line of (await readFile(join(claude, 'history.jsonl'), 'utf8').catch(missing) ?? '').split('\n')) {
+ if (!line.includes(sessionId)) continue
+ let row: { sessionId?: unknown; project?: unknown }
+ try { row = JSON.parse(line) } catch { continue }
+ if (row.sessionId === sessionId && !own(row.project)) return false
+ }
+ for (const name of await readdir(join(claude, 'projects')).catch(missing) ?? []) {
+ const transcript = join(claude, 'projects', name, `${sessionId}.jsonl`)
+ if (existsSync(transcript) && await recordsOtherFolder(transcript, folder)) return false
+ }
+ return true
+}
/** How long after an add the roster may ask for another (a roster read may predate the add), and the first wait after a
* failed one. Each try probes every engine's account (about 14 login shells), so the wait doubles up to half an hour:
* a refusal such as a dispatched start that never reports, or no signed-in engine, can last for days. */
@@ -296,6 +344,7 @@ export class SuperTabHost {
private readonly agentCommand: (core: CoreApi, machineId: string) => Promise<string>
private readonly startReceipt: (harnessId: string) => string | null
private readonly claudeHome: string
+ private readonly worktrees: string
/** Asked once, on the first delivery: the answer cannot change while this daemon runs (superTabs/shortCommand.ts). */
private prefix: Promise<string> | null = null
private configurationsRunning: Promise<void> | null = null
@@ -355,6 +404,7 @@ export class SuperTabHost {
this.agentCommand = options.agentCommand ?? defaultAgentCommand
this.startReceipt = options.startReceipt ?? (() => null)
this.claudeHome = options.claudeHome ?? homedir()
+ this.worktrees = options.worktrees ?? join(projectsRoot(), 'worktrees')
this.now = options.now ?? Date.now
this.write = options.write ?? writeJournal
this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
@@ -383,14 +433,17 @@ export class SuperTabHost {
}
this.journal.entries[id] = entry
}
- // Only a target this host could have written: its own agent id, a Claude Code session in a folder. Another is dropped,
- // never trusted, so a hand-edited journal cannot point the scrub elsewhere than a session folder's own traces.
+ // Only a target this host could have written: its own agent id, a Claude Code session in a Buddy's worktree here. Another
+ // is dropped, never trusted, so a hand-edited or corrupted journal cannot point the scrub at another folder's transcripts
+ // (follow-up to security review 1 of #2345). Said by agent id alone: the folder is what may not be trusted, or shown.
for (const [agentId, value] of Object.entries(object(saved.scrubs))) {
const t = object(value)
- if (agentId === t.agentId && identifier(agentId) && t.engine === 'claude' && typeof t.cwd === 'string' && t.cwd.startsWith('/')
+ if (agentId === t.agentId && identifier(agentId) && t.engine === 'claude' && typeof t.cwd === 'string' && buddyWorktree(t.cwd, this.worktrees)
&& (t.sessionId === null || typeof t.sessionId === 'string') && t.codexHome === null) {
- (this.journal.scrubs ??= {})[agentId] = { agentId, sessionId: t.sessionId as string | null, cwd: t.cwd, engine: 'claude', codexHome: null }
- }
+ const sessionId = typeof t.sessionId === 'string' && !CLAUDE_SESSION.test(t.sessionId) ? null : t.sessionId as string | null
+ if (sessionId !== t.sessionId) this.log(`Dropped the session id of a saved Buddy session scrub: agent ${agentId}`)
+ ;(this.journal.scrubs ??= {})[agentId] = { agentId, sessionId, cwd: t.cwd, engine: 'claude', codexHome: null }
+ } else this.log(`Dropped a saved Buddy session scrub this host did not write: ${identifier(agentId) ? `agent ${agentId}` : 'an unreadable agent id'}`)
}
}
this.persist()
@@ -1027,7 +1080,14 @@ export class SuperTabHost {
state.closed = true
}
if (state.scrub && !state.scrubbed) {
- await scrubClaudeSession(this.claudeHome, state.scrub)
+ // A fixed code: the error's own text names the transcript folder's path (security review 2 of #2375).
+ 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`) })
+ }
state.scrubbed = true
if (this.journal.scrubs?.[agent.id]) {
delete this.journal.scrubs[agent.id]
@@ -1050,6 +1110,26 @@ export class SuperTabHost {
}).finally(() => { state.running = false })
}
+ /** What of [target] an ended Buddy session's scrub removes, or null when its folder is not this agent's own. Any Harness
+ * worktree passed, a person's own (Desktop makes them there too) or another agent's included (security review 1 of
+ * #2375): only the one named for this agent's own Swarm start is (start.ts names its branch super-tab/<start>, the
+ * folder is named after it, -2, -3 when taken; machines.ts swarmWorktree checks the same). Its session id goes only when
+ * it is that folder's. */
+ private async ownScrub(agentId: string, harnessId: string, target: PurgeTarget): Promise<PurgeTarget | null> {
+ const creation = this.startReceipt(harnessId), folder = target.cwd ?? ''
+ const leaf = creation?.startsWith('super-') ? worktreeFolderName(`super-tab/${creation.slice('super-'.length)}`) : null
+ const name = basename(folder)
+ if (!leaf || (name !== leaf && !/^\d+$/.test(name.startsWith(`${leaf}-`) ? name.slice(leaf.length + 1) : ''))) {
+ this.log(`Dropped a Buddy session scrub that names no worktree of its own start: agent ${agentId}`)
+ return null
+ }
+ if (target.sessionId && !await sessionOfFolder(this.claudeHome, target.sessionId, folder)) {
+ this.log(`Kept another folder's session that a Buddy session scrub named: agent ${agentId}`)
+ return { ...target, sessionId: null }
+ }
+ return target
+ }
+
/** A CLI update can ship new built-in skill text while Swarm sessions run; until now a running agent kept the text it
* read at start, so a skill release reached nobody until each agent restarted (owner, 2026-10-22). Rewrite a role
* session's file at once; tell its agent through the Swarm, as any delivery, once it is in an open group. The
diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.ts
index 729d86d77..61023387b 100644
--- a/cli/src/superTabs/inCore/teamPurge.spec.ts
+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts
@@ -1,4 +1,4 @@
-import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
@@ -39,6 +39,37 @@ function teamHome() {
}
describe('scrubbing a Claude Code session from the Team user\'s shared home', () => {
+ // Security review 2 of #2375: Claude Code's transcript folder name makes every '/' and '.' a dash, so a removed worktree
+ // `<worktrees>/old/notes` shares it with an unrelated `~/harnesses/worktrees-old/notes`. Only transcripts that record no
+ // other working folder are the session's; the folder goes whole only when every one is.
+ it('removes only its own transcripts from a transcript folder another folder\'s sessions share, and says so', async () => {
+ const home = dir(), claude = join(home, '.claude'), folder = '/Users/me/harnesses/worktrees/old/notes'
+ const shared = join(claude, 'projects', folder.replace(/[^A-Za-z0-9]/g, '-'))
+ expect(shared).toBe(join(claude, 'projects', '/Users/me/harnesses/worktrees-old/notes'.replace(/[^A-Za-z0-9]/g, '-')))
+ for (const sub of ['own/subagents', 'theirs/subagents', 'memory']) mkdirSync(join(shared, sub), { recursive: true })
+ writeFileSync(join(shared, 'own.jsonl'), [JSON.stringify({ type: 'summary' }), JSON.stringify({ cwd: folder }), JSON.stringify({ cwd: `${folder}/src` }), 'not json "cwd"'].join('\n'))
+ writeFileSync(join(shared, 'theirs.jsonl'), [JSON.stringify({ cwd: '/Users/me/harnesses/worktrees-old/notes' })].join('\n'))
+ const shares = vi.fn()
+ await scrubClaudeSession(home, target({ sessionId: null, cwd: folder }), [], undefined, shares)
+ expect(['own.jsonl', 'own', 'theirs.jsonl', 'theirs', 'memory'].map(name => existsSync(join(shared, name)))).toEqual([false, false, true, true, true])
+ expect(shares).toHaveBeenCalledTimes(1)
+ // Once only its own are left, the folder goes whole.
+ rmSync(join(shared, 'theirs.jsonl'))
+ writeFileSync(join(shared, 'again.jsonl'), JSON.stringify({ cwd: folder }))
+ await scrubClaudeSession(home, target({ sessionId: null, cwd: folder }), [], undefined, shares)
+ expect(existsSync(shared)).toBe(false)
+ expect(shares).toHaveBeenCalledTimes(1)
+ })
+
+ // Security review 2 of #2375: todos were matched by prefix, so a one-character session id removed every todo starting with it.
+ it('removes only its own session\'s todos, never one whose name only starts with its id', async () => {
+ const { home, claude } = teamHome()
+ writeFileSync(join(claude, 'todos', 'pm-session2-agent-pm-session2.json'), '[]')
+ await scrubClaudeSession(home, target())
+ expect(existsSync(join(claude, 'todos', 'pm-session-agent-pm-session.json'))).toBe(false)
+ expect(existsSync(join(claude, 'todos', 'pm-session2-agent-pm-session2.json'))).toBe(true)
+ })
+
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'])
diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.ts
index 516c0d7d8..3f25b7470 100644
--- a/cli/src/superTabs/inCore/teamPurge.ts
+++ b/cli/src/superTabs/inCore/teamPurge.ts
@@ -13,9 +13,10 @@
* 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 { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } 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'
import { PM_HOMES } from '../teamDaemon.js'
/** What a purge needs of a session, kept until it finishes. `pastes`: the paste cache files its history lines kept. */
@@ -138,14 +139,46 @@ function withoutFolder(text: string, folder: string): string {
return changed ? JSON.stringify(config, null, 2) : text
}
+/** Whether the transcript [file] records a working folder other than [folder] or one inside it: Claude Code writes the cwd
+ * on every turn, and its folder name makes every '/' and '.' a dash, so a removed worktree `<worktrees>/old/notes` shares its
+ * transcript folder with an unrelated `~/harnesses/worktrees-old/notes` (security review 2 of #2375). */
+export async function recordsOtherFolder(file: string, folder: string): Promise<boolean> {
+ const lines = createInterface({ input: createReadStream(file, 'utf8'), crlfDelay: Infinity })
+ try {
+ for await (const line of lines) {
+ if (!line.includes('"cwd"')) continue
+ let cwd: unknown
+ try { cwd = (JSON.parse(line) as { cwd?: unknown }).cwd } catch { continue }
+ if (typeof cwd === 'string' && cwd !== folder && !cwd.startsWith(`${folder}/`)) return true
+ }
+ return false
+ } finally { lines.close() }
+}
+
+/** [dir], the transcript folder Claude Code names for [folder]: whole when no transcript in it is another folder's; else only
+ * [folder]'s own transcripts, each with its folder of subagents and tool results, and [onShared] is told. */
+async function removeTranscripts(dir: string, folder: string, onShared?: () => void): Promise<void> {
+ const transcripts = (await readdir(dir).catch(() => [] as string[])).filter(name => name.endsWith('.jsonl'))
+ const others = new Set<string>()
+ for (const name of transcripts) if (await recordsOtherFolder(join(dir, name), folder)) others.add(name)
+ if (!others.size) { await rm(dir, { recursive: true, force: true }); return }
+ onShared?.()
+ for (const name of transcripts) {
+ if (others.has(name)) continue
+ await rm(join(dir, name), { force: true })
+ await rm(join(dir, name.slice(0, -'.jsonl'.length)), { recursive: true, force: true })
+ }
+}
+
/**
* 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, 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.
+ * project folder with its transcripts and memory (only its own transcripts when another folder's share it, [onShared]),
+ * 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.
*/
export async function scrubClaudeSession(home: string, target: PurgeTarget, pastes: readonly string[] = [],
- onPastes?: (pastes: string[]) => void): Promise<string[]> {
+ onPastes?: (pastes: string[]) => void, onShared?: () => void): Promise<string[]> {
const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : null
const folder = folderOf(target)
if (!sessionId && !folder) return []
@@ -173,12 +206,13 @@ export async function scrubClaudeSession(home: string, target: PurgeTarget, past
return 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 rm(join(claude, 'projects', claudeSlug(folder)), { recursive: true, force: true })
+ if (folder) await removeTranscripts(join(claude, 'projects', claudeSlug(folder)), folder, onShared)
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[])
- for (const name of todos) if (name.startsWith(sessionId)) await rm(join(claude, 'todos', name), { force: true })
+ // `<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 })
}
if (folder) {
await rewriteIfUnchanged(join(home, '.claude.json'), text => withoutFolder(text, folder))