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.

Merge batch 11-02 1102-n: #2590 #2588 #2584 (#2591)

0xken15488fd4543164
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e032c8180..f34c7af0b 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import './config/startHome.js'
import './config/loadEnv.js'
import { runDevicesCommand } from './devices/client.js'
import { fingerprint as e2eeCoreFingerprint, b64d as e2eeCoreDecode } from './lib/e2ee/core.js'
@@ -109,6 +110,24 @@ import { privacyCommand } from './lib/privacyCommand.js'
const LOG_FILE = DAEMON_LOG_FILE
+/** `harness start --help`: the start options alone (`harness --help` lists them among the rest). */
+const START_HELP = `harness start — start the Harness daemon on this computer, using the saved sign-in
+
+Usage: harness start [options]
+
+ -f, --foreground run the daemon in the FOREGROUND (for a supervisor; logs to stdout)
+ --repair also re-verify the managed Node runtime and repoint the launcher at it
+ --if-down start only if it is not running and \`harness stop\` has not stopped it
+ (what Windows's scheduled task runs; quiet otherwise)
+ --at-logon with --if-down: the sign-in task's start, first forgets a \`harness stop\`
+ --restart stop the daemon that is running for this data folder and start it over
+ (without it, a running daemon is never replaced by a start that has no
+ sign-in of its own)
+ --device-dump[=<file>] record every frame to/from the paired Autonomous device, decrypted
+ -h, --help print this and exit; nothing is started
+
+The data folder is ~/.harness/cli/data under the HOME this runs with (or ADAPTER_DATA_DIR).`
+
function usage(exitCode = 0): never {
// An agent is pointed to its own help first (agentClient/help.ts); one that asks gets it before the rest.
console.log(helpFor(process.env, `harness v${VERSION} — connect this computer to your machine
@@ -144,6 +163,9 @@ Machine:
harness start --repair also re-verify the managed Node runtime and repoint the launcher at it
(normally done once by the installer; use this if a start fails because
the launcher points at a Node that no longer runs)
+ harness start --restart stop the daemon that is running and start it over (a start with no sign-in of its own
+ never replaces a running daemon without it)
+ harness start --help the start options; starts nothing
harness start --if-down start the daemon only if it is not running and \`harness stop\` has not stopped it
since the computer started (what Windows's scheduled task runs; quiet otherwise).
--at-logon (the sign-in task's start) first forgets a \`harness stop\`
@@ -1100,7 +1122,7 @@ async function runningDaemonPid(underLock: boolean = false): Promise<number | nu
* the very value the backend binds a machine to at login) — so a later sign-in ADOPTS this machine
* rather than replacing it.
*/
-async function startCommand(foreground: boolean, repair: boolean = false, ifDown: boolean = false, atLogon: boolean = false): Promise<void> {
+async function startCommand(foreground: boolean, repair: boolean = false, ifDown: boolean = false, atLogon: boolean = false, restart: boolean = false): Promise<void> {
// The scheduled task's start (Windows, lib/startIfDown.ts): nothing to do is the usual answer, and it is quiet. The
// logon task's (`--at-logon`) forgets a `harness stop` first; the five-minute task's honours it.
if (ifDown) {
@@ -1135,9 +1157,13 @@ async function startCommand(foreground: boolean, repair: boolean = false, ifDown
// there, with `auth status` naming the new machine and the socket serving the old one. Asked
// of the daemon itself; one that cannot answer (still booting, mid-update) is trusted as before.
const serving = (await runningDaemonStatus())?.machineId
+ // `--restart` is the person asking for it: stopped whatever it serves, and started over below.
+ if (restart) {
+ console.log(`machine running (pid ${running}) — restarting it (--restart)`)
+ await stopDaemonOrExit()
// Signed out, the daemon serves this computer under its own id and there is no account to be on
// the wrong one of — `wantedDaemonIdentity` is the same answer `restartDaemonForIdentity` uses.
- if (!serving || serving === wantedDaemonIdentity()) {
+ } else if (!serving || serving === wantedDaemonIdentity()) {
// `--repair` still does its provisioning here: it touches the managed runtimes, never the
// bundle, and the live daemon picks a grid laid down now up on its next resolve (see
// repairManagedRuntimes). Without this, a new pin could only be followed by a restart.
@@ -1145,9 +1171,16 @@ async function startCommand(foreground: boolean, repair: boolean = false, ifDown
console.log(`machine already running (pid ${running}) — it auto-reconnects.`)
console.log(' check: harness status · stop: harness stop · update now: harness update')
process.exit(0)
+ } else if (!session) {
+ // Nothing on disk says this daemon is on the wrong account: this start has only its own computer id, which a
+ // run under another HOME always differs from. A daemon is never replaced on that evidence.
+ console.error(`machine already running (pid ${running}) as another account — not replacing it: this start has no sign-in of its own.`)
+ console.error(' check: harness status · replace it: harness start --restart')
+ process.exit(1)
+ } else {
+ console.log(`machine running (pid ${running}) as another account — restarting it on this sign-in`)
+ await stopDaemonOrExit()
}
- console.log(`machine running (pid ${running}) as another account — restarting it on this sign-in`)
- await stopDaemonOrExit()
}
// Windows, the task registered: it starts the master, as the task would at logon; not under the spawn lock,
// which its own `harness start --if-down` takes (lib/platformDaemon.ts startThroughTask).
@@ -2865,11 +2898,13 @@ switch (cmd) {
logout().catch(onError)
break
case 'start': {
+ // Reading the options never starts, stops or touches anything.
+ if (flags.includes('--help') || flags.includes('-h')) { console.log(START_HELP); process.exit(0) }
// `--device-dump[=<file>]`: the daemon (this process with -f, else the detached child, which inherits
// the environment) records every frame to/from a paired Autonomous device — see lib/autonomous-device/dump.ts.
const dump = flags.find((f) => f === '--device-dump' || f.startsWith('--device-dump='))
if (dump) process.env.HARNESS_DEVICE_DUMP = dump === '--device-dump' ? '1' : resolve(dump.slice('--device-dump='.length))
- startCommand(foreground, repair, flags.includes('--if-down'), flags.includes(AT_LOGON_FLAG)).catch(onError)
+ startCommand(foreground, repair, flags.includes('--if-down'), flags.includes(AT_LOGON_FLAG), flags.includes('--restart')).catch(onError)
break
}
case 'join':
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index f4ab4759b..7948a85ae 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -310,6 +310,60 @@ describe('start --repair beside a running daemon', () => {
}, ONE_RUN_TEST_MS)
})
+describe('start --help', () => {
+ it.each(['--help', '-h'])('%s prints the start options and starts, stops and writes nothing', async (flag) => {
+ const root = freshRoot()
+ seedSession(root)
+ const daemon = seedRunningDaemon(root)
+ const port = await daemonStatusServer(root, 'm_other')
+
+ const result = await runAsync(root, ['start', flag], { PORT: String(port) })
+
+ expect(result.timedOut).toBe(false)
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain('Usage: harness start')
+ expect(result.stdout).toContain('--restart')
+ expect(result.stdout).not.toContain('machine running')
+ expect(result.stdout).not.toContain('already running')
+ expect(alive(daemon.pid)).toBe(true)
+ expect(readFileSync(join(root, 'data', 'adapter.pid'), 'utf8').trim()).toBe(String(daemon.pid))
+ }, ONE_RUN_TEST_MS)
+})
+
+describe('start beside a running daemon it has no sign-in to judge by', () => {
+ // A run under another HOME has no session there: its identity is a fresh computer id, which always differs from
+ // the daemon's. That used to read as "another account" and stop the daemon.
+ it('says it runs and exits, leaving the daemon up', async () => {
+ const root = freshRoot() // signed out
+ const daemon = seedRunningDaemon(root)
+ const port = await daemonStatusServer(root, 'm_account')
+
+ const result = await runAsync(root, ['start'], { PORT: String(port) })
+
+ expect(result.status).toBe(1)
+ expect(result.stdout + result.stderr).toContain(`machine already running (pid ${daemon.pid}) as another account`)
+ expect(result.stdout + result.stderr).toContain('harness start --restart')
+ expect(alive(daemon.pid)).toBe(true)
+ expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(true)
+ }, ONE_RUN_TEST_MS)
+
+ it('--restart stops it and starts over, as asked', async () => {
+ const root = freshRoot()
+ const daemon = seedRunningDaemon(root)
+ const port = await daemonStatusServer(root, 'm_account')
+
+ const result = await runAsync(root, ['start', '--restart'], { PORT: String(port) })
+
+ // As the test above it: after the stop the start goes on to boot inline, which refuses to displace this
+ // fixture's live private socket, so no daemon comes up.
+ expect(result.timedOut).toBe(false)
+ expect(result.status).toBe(1)
+ expect(result.stdout).toContain(`machine running (pid ${daemon.pid}) — restarting it (--restart)`)
+ await daemon.exited
+ expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(false)
+ }, ONE_RUN_TEST_MS)
+})
+
describe('start beside a daemon that serves another account', () => {
// A forced login stops the daemon and waits for the browser, and a start that landed in that window
// used to bring a daemon up on the OLD session (closed under the spawn lock now — loginForceRace.spec.ts).
diff --git a/cli/src/config/startHome.ts b/cli/src/config/startHome.ts
new file mode 100644
index 000000000..04f4f867a
--- /dev/null
+++ b/cli/src/config/startHome.ts
@@ -0,0 +1,21 @@
+import { userInfo } from 'node:os'
+import { inheritedAccountDataFolder } from '../lib/homeDataFolder.js'
+
+/** The commands that start, stop or wipe a daemon or its folder: under a HOME that is not the account's they act
+ * on that HOME's data folder, never the account's. The ones an agent uses to reach its own daemon (send, new,
+ * super-tab ...) keep the variable. */
+export const HOME_FOLLOWING_COMMANDS = ['start', 'stop', 'login', 'logout', 'update', 'reset', 'uninstall', 'service', 'team', 'status', 'logs']
+
+/**
+ * A daemon command under a HOME that is not the account's gets that HOME's data folder, never the account's
+ * through an inherited ADAPTER_DATA_DIR (lib/homeDataFolder.ts). Imported first by cli.ts, before env.ts reads
+ * the variable; the daemon `start` spawns inherits the corrected environment. Said on stderr, never silent.
+ */
+if (HOME_FOLLOWING_COMMANDS.includes(process.argv[2] ?? '')) {
+ try {
+ if (inheritedAccountDataFolder(process.env, userInfo().homedir)) {
+ console.error(`harness: HOME is ${process.env.HOME}, not this account's home, so ignoring ADAPTER_DATA_DIR=${process.env.ADAPTER_DATA_DIR}; using ${process.env.HOME}/.harness/cli/data. Set ADAPTER_DATA_DIR to a folder outside ~/.harness to choose one.`)
+ delete process.env.ADAPTER_DATA_DIR
+ }
+ } catch { /* no passwd entry: nothing to compare with */ }
+}
diff --git a/cli/src/lib/homeDataFolder.spec.ts b/cli/src/lib/homeDataFolder.spec.ts
new file mode 100644
index 000000000..0d54b5db3
--- /dev/null
+++ b/cli/src/lib/homeDataFolder.spec.ts
@@ -0,0 +1,98 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { inheritedAccountDataFolder } from './homeDataFolder.js'
+
+const ACCOUNT = '/Users/real'
+const REAL_DATA = '/Users/real/.harness/cli/data'
+
+describe('an ADAPTER_DATA_DIR inherited from the account under another HOME', () => {
+ it('is recognised: the account\'s own folder while HOME is a throwaway', () => {
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: REAL_DATA }, ACCOUNT, 'darwin')).toBe(true)
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: `${REAL_DATA}/` }, ACCOUNT, 'linux')).toBe(true)
+ })
+
+ it('is left alone under the account\'s own HOME', () => {
+ expect(inheritedAccountDataFolder({ HOME: ACCOUNT, ADAPTER_DATA_DIR: REAL_DATA }, ACCOUNT, 'darwin')).toBe(false)
+ })
+
+ it('is left alone when it names a folder of its own choosing', () => {
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: '/tmp/throwaway/data' }, ACCOUNT, 'darwin')).toBe(false)
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: '/Users/real/.harnessx/data' }, ACCOUNT, 'darwin')).toBe(false)
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: '/Users/real/.harness' }, ACCOUNT, 'darwin')).toBe(false)
+ })
+
+ it('needs both a HOME and a variable, and is not decided on Windows', () => {
+ expect(inheritedAccountDataFolder({ ADAPTER_DATA_DIR: REAL_DATA }, ACCOUNT, 'darwin')).toBe(false)
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway' }, ACCOUNT, 'darwin')).toBe(false)
+ expect(inheritedAccountDataFolder({ HOME: '/tmp/throwaway', ADAPTER_DATA_DIR: REAL_DATA }, ACCOUNT, 'win32')).toBe(false)
+ })
+})
+
+describe('real locations', () => {
+ it('a HOME that links to the account home is the account home, and a deliberate folder there stays', () => {
+ const base = mkdtempSync(join(tmpdir(), 'home-data-folder-'))
+ try {
+ const account = join(base, 'account')
+ mkdirSync(join(account, '.harness', 'cli', 'data'), { recursive: true })
+ const link = join(base, 'link')
+ symlinkSync(account, link)
+ expect(inheritedAccountDataFolder({ HOME: link, ADAPTER_DATA_DIR: join(account, '.harness', 'cli', 'data') }, account, 'darwin')).toBe(false)
+ expect(inheritedAccountDataFolder({ HOME: join(base, 'other'), ADAPTER_DATA_DIR: join(link, '.harness', 'cli', 'data') }, account, 'darwin')).toBe(true)
+ } finally { rmSync(base, { recursive: true, force: true }) }
+ })
+})
+
+describe('a ~/.harness that is itself a link', () => {
+ it('is judged by where it leads: the folder it leads to is the account\'s', () => {
+ const base = mkdtempSync(join(tmpdir(), 'home-data-folder-'))
+ try {
+ const account = join(base, 'account')
+ const elsewhere = join(base, 'disk', 'harness')
+ mkdirSync(join(elsewhere, 'cli', 'data'), { recursive: true })
+ mkdirSync(account, { recursive: true })
+ symlinkSync(elsewhere, join(account, '.harness'))
+ const throwaway = { HOME: join(base, 'throwaway') }
+ expect(inheritedAccountDataFolder({ ...throwaway, ADAPTER_DATA_DIR: join(elsewhere, 'cli', 'data') }, account, 'darwin')).toBe(true)
+ expect(inheritedAccountDataFolder({ ...throwaway, ADAPTER_DATA_DIR: join(account, '.harness', 'cli', 'data') }, account, 'darwin')).toBe(true)
+ expect(inheritedAccountDataFolder({ ...throwaway, ADAPTER_DATA_DIR: join(base, 'mine') }, account, 'darwin')).toBe(false)
+ } finally { rmSync(base, { recursive: true, force: true }) }
+ })
+})
+
+describe('config/startHome', () => {
+ const saved = { argv: process.argv, data: process.env.ADAPTER_DATA_DIR, home: process.env.HOME }
+ afterEach(() => {
+ process.argv = saved.argv
+ if (saved.data === undefined) delete process.env.ADAPTER_DATA_DIR; else process.env.ADAPTER_DATA_DIR = saved.data
+ if (saved.home === undefined) delete process.env.HOME; else process.env.HOME = saved.home
+ vi.doUnmock('node:os')
+ vi.resetModules()
+ })
+
+ async function load(command: string): Promise<string | undefined> {
+ vi.resetModules()
+ vi.doMock('node:os', async (original) => ({ ...(await original<typeof import('node:os')>()), userInfo: () => ({ homedir: ACCOUNT }) }))
+ process.argv = ['node', 'cli.js', command]
+ process.env.HOME = '/tmp/throwaway'
+ process.env.ADAPTER_DATA_DIR = REAL_DATA
+ await import('../config/startHome.js')
+ return process.env.ADAPTER_DATA_DIR
+ }
+
+ it('start under a throwaway HOME drops the inherited folder, so the data folder follows HOME', async () => {
+ expect(await load('start')).toBeUndefined()
+ })
+
+ it.each(['stop', 'logout', 'update', 'reset', 'team'])('%s follows HOME too, and says it dropped the variable', async (command) => {
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {})
+ expect(await load(command)).toBeUndefined()
+ expect(said).toHaveBeenCalledWith(expect.stringContaining('ignoring ADAPTER_DATA_DIR='))
+ said.mockRestore()
+ })
+
+ it('a command an agent reaches its own daemon with keeps the variable', async () => {
+ expect(await load('super-tab')).toBe(REAL_DATA)
+ })
+})
diff --git a/cli/src/lib/homeDataFolder.ts b/cli/src/lib/homeDataFolder.ts
new file mode 100644
index 000000000..5ad45031e
--- /dev/null
+++ b/cli/src/lib/homeDataFolder.ts
@@ -0,0 +1,42 @@
+import { existsSync, realpathSync } from 'node:fs'
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
+
+/** `path` with symlinks resolved as far as it exists; the part that does not exist yet is kept as written. */
+function realOrResolved(path: string): string {
+ let existing = resolve(path)
+ const rest: string[] = []
+ while (!existsSync(existing) && dirname(existing) !== existing) {
+ rest.unshift(basename(existing))
+ existing = dirname(existing)
+ }
+ try { return join(realpathSync(existing), ...rest) } catch { return resolve(path) }
+}
+
+/**
+ * Whether an ADAPTER_DATA_DIR in the environment is the account's own Harness folder reached through a
+ * HOME that is no longer the account's.
+ *
+ * An agent's environment carries the daemon's ADAPTER_DATA_DIR. A run that points HOME at a throwaway
+ * folder to be isolated (a tester running a branch from source) still inherited that variable, so its
+ * "isolated" `harness start` read and replaced the real account's running Harness. The data folder is
+ * meant to follow HOME: a variable that names a folder inside the account's real `~/.harness` while HOME is
+ * somewhere else is that inheritance, not a choice. A folder anywhere else is a choice (a test rig, a
+ * custom install) and stays. Paths are compared by their real location, so a HOME that is a link to the
+ * account's home is the account's home, and a folder under `.harness` is not the default one's twin.
+ *
+ * `accountHome` is the account's home from the system, never from HOME.
+ */
+export function inheritedAccountDataFolder(
+ environ: { HOME?: string; ADAPTER_DATA_DIR?: string },
+ accountHome: string,
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ if (platform === 'win32') return false // homedir() follows USERPROFILE there, not HOME
+ const home = environ.HOME?.trim()
+ const dataDir = environ.ADAPTER_DATA_DIR?.trim()
+ if (!home || !dataDir || !accountHome) return false
+ const account = realOrResolved(accountHome)
+ if (realOrResolved(home) === account) return false
+ const inside = relative(realOrResolved(join(account, '.harness')), realOrResolved(dataDir))
+ return inside !== '' && !inside.startsWith('..') && !isAbsolute(inside) && !inside.startsWith(sep)
+}
diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.ts
index 10a84a118..765ce4187 100644
--- a/cli/src/superTabs/inCore/teamPurge.spec.ts
+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts
@@ -1,7 +1,7 @@
import { buddyTmpFolder, buddyTmpParent } from '../../lib/agentTmp.js'
import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
+import { dirname, join, win32 } from 'node:path'
import { PM_HOMES } from '../teamDaemon.js'
import { describe, expect, it, vi } from 'vitest'
import { createSwarmAgents } from './agents.js'
@@ -747,3 +747,130 @@ describe('the record of purges still to finish', () => {
warn.mockRestore()
})
})
+
+// Windows audit W3 (task #2096): `folderOf` wanted a leading '/', so a Windows worktree had no folder, and the sweep then held the
+// account at every retry, with its memory unread. The folder's forms are what Claude Code 2.1.316 writes on Windows: `C:/...` as a
+// config key (its `U3`), `C:\\...` elsewhere, and `C--...` as the project folder's name.
+describe('on Windows', () => {
+ const WIN = 'C:\\Users\\team\\swarm\\app\\.worktrees\\pm', KEY = WIN.replaceAll('\\', '/')
+ const WSLUG = WIN.replace(/[^A-Za-z0-9]/g, '-')
+ /** A folder sharing its name in `projects` ('.' and '\\' both become '-'), and folders that only start like it. */
+ const SHARES = 'C:\\Users\\team\\swarm\\app\\-worktrees\\pm', EVIL = `${WIN}-evil`, TWO = `${WIN}2`
+ const pm = (over: Partial<PurgeTarget> = {}): PurgeTarget => ({ agentId: 'pm', sessionId: 'pm-session', cwd: WIN, engine: 'claude', codexHome: null, ...over })
+ const row = (cwd: string) => `${JSON.stringify({ type: 'user', cwd })}\n`
+ function windowsHome() {
+ const parent = dir(), home = join(parent, 'home'), claude = join(home, '.claude')
+ for (const sub of [`projects/${WSLUG}/memory`, 'projects/C--other', 'backups', 'paste-cache']) mkdirSync(join(claude, sub), { recursive: true })
+ mkdirSync(join(home, '.codex'), { recursive: true })
+ writeFileSync(join(claude, 'history.jsonl'), [
+ JSON.stringify({ display: 'secret', pastedContents: { 1: { contentHash: 'abc123' } }, project: WIN, sessionId: 'pm-session' }),
+ JSON.stringify({ display: 'evil work', pastedContents: {}, project: EVIL, sessionId: 'evil' }),
+ JSON.stringify({ display: 'two work', pastedContents: {}, project: TWO, sessionId: 'two' }), ''].join('\n'))
+ writeFileSync(join(claude, 'paste-cache', 'abc123.txt'), 'pasted')
+ writeFileSync(join(claude, 'projects', WSLUG, 'pm-session.jsonl'), row(WIN) + row(`${WIN}\\sub`))
+ writeFileSync(join(claude, 'projects', WSLUG, 'memory', 'MEMORY.md'), 'remembered')
+ writeFileSync(join(claude, 'projects', 'C--other', 'other.jsonl'), row(EVIL))
+ const config = { projects: { [KEY]: { history: ['secret'] }, [WIN]: { history: ['old'] }, [EVIL.replaceAll('\\', '/')]: { keep: 1 }, [TWO]: { keep: 2 } },
+ githubRepoPaths: { 'example/app': [WIN, EVIL], 'example/pm': [KEY] } }
+ writeFileSync(join(home, '.claude.json'), JSON.stringify(config, null, 2))
+ writeFileSync(join(claude, 'backups', '.claude.json.backup.1'), JSON.stringify(config))
+ return { parent, home, claude }
+ }
+ const scrub = (home: string, target: PurgeTarget, told?: (what: string) => void) => scrubClaudeSession(home, target, [], undefined, told, win32)
+ const sweep = (home: string, target: PurgeTarget) => sweepForSession(home, target, [], win32)
+
+ it('scrubs the PM and only the PM, its memory too, and the sweep then finds nothing', async () => {
+ const { home, claude } = windowsHome()
+ await scrub(home, pm())
+ expect(existsSync(join(claude, 'projects', WSLUG))).toBe(false)
+ expect(existsSync(join(claude, 'paste-cache', 'abc123.txt'))).toBe(false)
+ const history = readFileSync(join(claude, 'history.jsonl'), 'utf8')
+ expect(history).not.toContain('pm-session')
+ expect(history).toContain('evil work')
+ expect(history).toContain('two work')
+ for (const file of [join(home, '.claude.json'), join(claude, 'backups', '.claude.json.backup.1')]) {
+ const config = JSON.parse(readFileSync(file, 'utf8')) as { projects: Record<string, unknown>; githubRepoPaths: Record<string, string[]> }
+ expect(Object.keys(config.projects)).toEqual([EVIL.replaceAll('\\', '/'), TWO])
+ expect(config.githubRepoPaths).toEqual({ 'example/app': [EVIL] })
+ }
+ expect(existsSync(join(claude, 'projects', 'C--other', 'other.jsonl'))).toBe(true)
+ expect(await sweep(home, pm())).toBeNull()
+ })
+
+ it.each([['forward slashes', KEY], ['both separators', 'C:\\Users\\team/swarm\\app/.worktrees\\pm'], ['a lower-case drive', `c${WIN.slice(1)}`],
+ ['a trailing separator', `${WIN}\\`]])('finds the same folder written with %s', async (_, cwd) => {
+ const { home, claude } = windowsHome()
+ await scrub(home, pm({ cwd }))
+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).not.toContain('pm-session')
+ expect(Object.keys((JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8')) as { projects: object }).projects)).toEqual([EVIL.replaceAll('\\', '/'), TWO])
+ expect(existsSync(join(claude, 'projects', WSLUG))).toBe(false)
+ expect(await sweep(home, pm({ cwd }))).toBeNull()
+ })
+
+ it.each(['C:\\', 'C:/', 'C:', '\\', '/', 'C:foo', 'foo\\bar', '\\\\server', '\\\\server\\', '\\\\server\\share', '\\\\server\\share\\', 'C:\\a\\..', '/Users/team/pm', '\\Users\\team', ''])(
+ 'takes no folder from %j: with no session either, nothing is touched', async (cwd) => {
+ const { home, claude } = windowsHome()
+ // A line that does name it, to show it stays: a form with no drive could be any drive's folder.
+ appendFileSync(join(claude, 'history.jsonl'), `${JSON.stringify({ display: 'named', pastedContents: {}, project: cwd, sessionId: 'named' })}\n`)
+ const before = readFileSync(join(claude, 'history.jsonl'), 'utf8'), config = readFileSync(join(home, '.claude.json'), 'utf8')
+ expect(await scrub(home, pm({ cwd, sessionId: null }))).toEqual([])
+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toBe(before)
+ expect(readFileSync(join(home, '.claude.json'), 'utf8')).toBe(config)
+ expect(existsSync(join(claude, 'projects', WSLUG))).toBe(true)
+ expect(await sweep(home, pm({ cwd, sessionId: null }))).toBeNull()
+ })
+
+ it('reads a transcript in a folder only as inside it past a separator, in any case', async () => {
+ const { home } = windowsHome()
+ const file = join(home, 't.jsonl')
+ for (const [cwd, other] of [[WIN, false], [`${WIN}\\sub`, false], [`${KEY}/sub`, false], [WIN.toUpperCase(), false], [EVIL, true], [TWO, true], [SHARES, true]] as const) {
+ writeFileSync(file, row(cwd))
+ expect(await recordsOtherFolder(file, WIN, win32)).toBe(other)
+ }
+ })
+
+ it('the sweep sees a folder as JSON holds it, by either separator, and not one that only starts like it', async () => {
+ for (const [text, left] of [[`{"project":${JSON.stringify(WIN)},"sessionId":"x"}\n`, SWEEP_LEFT.claudeHistory], [`{"project":${JSON.stringify(KEY)}}\n`, SWEEP_LEFT.claudeHistory],
+ [`{"project":${JSON.stringify(`${WIN}\\sub`)}}\n`, SWEEP_LEFT.claudeHistory], [`{"project":${JSON.stringify(EVIL)}}\n`, null], [`{"project":${JSON.stringify(TWO)}}\n`, null]] as const) {
+ const home = dir()
+ mkdirSync(join(home, '.claude'), { recursive: true })
+ writeFileSync(join(home, '.claude', 'history.jsonl'), text)
+ expect(await sweep(home, pm({ sessionId: null }))).toBe(left)
+ }
+ for (const key of [KEY, WIN]) {
+ const home = dir()
+ mkdirSync(join(home, '.claude'), { recursive: true })
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: { [key]: {} } }, null, 2))
+ expect(await sweep(home, pm({ sessionId: null }))).toBe(SWEEP_LEFT.config)
+ }
+ })
+
+ it('keeps another folder\'s transcript that shares the name, says so, and the memory left holds the account', async () => {
+ const { home, claude } = windowsHome()
+ writeFileSync(join(claude, 'projects', WSLUG, 'shared.jsonl'), row(SHARES))
+ const told: string[] = []
+ await scrub(home, pm(), what => told.push(what))
+ expect(told).toEqual(['shared'])
+ expect(existsSync(join(claude, 'projects', WSLUG, 'shared.jsonl'))).toBe(true)
+ expect(existsSync(join(claude, 'projects', WSLUG, 'pm-session.jsonl'))).toBe(false)
+ expect(await sweep(home, pm())).toBe(SHARED_LEFT.memory)
+ rmSync(join(claude, 'projects', WSLUG, 'memory'), { recursive: true })
+ expect(await sweep(home, pm())).toBeNull()
+ })
+
+ it('finishes the whole purge, and frees the account, touching nothing outside the home', async () => {
+ const { parent, home, claude } = windowsHome()
+ const outside = join(parent, '.claude', 'projects', WSLUG, 'pm-session.jsonl')
+ mkdirSync(join(parent, '.claude', 'projects', WSLUG), { recursive: true })
+ writeFileSync(outside, 'someone else\'s')
+ writeFileSync(join(parent, '.claude.json'), JSON.stringify({ projects: { [KEY]: {} } }))
+ const record = purgeRecord(join(parent, 'purges.json'))
+ const purge = createConfidentialPurge({ confidential: () => true, home, record, paths: win32,
+ session: () => ({ agentId: 'pm', sessionId: 'pm-session', registeredAt: 1, engine: 'claude', cwd: WIN }),
+ purge: async request => request.mode === 'inspect' ? { reviewId: 'review' } : { ok: true } })
+ expect(await purge('pm')).toEqual({ ok: true })
+ expect(existsSync(join(claude, 'projects', WSLUG))).toBe(false)
+ expect(readFileSync(outside, 'utf8')).toBe('someone else\'s')
+ expect(readFileSync(join(parent, '.claude.json'), 'utf8')).toContain(KEY)
+ })
+})
diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.ts
index d85f4c501..add532915 100644
--- a/cli/src/superTabs/inCore/teamPurge.ts
+++ b/cli/src/superTabs/inCore/teamPurge.ts
@@ -16,7 +16,7 @@
import { buddyTmpFolder, realOfFolder } from '../../lib/agentTmp.js'
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 nodePath, { basename, dirname, join, type PlatformPath } from 'node:path'
import { createInterface } from 'node:readline'
import { PM_HOMES } from '../teamDaemon.js'
@@ -102,8 +102,30 @@ const listed = (dir: string) => readdir(dir).catch((error: NodeJS.ErrnoException
/** 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}$/
-/** Its folder, when it names one that is no root: an empty or root key would match every other session's. */
-const folderOf = (target: PurgeTarget) => target.cwd && target.cwd.startsWith('/') && target.cwd.length > 1 ? target.cwd : null
+/** What purge asks of a platform's paths: the host's, or `path.win32` in a test. */
+type FolderPaths = Pick<PlatformPath, 'isAbsolute' | 'normalize' | 'parse' | 'sep'>
+const onWindows = (paths: FolderPaths) => paths.sep === '\\'
+/** [path] as it compares. On Windows any separator names the same folder, in any case, as Claude Code compares them there. Its
+ * forms differ too: a config key has `/` (2.1.316's `U3`), history and transcripts `\` (Windows audit W3). */
+const folderKey = (path: string, paths: FolderPaths) =>
+ onWindows(paths) ? paths.normalize(path).replaceAll('\\', '/').replace(/\/+$/, '').toLowerCase() : path
+/** Whether [cwd], as its key, is [key] or inside it: past a separator, so `C:\a\b-evil` is not inside `C:\a\b`. */
+const inFolder = (cwd: string, key: string, paths: FolderPaths) => {
+ const candidate = folderKey(cwd, paths)
+ return candidate === key || candidate.startsWith(`${key}/`)
+}
+/** [text] of a file, as folder keys read in it: JSON doubles a `\`. */
+const foldedText = (text: string, paths: FolderPaths) =>
+ onWindows(paths) ? text.replaceAll('\\\\', '/').replaceAll('\\', '/').toLowerCase() : text
+/** Its folder, when it names one that is no root: an empty or root key would match every other session's. On Windows a folder
+ * has a drive or a share: `\Users` and `/Users` are relative to whichever drive is current, so which folder they name is not known. */
+function folderOf(target: PurgeTarget, paths: FolderPaths): string | null {
+ const cwd = target.cwd
+ if (!cwd || !paths.isAbsolute(cwd) || (onWindows(paths) && !/^([A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(cwd))) return null
+ const bare = (path: string) => path.replace(/[\\/]+$/, '')
+ const normal = paths.normalize(cwd)
+ return bare(normal) === bare(paths.parse(normal).root) ? null : cwd
+}
/**
* Rewrites [path] through [transform], unless it changed while being rewritten: another agent of the account may write the
@@ -132,15 +154,17 @@ export async function rewriteIfUnchanged(path: string, transform: (text: string)
}
/** [config] (Claude Code's `.claude.json`, or a backup of it) without [folder]: its project entry and its repository paths. */
-function withoutFolder(text: string, folder: string): string {
+function withoutFolder(text: string, folder: string, paths: FolderPaths): string {
let config: { projects?: Record<string, unknown>; githubRepoPaths?: Record<string, unknown> }
try { config = JSON.parse(text) } catch { return text }
if (!config || typeof config !== 'object') return text
let changed = false
- if (config.projects && folder in config.projects) { delete config.projects[folder]; changed = true }
- for (const [repository, paths] of Object.entries(config.githubRepoPaths ?? {})) {
- if (!Array.isArray(paths) || !paths.includes(folder)) continue
- const kept = paths.filter(path => path !== folder)
+ const key = folderKey(folder, paths)
+ const same = (path: unknown) => typeof path === 'string' && folderKey(path, paths) === key
+ for (const name of Object.keys(config.projects ?? {})) if (same(name)) { delete config.projects![name]; changed = true }
+ for (const [repository, listed] of Object.entries(config.githubRepoPaths ?? {})) {
+ if (!Array.isArray(listed) || !listed.some(same)) continue
+ const kept = listed.filter(path => !same(path))
if (kept.length) config.githubRepoPaths![repository] = kept
else delete config.githubRepoPaths![repository]
changed = true
@@ -151,14 +175,15 @@ function withoutFolder(text: string, folder: string): string {
/** 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> {
+export async function recordsOtherFolder(file: string, folder: string, paths: FolderPaths = nodePath): Promise<boolean> {
+ const key = folderKey(folder, paths)
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
+ if (typeof cwd === 'string' && !inFolder(cwd, key, paths)) return true
}
return false
} finally { lines.close() }
@@ -166,15 +191,15 @@ export async function recordsOtherFolder(file: string, folder: string): Promise<
/** 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 }
+async function foldersOf(file: string, folder: string, paths: FolderPaths): Promise<{ own: boolean; other: boolean; unread?: true }> {
+ const found = { own: false, other: false }, key = folderKey(folder, paths)
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 } | null)?.cwd } catch { continue }
- if (typeof cwd === 'string') found[cwd === folder || cwd.startsWith(`${folder}/`) ? 'own' : 'other'] = true
+ if (typeof cwd === 'string') found[inFolder(cwd, key, paths) ? 'own' : 'other'] = true
}
} catch { return { own: false, other: false, unread: true } } finally { lines.close() }
return found
@@ -187,7 +212,7 @@ 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, told?: (what: ScrubTold) => void): Promise<void> {
+async function removeTranscripts(dir: string, folder: string, paths: FolderPaths, 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;
@@ -196,7 +221,7 @@ async function removeTranscripts(dir: string, folder: string, told?: (what: Scru
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))
+ transcripts.set(name, await foldersOf(join(dir, name), folder, paths))
}
// 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()]
@@ -214,14 +239,14 @@ async function removeTranscripts(dir: string, folder: string, told?: (what: Scru
* would name another folder's file (security review 1 of #2385). Null when it holds only transcripts that record other
* 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> {
+async function leftInSharedFolder(dir: string, folder: string, paths: FolderPaths): Promise<string | null> {
// 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))
+ for (const entry of entries.filter(entry => entry.isFile() && entry.name.endsWith('.jsonl'))) read.set(entry.name, await foldersOf(join(dir, entry.name), folder, paths))
// 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_LEFT
const transcripts = new Set<string>()
@@ -277,6 +302,18 @@ export const SWEEP_LEFT = {
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')}`,
}
+/** The names in [projects] Claude Code uses for [folder]. On Windows that is by any case, as `c:\a` and `C:\a` are one folder there
+ * and their names differ only by it. Elsewhere it is the one name, listed or not, for the caller to find what is there. */
+async function transcriptFolders(projects: string, folder: string, paths: FolderPaths): Promise<string[]> {
+ const slug = claudeSlug(folderOnDisk(folder, paths))
+ if (!onWindows(paths)) return [slug]
+ const names = await listed(projects)
+ // A listing that failed names only what the slug says: the removal reports it, unread, by its kind.
+ return names ? names.filter(name => name.toLowerCase() === slug.toLowerCase()) : [slug]
+}
+/** [folder] as Claude Code names its project folder from it, by its working folder: no `..` and no trailing separator. */
+const folderOnDisk = (folder: string, paths: FolderPaths) => onWindows(paths) ? paths.normalize(folder).replace(/[\\/]+$/, '') : folder
+
/**
* 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
@@ -288,9 +325,10 @@ export const SWEEP_LEFT = {
* history named, for the record.
*/
export async function scrubClaudeSession(home: string, target: PurgeTarget, pastes: readonly string[] = [],
- onPastes?: (pastes: string[]) => void, told?: (what: ScrubTold) => void): Promise<string[]> {
+ onPastes?: (pastes: string[]) => void, told?: (what: ScrubTold) => void, paths: FolderPaths = nodePath): Promise<string[]> {
const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : null
- const folder = folderOf(target)
+ const folder = folderOf(target, paths)
+ const key = folder && folderKey(folder, paths)
if (!sessionId && !folder) return []
const claude = join(home, '.claude'), history = join(claude, 'history.jsonl')
/** Its history's lines kept, and the pastes its own lines named. */
@@ -299,8 +337,8 @@ export async function scrubClaudeSession(home: string, target: PurgeTarget, past
const kept = text.split('\n').filter(line => {
if (!line.trim()) return false
let row: { sessionId?: unknown; project?: unknown; pastedContents?: Record<string, { contentHash?: unknown } | null> }
- try { row = JSON.parse(line) } catch { return !(sessionId && line.includes(sessionId)) && !(folder && line.includes(folder)) }
- const ours = (!!sessionId && row.sessionId === sessionId) || (!!folder && row.project === folder)
+ try { row = JSON.parse(line) } catch { return !(sessionId && line.includes(sessionId)) && !(key && foldedText(line, paths).includes(key)) }
+ const ours = (!!sessionId && row.sessionId === sessionId) || (!!key && typeof row.project === 'string' && folderKey(row.project, paths) === key)
if (ours) for (const paste of Object.values(row.pastedContents ?? {})) if (typeof paste?.contentHash === 'string' && SESSION.test(paste.contentHash)) named.push(paste.contentHash)
return !ours
})
@@ -316,7 +354,7 @@ 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 removeTranscripts(join(claude, 'projects', claudeSlug(folder)), folder, told)
+ if (folder) for (const name of await transcriptFolders(join(claude, 'projects'), folder, paths)) await removeTranscripts(join(claude, 'projects', name), folder, paths, told)
// Its private temporary folder beside a Team account: command output from its person's private work (lib/agentTmp.ts). A plain
// session shares its Buddy's folder, and this one's TMPDIR with it, so the whole folder goes only once that folder has; the
// sweep takes what a tool left meanwhile (review of #2563).
@@ -334,10 +372,10 @@ export async function scrubClaudeSession(home: string, target: PurgeTarget, past
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))
+ await rewriteIfUnchanged(join(home, '.claude.json'), text => withoutFolder(text, folder, paths))
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))
+ for (const name of backups ?? []) await rewriteIfUnchanged(join(claude, 'backups', name), text => withoutFolder(text, folder, paths))
}
return [...new Set(found)]
}
@@ -349,12 +387,12 @@ export async function scrubClaudeSession(home: string, target: PurgeTarget, past
* transcripts: another agent that read the Product Manager's status names both there, and is not its to delete. Its transcript
* folder, when another folder's transcripts share it, only by the working folders they record.
*/
-export async function sweepForSession(home: string, target: PurgeTarget, pastes: readonly string[]): Promise<string | null> {
+export async function sweepForSession(home: string, target: PurgeTarget, pastes: readonly string[], paths: FolderPaths = nodePath): Promise<string | null> {
const sessionId = target.sessionId && SESSION.test(target.sessionId) ? target.sessionId : null
- const folder = folderOf(target)
+ const folder = folderOf(target, paths), key = folder && folderKey(folder, paths)
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))
+ const names = (text: string) => (!!sessionId && text.includes(`"${sessionId}"`))
+ || (!!key && [`"${key}"`, `"${key}/`].some(quoted => foldedText(text, paths).includes(quoted)))
// 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'
@@ -371,20 +409,21 @@ export async function sweepForSession(home: string, target: PurgeTarget, pastes:
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
+ if (foldedText(text, paths).includes(`"${key}"`)) return SWEEP_LEFT.config
}
}
- const slug = folder ? claudeSlug(folder) : null, projects = join(claude, 'projects')
+ const slug = folder ? claudeSlug(folderOnDisk(folder, paths)) : null, projects = join(claude, 'projects')
+ const isSlug = (name: string) => slug !== null && (onWindows(paths) ? name.toLowerCase() === slug.toLowerCase() : name === slug)
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 named
- if (entry.name === slug) {
+ if (isSlug(entry.name)) {
// 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!) : named
+ const left = path === projects && entry.isDirectory() ? await leftInSharedFolder(child, folder!, paths) : named
if (left) return left
}
if (entry.isDirectory()) { const found = await walk(child, named); if (found) return found }
@@ -420,6 +459,8 @@ export function createConfidentialPurge(deps: {
/** The Team user's home. */
home: string
record: PurgeRecord
+ /** The platform's paths; a test's `path.win32`. */
+ paths?: FolderPaths
}): (agentId: string) => Promise<Record<string, unknown>> {
return async agentId => {
// With its record unreadable, which purges are still to finish is not known: none is answered, not even a 'skipped' for a
@@ -453,9 +494,9 @@ export function createConfidentialPurge(deps: {
const pastes = [...new Set([...target!.pastes ?? [], ...found])]
if (pastes.length !== (target!.pastes ?? []).length) { target = { ...target!, pastes }; deps.record.put(target) }
}
- keep(await scrubClaudeSession(deps.home, target, target.pastes, keep))
+ keep(await scrubClaudeSession(deps.home, target, target.pastes, keep, undefined, deps.paths))
}
- const left = await sweepForSession(deps.home, target, target.pastes ?? [])
+ const left = await sweepForSession(deps.home, target, target.pastes ?? [], deps.paths)
if (left) return { error: 'SCRUB_INCOMPLETE', detail: `Something still names the session: ${left}` }
deps.record.drop(agentId)
return { ok: true }
diff --git a/docs/plans/2026-11-02-purge-claude-pm-windows-paths-plan.md b/docs/plans/2026-11-02-purge-claude-pm-windows-paths-plan.md
new file mode 100644
index 000000000..26fd12366
--- /dev/null
+++ b/docs/plans/2026-11-02-purge-claude-pm-windows-paths-plan.md
@@ -0,0 +1,78 @@
+# Purge a Claude Code PM on Windows Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** On Windows, purge scrubs a Claude Code Product Manager's traces from the Team home, and touches nothing outside its own folder and session.
+
+**Architecture:** `folderOf` in `teamPurge.ts` wants a path starting with `/`, so on Windows the scrub has no folder and the sweep holds the account for good. One platform-aware folder rule replaces it, used by the scrub and the sweep alike, with `path.win32` injectable as in #2568's `isPmCodexHome`.
+
+**Tech Stack:** TypeScript, Node `path`, Vitest with real files in throwaway folders.
+
+**Spec:** Windows audit W3, `docs/security/2026-11-02-team-account-windows.md` on PR #2568 (task #2022).
+
+## Global Constraints
+
+- PR body starts with: Requested by [email protected] through Harness.
+- Two security reviews (it deletes data): Quinn 2 and Reed.
+- Swarm code stays out of `cli/src/core`.
+- It fails closed: what can't be named or read holds the account, and no message names a path.
+- macOS and Linux behaviour does not change, beyond refusing more forms of a root.
+
+## What Claude Code writes (2.1.316, read from its own bundle)
+
+- Config keys (`.claude.json` `projects`): function `U3` replaces `\` with `/` on Windows, so `C:/Users/...`. Older records and the #1647 spec have `C:\Users\...`, so both are matched.
+- `githubRepoPaths`, history `project` and transcript `cwd`: the native form, `C:\Users\...`, JSON-escaped on disk.
+- Project folder name: every non-alphanumeric character becomes `-`, so `C--Users-...`, and names over 200 characters get a hash suffix (`EL`). The suffix is existing behaviour on every platform and is out of scope.
+- Claude Code itself compares Windows paths with `\` as `/` and lowercased (`dYe`).
+
+## Review Focus
+
+- A drive root, `C:`, `\`, a UNC share root or `C:\a\..` as the folder: no folder, so nothing is matched by folder.
+- `C:\a\b` must not match `C:\a\b-evil` or `C:\a\b2`, in any list, in any case.
+- A sweep over JSON text: `C:\\a\\b` on disk must be seen, or a purge reports clean with traces left.
+- Another folder sharing the slug (`C:\a\.b` and `C:\a-b`): its transcripts stay and the memory folder holds the account.
+- A POSIX path handed to the Windows rules, and a Windows path to the POSIX ones: refused, not guessed.
+
+---
+
+### Task 1: One folder rule for scrub and sweep
+
+**Files:**
+- Modify: `cli/src/superTabs/inCore/teamPurge.ts`
+- Test: `cli/src/superTabs/inCore/teamPurge.spec.ts`
+
+**Interfaces:**
+- Produces: `FolderPaths = Pick<PlatformPath, 'isAbsolute' | 'normalize' | 'parse' | 'sep'>`, a last optional `paths` argument on `scrubClaudeSession`, `sweepForSession` and `recordsOtherFolder`, and `paths?` on `createConfidentialPurge`'s deps. All default to the host's `node:path`.
+
+- [ ] **Step 1: Write the failing tests** in a `describe('on Windows')` with `path.win32`, a home holding `C:\Users\team\swarm\app\.worktrees\pm`: `scrubs the PM and only the PM, its memory too`; `it.each` of `C:/...`, mixed separators, `c:\...` and a trailing separator; `refuses a root` for each Review Focus form; `keeps what only looks like its folder`; `the sweep sees JSON-escaped and forward-slash forms`; `a shared slug keeps the other folder's transcript and holds the account`; `the whole purge answers ok` through `createConfidentialPurge`; `nothing outside the home is touched`.
+
+- [ ] **Step 2: Run to verify they fail**
+
+Run: `npx vitest run src/superTabs/inCore/teamPurge.spec.ts`
+Expected: FAIL, with the Windows purge answering `SCRUB_INCOMPLETE`.
+
+- [ ] **Step 3: Implement** `folderOf(target, paths)` and `folderKey(path, paths)`. On Windows the key is the normalized path with `/`, no trailing separator, lowercased; on POSIX it is the path as given. `foldersOf`, `recordsOtherFolder`, `withoutFolder`, the history filter and the sweep compare by key; the sweep folds the text it reads the same way.
+
+- [ ] **Step 4: Run to verify they pass**
+
+Run: `npx vitest run src/superTabs/inCore/teamPurge.spec.ts && npx tsc --noEmit -p .`
+Expected: PASS, and no type errors.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add cli/src/superTabs/inCore/teamPurge.ts cli/src/superTabs/inCore/teamPurge.spec.ts
+git commit -m "Team purge: a Claude Code PM's folder by the platform's own path rules"
+```
+
+## Design
+
+- **Growth:** nothing new is stored.
+- **Concurrency:** unchanged; `rewriteIfUnchanged` still guards each rewrite.
+- **Read cost:** unchanged, plus one text fold per file on Windows only.
+- **Scale:** N/A because this runs once per purged session.
+- **Compatibility:** no wire or record change. A held Windows account's record finishes on its next retry.
+- **Migration and rollback:** none. A rollback holds such an account again.
+- **Audience, identity:** N/A because no reader or login changes.
+- **Failure:** a refused folder leaves only session-id matching, and the sweep still holds the account while anything names the session.
+- **Platforms:** the rule is chosen by `path`. A real Windows home could not be checked from here unless a Windows machine is free; the PR says so.
diff --git a/store/tools/local-credential.test.mjs b/store/tools/local-credential.test.mjs
index 1bfda29e6..bbdcfd7a2 100644
--- a/store/tools/local-credential.test.mjs
+++ b/store/tools/local-credential.test.mjs
@@ -1,17 +1,20 @@
// node --test store/tools/local-credential.test.mjs
import assert from 'node:assert/strict'
-import { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createServer } from 'node:net'
-import { test } from 'node:test'
+import { after, test } from 'node:test'
import { daemonBridge, localCredentialHeaders } from './local-credential.mjs'
+import { removeTempFolders, tempFolder } from './test-folders.mjs'
+
+after(removeTempFolders)
const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}` // the CLI's shape: 43 base64url characters
/** A data folder as the CLI leaves it: 0700, holding a 0600 `hook-credential` (or none). */
function dataDir({ credential = CREDENTIAL, mode = 0o600, folderMode = 0o700 } = {}) {
- const dir = join(mkdtempSync(join(tmpdir(), 'store-tools-credential-')), 'data-'.padEnd(120, 'x'))
+ const dir = join(tempFolder('store-tools-credential-'), 'data-'.padEnd(120, 'x'))
mkdirSync(dir, { mode: 0o700 })
if (credential !== null) { writeFileSync(join(dir, 'hook-credential'), `${credential}\n`, { mode: 0o600 }); chmodSync(join(dir, 'hook-credential'), mode) }
chmodSync(dir, folderMode)
@@ -38,7 +41,7 @@ test('on Windows the credential is read whatever mode the folder and file report
})
test('where a socket can be, a check opens it and shows nothing, and only if it is private', async (t) => {
- const short = mkdtempSync(join('/tmp', 'tools-'))
+ const short = tempFolder('tools-')
writeFileSync(join(short, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })
chmodSync(short, 0o700)
const env = { ADAPTER_DATA_DIR: short }, path = join(short, 'daemon-18473.sock')
diff --git a/store/tools/local-daemon.test.mjs b/store/tools/local-daemon.test.mjs
index 2a85b1649..fd6e03883 100644
--- a/store/tools/local-daemon.test.mjs
+++ b/store/tools/local-daemon.test.mjs
@@ -2,19 +2,20 @@
// The small WebSocket and fetch every Store package reaches the daemon with, against raw frames on a real Unix socket.
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
-import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { chmodSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { join } from 'node:path'
import { after, test } from 'node:test'
import { DaemonWebSocket, daemonFetch, daemonSocketPath, socketIsPrivate } from './local-daemon.mjs'
+import { removeTempFolders, tempFolder } from './test-folders.mjs'
const closers = []
-after(async () => { for (const close of closers) await close() })
+after(async () => { try { for (const close of closers) await close() } finally { removeTempFolders() } })
const PORT = 4242
/** A daemon on a private socket: `upgrade(socket, unmaskedFramesSeen)`, and `rest` for plain requests. */
async function daemon({ upgrade, rest, accept } = {}) {
- const dir = mkdtempSync(join('/tmp', 'ld-'))
+ const dir = tempFolder('ld-')
chmodSync(dir, 0o700)
const sockets = new Set(), seen = []
const server = createServer(rest ?? ((_req, res) => res.writeHead(404).end()))
@@ -107,7 +108,7 @@ test('a frame past the limit closes without being held', async () => {
})
test('no socket, one anyone can reach, a wrong accept and a refusal are each an error, then a close', async () => {
- const dir = mkdtempSync(join('/tmp', 'ld-')); chmodSync(dir, 0o700)
+ const dir = tempFolder('ld-'); chmodSync(dir, 0o700)
for (const socket of [open({ ADAPTER_DATA_DIR: dir })]) { const failed = once(socket, 'error'); await once(socket, 'close'); await failed }
const open_ = await daemon(); chmodSync(open_.path, 0o666)
assert.equal(socketIsPrivate(open_.path), false)
@@ -134,7 +135,7 @@ test('close() gives up on a daemon that never answers it', async () => {
})
test('a connection the caller gave up on stays given up: no open, nothing sent, and the daemon sees it go', async () => {
- const dir = mkdtempSync(join('/tmp', 'ld-')); chmodSync(dir, 0o700)
+ const dir = tempFolder('ld-'); chmodSync(dir, 0o700)
const events = [], path = join(dir, `daemon-${PORT}.sock`)
const server = createServer()
const gone = new Promise(resolve => server.on('upgrade', (req, stream) => {
@@ -178,7 +179,7 @@ test('fetch: a request and its body over the socket; the timeout reads as a time
assert.equal(answer.ok, true)
assert.deepEqual(await answer.json(), { method: 'POST', url: '/api/x?y=1', raw: '{"a":1}', local: '1' })
await assert.rejects(daemonFetch(`${base}/slow`, { env: d.env, signal: AbortSignal.timeout(30) }), { name: 'TimeoutError' })
- const dir = mkdtempSync(join('/tmp', 'ld-')); chmodSync(dir, 0o700)
+ const dir = tempFolder('ld-'); chmodSync(dir, 0o700)
await assert.rejects(daemonFetch(`${base}/api/x`, { env: { ADAPTER_DATA_DIR: dir } }), /not private/)
})
diff --git a/store/tools/port-holder.test.mjs b/store/tools/port-holder.test.mjs
index 4f0f8bffa..8013fe343 100644
--- a/store/tools/port-holder.test.mjs
+++ b/store/tools/port-holder.test.mjs
@@ -2,23 +2,23 @@
// Whoever holds the daemon's loopback port hears nothing from a Store package (audit H1), and each still works over the socket.
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
-import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { after, test } from 'node:test'
import { closeBridges, listAgents as monitorAgents } from '../agents/harness-monitor/lib/bridge.mjs'
import { closeBridges as closeMemories, listAgents as memoriesAgents } from '../agents/memories/lib/bridge.mjs'
import { closeSessions, listHarnesses, listMachines } from '../agents/machine-monitor/lib/daemon.mjs'
import { harnessExecute } from '../agents/autonomous-grid/lib/harness.mjs'
+import { removeTempFolders, tempFolder } from './test-folders.mjs'
const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}`
const closers = []
-after(async () => { closeBridges(); closeMemories(); closeSessions(); for (const close of closers) await close() })
+after(async () => { try { closeBridges(); closeMemories(); closeSessions(); for (const close of closers) await close() } finally { removeTempFolders() } })
/** A data folder as the CLI leaves it, short enough to hold a socket, with a real credential a client could read. */
function dataDir() {
- const dir = join(mkdtempSync(join('/tmp', 'hold-')), 'd')
+ const dir = join(tempFolder('hold-'), 'd')
mkdirSync(dir, { mode: 0o700 })
writeFileSync(join(dir, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })
chmodSync(join(dir, 'hook-credential'), 0o600)
diff --git a/store/tools/test-folders.mjs b/store/tools/test-folders.mjs
new file mode 100644
index 000000000..5430e2031
--- /dev/null
+++ b/store/tools/test-folders.mjs
@@ -0,0 +1,22 @@
+// The temporary folders of these specs: under the OS temp folder, and gone when a spec file ends, passed or failed.
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+/** A socket's path has 96 bytes (local-daemon.mjs), and these specs put up to 32 under the root: an agent's long TMPDIR would not fit. */
+const MAX_ROOT_BYTES = 60
+
+const made = new Set()
+
+/** A new folder for this spec file, under [root], removed by [removeTempFolders]. */
+export function tempFolder(prefix, root = Buffer.byteLength(tmpdir()) <= MAX_ROOT_BYTES ? tmpdir() : '/tmp') {
+ const dir = mkdtempSync(join(root, prefix))
+ made.add(dir)
+ return dir
+}
+
+/** Removes every folder [tempFolder] made: call it from the spec file's `after`, once what listens in them has closed. */
+export function removeTempFolders() {
+ for (const dir of made) rmSync(dir, { recursive: true, force: true })
+ made.clear()
+}
diff --git a/store/tools/test-folders.test.mjs b/store/tools/test-folders.test.mjs
new file mode 100644
index 000000000..a9073691f
--- /dev/null
+++ b/store/tools/test-folders.test.mjs
@@ -0,0 +1,60 @@
+// node --test store/tools/test-folders.test.mjs
+// The socket specs leave nothing in the temp folder, which builds up on a shared Mac.
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { after, test } from 'node:test'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { removeTempFolders, tempFolder } from './test-folders.mjs'
+
+after(removeTempFolders)
+const here = (name) => fileURLToPath(new URL(name, import.meta.url))
+
+/** `node --test` on [files] with its own empty temp folder: its exit status, and what it left there. Under /tmp whatever
+ * TMPDIR says: one past the helper's limit would send the specs to /tmp, and this would look in an empty folder. */
+function run(files) {
+ const temp = tempFolder('tf-', '/tmp')
+ const { NODE_TEST_CONTEXT: _nested, ...env } = process.env
+ const { status } = spawnSync(process.execPath, ['--test', ...files], { env: { ...env, TMPDIR: temp }, stdio: 'ignore' })
+ return { status, left: readdirSync(temp) }
+}
+
+const specs = ['local-daemon.test.mjs', 'port-holder.test.mjs', 'local-credential.test.mjs'].map(here)
+
+test('the socket specs leave nothing behind, run after run', () => {
+ for (let i = 0; i < 2; i++) assert.deepEqual(run(specs), { status: 0, left: [] })
+})
+
+test('the socket specs make their folders only through tempFolder, which the run above can see', () => {
+ for (const spec of specs) assert.doesNotMatch(readFileSync(spec, 'utf8'), /mkdtemp|'\/tmp'/, spec)
+})
+
+test('a folder a spec leaves is seen, however long this run\'s own temp folder is', (t) => {
+ const spec = join(tempFolder('tf-spec-'), 'leaves.test.mjs')
+ writeFileSync(spec, `import { test } from 'node:test'
+import { tempFolder } from ${JSON.stringify(pathToFileURL(here('test-folders.mjs')).href)}
+test('leaves its folder', () => { tempFolder('left-') })
+`)
+ const before = process.env.TMPDIR
+ t.after(() => { if (before === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = before })
+ const base = tempFolder('tf-long-', '/tmp')
+ for (const size of [52, 55, 60, 100]) {
+ const long = join(base, 'x'.repeat(size - base.length - 1))
+ mkdirSync(long)
+ process.env.TMPDIR = long
+ const { left } = run([spec])
+ assert.equal(left.length, 1, `a ${size}-byte temp folder`)
+ assert.match(left[0], /^left-/)
+ }
+})
+
+test('a spec that fails leaves nothing behind either', () => {
+ const failing = join(tempFolder('tf-spec-'), 'failing.test.mjs')
+ writeFileSync(failing, `import { after, test } from 'node:test'
+import { removeTempFolders, tempFolder } from ${JSON.stringify(pathToFileURL(here('test-folders.mjs')).href)}
+after(removeTempFolders)
+test('fails with its folder made', () => { tempFolder('x-'); throw new Error('on purpose') })
+`)
+ assert.deepEqual(run([failing]), { status: 1, left: [] })
+})