The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-03 bh: #2680 (#2685)
0xken15b4147f10221f
diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 4607c94b4..7d767ec8b 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1455,9 +1455,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {const purges = swarm.purgeRecord(join(env.ADAPTER_DATA_DIR, 'super-tabs', 'team-purges.json'))const policy = swarm.teamAppPolicyFor(env.ADAPTER_DATA_DIR, () => coreApi.daemon.machineId(), () => registry.list(), () => stoppedAgents.list(), purges)backend.remoteAppPolicy = policy- teamPurge = swarm.createConfidentialPurge({ confidential: (agentId) => policy.isConfidential(agentId), home: homedir(), record: purges,+ // What it doesn't finish is tried again, here and after a restart (superTabs/inCore/teamPurge.ts withPurgeRetries).+ const purgeSessions = () => ({ live: registry.list(), stopped: stoppedAgents.list() })+ teamPurge = swarm.withPurgeRetries(swarm.createConfidentialPurge({ sessions: purgeSessions, confidential: (agentId) => policy.isConfidential(agentId), home: homedir(), record: purges,session: (agentId) => registry.byAgent(agentId) ?? stoppedAgents.get(agentId),- purge: async (request) => backend.purgeAgentService ? await backend.purgeAgentService.request(request as never) : { error: 'UNSUPPORTED' } })+ purge: async (request) => backend.purgeAgentService ? await backend.purgeAgentService.request(request as never) : { error: 'UNSUPPORTED' } }),+ { record: purges, sessions: purgeSessions, report: swarm.teamPurgeReport(), log: (line) => console.warn(`[super-tabs] ${line}`) })}const questionWatcher = asking.questionWatcherdiff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.tsindex 141bddcaa..6d67771c7 100644--- a/cli/src/superTabs/inCore.ts+++ b/cli/src/superTabs/inCore.ts@@ -18,7 +18,7 @@ export { quietOnDevices } from './inCore/devices.js'export { createSwarmSkillAdoption } from './inCore/adoption.js'export { createSwarmAgents } from './inCore/agents.js'export { SWARM_LAUNCH } from './inCore/launch.js'-export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor } from './inCore/teamApps.js'+export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor, teamPurgeReport, withPurgeRetries } from './inCore/teamApps.js'export { typesWhileBusy } from './inCore/deliveries.js'export { mayBeBuddy, retainedHarnesses, retainedLeads } from './retention.js'// A Product Manager switched from its pane (Change agent) is the one stop of a Lead its close guard and stop guard let through.diff --git a/cli/src/superTabs/inCore/teamApps.ts b/cli/src/superTabs/inCore/teamApps.tsindex c27f9f3fc..a807aba28 100644--- a/cli/src/superTabs/inCore/teamApps.ts+++ b/cli/src/superTabs/inCore/teamApps.ts@@ -22,9 +22,11 @@ import type { RemoteAppPolicy } from '../../core/api.js'import { eventAgentId } from '../../core/guestPolicy.js'import { roleFromWire } from '../../lib/swarmSkills.js'import { observerSnapshotFile } from '../../sharing/swarmMarks.js'-import type { PurgeRecord } from './teamPurge.js'+import { readTeamConfig } from '../../team/config.js'+import { writeTeamStatus } from '../../team/privacy.js'+import type { PurgeRecord, PurgeStatus } from './teamPurge.js'export { isTeamDaemon, pmEngineHome, PM_HOMES } from '../teamDaemon.js'-export { createConfidentialPurge, purgeRecord } from './teamPurge.js'+export { createConfidentialPurge, purgeRecord, withPurgeRetries } from './teamPurge.js'/** Answered while a confidential session runs here: each only reads, and those naming a session only a non-confidential one.* A terminal stream's frames are its own (terminalStreamManager.ts): it is watch-only, and only these reach it. */@@ -234,3 +236,10 @@ export function teamAppPolicyFor(dataDir: string, machineId: () => string,recorded: record.ids, record: ids => record.add(ids),...(purges ? { purging: () => ({ ids: purges.pending().map(t => t.agentId), unknown: purges.unknown() }) } : {}) })}++/** Tells `harness team status` the purges still to finish, in the Team account's status file (team/privacy.ts). A computer+ * with no owner (`harness team on`) has no such file, and no one's apps to hold it from. */+export const teamPurgeReport = () => (purges: PurgeStatus): void => {+ const config = readTeamConfig()+ if (config) writeTeamStatus(config.statusFile, { purges })+}diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.tsindex a6d940bc3..414c5a659 100644--- a/cli/src/superTabs/inCore/teamPurge.spec.ts+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts@@ -3,9 +3,10 @@ import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileimport { tmpdir } from 'node:os'import { dirname, join, win32 } from 'node:path'import { PM_HOMES } from '../teamDaemon.js'-import { describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PurgeAgentService } from '../../lib/purgeAgentService.js'import { createSwarmAgents } from './agents.js'-import { OWN_LEFT, SHARED_LEFT, SWEEP_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, isPmCodexHome, ownHomeFolder, purgeRecord, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'+import { OWN_LEFT, SHARED_LEFT, SWEEP_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, isPmCodexHome, ownHomeFolder, purgeRecord, withPurgeRetries, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'/** A folder that goes between the sweep's listing of its parent and its own read: removed just before that read. */const vanish = vi.hoisted(() => ({ path: '' }))@@ -965,3 +966,186 @@ describe('on Windows', () => {expect(readFileSync(join(parent, '.claude.json'), 'utf8')).toContain(KEY)})})++// Task #2264, Echo and Reed on #2675: nothing tried again once a host gave up, not even a restart.+describe('a purge that did not finish', () => {+ const MINUTE = 60_000+ const realTimeout = globalThis.setTimeout+ const fixture = (home: string, recordFile = join(home, 'super-tabs', 'team-purges.json')) => {+ const own = join(home, PM_HOMES, 'super-start', 'codex')+ mkdirSync(own, { recursive: true })+ const record = purgeRecord(recordFile)+ const state = { failing: true }+ const purge = vi.fn(async (request: Record<string, unknown>) => {+ if (state.failing) return { error: 'SERVICE_DOWN' }+ return request.mode === 'inspect' ? { reviewId: 'review-1' } : { ok: true }+ })+ const ended = createConfidentialPurge({ confidential: () => true, home, record, purge,+ session: agentId => ({ agentId, sessionId: 'session', registeredAt: 1, engine: 'codex', cwd: null, codexHome: own }) })+ const reports: unknown[] = [], logs: string[] = []+ const start = () => withPurgeRetries(ended, { record, sessions: () => ({ live: [], stopped: [] }), report: status => reports.push(status), log: line => logs.push(line) })+ return { own, record, state, purge, ended, reports, logs, start, recordFile }+ }+ /** Lets a due retry's disk work finish: it reads real folders, which fake timers do not wait for. */+ const pass = async (ms: number) => {+ await vi.advanceTimersByTimeAsync(ms)+ await new Promise(resolve => realTimeout(resolve, 60))+ }+ beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) })+ afterEach(() => { vi.useRealTimers() })++ it('is retried after a restart and clears, its engine home gone', async () => {+ const home = dir()+ const before = fixture(home)+ const first = before.start()+ expect(await first('pm')).toMatchObject({ error: 'SERVICE_DOWN' })+ first.stop()+ expect(existsSync(before.own)).toBe(true)+ // The daemon starts again, with only the file left.+ const after = fixture(home)+ expect(after.record.pending().map(t => t.agentId)).toEqual(['pm'])+ after.state.failing = false+ const second = after.start()+ await pass(MINUTE + 1)+ expect(existsSync(dirname(after.own))).toBe(false)+ expect(after.record.pending()).toEqual([])+ expect(after.reports.at(-1)).toMatchObject({ pending: 0, unreadable: false })+ second.stop()+ })++ it('tries again with growing waits while it fails, and stops once none is left', async () => {+ const f = fixture(dir())+ const retried = f.start()+ await retried('pm')+ const tries = () => f.purge.mock.calls.length+ const first = tries()+ await pass(MINUTE - 1)+ expect(tries()).toBe(first)+ await pass(1)+ expect(tries()).toBe(first + 1)+ await pass(MINUTE)+ expect(tries()).toBe(first + 1)+ await pass(MINUTE)+ expect(tries()).toBe(first + 2)+ for (const wait of [5, 15, 30, 30]) await pass(wait * MINUTE)+ expect(tries()).toBe(first + 6)+ expect(f.record.pending().map(t => t.agentId)).toEqual(['pm'])+ expect(f.reports.at(-1)).toMatchObject({ pending: 1, unreadable: false })+ f.state.failing = false+ await pass(30 * MINUTE)+ expect(f.record.pending()).toEqual([])+ const done = tries()+ await pass(120 * MINUTE)+ expect(tries()).toBe(done)+ retried.stop()+ })++ // Security review 2 of #2680: the real service stops a live session in delete mode and erases it, and refuses nothing here.+ describe('with its session or folder in use again', () => {+ /** A retry against the real purge service, its stop watched, on what the registry holds now. */+ type Rows = { live: Array<Record<string, unknown>>; stopped: Array<Record<string, unknown>> }+ const inUse = (home: string, rows_: Rows | ((paths: { own: string; cwd: string }) => Rows)) => {+ const own = join(home, PM_HOMES, 'super-start', 'codex'), cwd = join(home, 'work')+ const registry = typeof rows_ === 'function' ? rows_({ own, cwd }) : rows_+ mkdirSync(own, { recursive: true }); mkdirSync(cwd, { recursive: true })+ const record = purgeRecord(join(home, 'super-tabs', 'team-purges.json'))+ record.put({ agentId: 'pm', sessionId: 'session', cwd, engine: 'codex', codexHome: own })+ const stop = vi.fn(async () => {})+ const rows = () => [...registry.live, ...registry.stopped] as never[]+ const byId = (id: string) => registry.live.find(s => s.agentId === id) as never+ const service = new PurgeAgentService({ live: byId, sessions: rows, stop, restarting: () => false, deleted: () => {},+ stopped: { get: (id: string) => registry.stopped.find(s => s.agentId === id), list: () => registry.stopped, remove: () => {}, delete: () => {} } as never,+ checkpoints: { forSession: () => [], delete: () => {}, list: () => [] } as never,+ inspect: (async () => ({ sessions: [], files: [] })) as never, erase: (async () => ({ ok: true })) as never })+ const purge = vi.fn(async (request: Record<string, unknown>) => service.request(request as never) as Promise<Record<string, unknown>>)+ const sessions = () => ({ live: registry.live as never, stopped: registry.stopped as never })+ const ended = createConfidentialPurge({ confidential: () => true, home, record, purge, sessions,+ session: id => (byId(id) ?? registry.stopped.find(s => s.agentId === id) ?? null) as never })+ const retried = withPurgeRetries(ended, { record, sessions, report: () => {}, log: () => {} })+ return { own, cwd, record, stop, purge, ended, retried, registry }+ }+ const row = (over: Record<string, unknown>) => ({ agentId: 'other', sessionId: 'other-session', registeredAt: 1, engine: 'codex', cwd: '/elsewhere', codexHome: null, ...over })++ it('a retry leaves its own agent alone while it is live, and finishes once it stops', async () => {+ const registry = { live: [row({ agentId: 'pm', sessionId: 'session' })], stopped: [] as Array<Record<string, unknown>> }+ const f = inUse(dir(), registry)+ await pass(MINUTE)+ expect(f.purge).not.toHaveBeenCalled()+ expect(f.stop).not.toHaveBeenCalled()+ expect(existsSync(f.own)).toBe(true)+ expect(f.record.pending().map(t => t.agentId)).toEqual(['pm'])+ // It stopped: the next try goes through the service as any purge does.+ registry.stopped.push(registry.live.pop()!)+ await pass(2 * MINUTE)+ expect(f.purge).toHaveBeenCalled()+ f.retried.stop()+ })++ it('a conversation running under a new agent id keeps its engine home and traces, in a retry and a host\'s close', async () => {+ const f = inUse(dir(), { live: [row({ agentId: 'new', sessionId: 'session' })], stopped: [] })+ expect(await f.ended('pm')).toMatchObject({ error: 'SESSION_IN_USE' })+ await pass(MINUTE)+ expect(existsSync(f.own)).toBe(true)+ expect(f.record.pending().map(t => t.agentId)).toEqual(['pm'])+ f.retried.stop()+ })++ it('a later session in its folder or on its engine home stops it too', async () => {+ for (const clash of [(p: { own: string; cwd: string }) => ({ cwd: p.cwd }), (p: { own: string; cwd: string }) => ({ codexHome: p.own })]) {+ const f = inUse(dir(), paths => ({ live: [row(clash(paths))], stopped: [] }))+ expect(await f.ended('pm')).toMatchObject({ error: 'SESSION_IN_USE' })+ expect(existsSync(f.own)).toBe(true)+ f.retried.stop()+ }+ })++ it('a stopped session under a new id holds it unless that one is ending too, so two can\'t wait on each other', async () => {+ const held = inUse(dir(), { live: [], stopped: [row({ agentId: 'new', sessionId: 'session' })] })+ expect(await held.ended('pm')).toMatchObject({ error: 'SESSION_IN_USE' })+ held.retried.stop()+ const both = inUse(dir(), { live: [], stopped: [row({ agentId: 'new', sessionId: 'session' })] })+ both.record.put({ agentId: 'new', sessionId: 'session', cwd: null, engine: 'codex', codexHome: null })+ expect((await both.ended('pm')).error).not.toBe('SESSION_IN_USE')+ both.retried.stop()+ })+ })++ it('runs nothing with its record unreadable, and says so', async () => {+ const home = dir(), file = join(home, 'super-tabs', 'team-purges.json')+ mkdirSync(dirname(file), { recursive: true })+ writeFileSync(file, 'not json')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const f = fixture(home, file)+ warn.mockRestore()+ const retried = f.start()+ await pass(MINUTE)+ expect(f.purge).not.toHaveBeenCalled()+ expect(f.reports.at(-1)).toMatchObject({ pending: 0, unreadable: true })+ retried.stop()+ })++ it('shares one run between a host\'s close and a retry of the same agent', async () => {+ const f = fixture(dir())+ f.state.failing = false+ let open!: () => void+ const held = new Promise<void>(resolve => { open = resolve })+ const slow = vi.fn(async (agentId: string) => { await held; return f.ended(agentId) })+ const retried = withPurgeRetries(slow, { record: f.record, sessions: () => ({ live: [], stopped: [] }), report: () => {}, log: () => {} })+ const both = [retried('pm'), retried('pm')]+ expect(slow).toHaveBeenCalledTimes(1)+ open()+ await Promise.all(both)+ retried.stop()+ })++ it('reports a count only: no agent, session or path', async () => {+ const f = fixture(dir())+ const retried = f.start()+ await retried('pm-secret')+ const said = JSON.stringify(f.reports.at(-1))+ expect(Object.keys(f.reports.at(-1) as object).sort()).toEqual(['at', 'pending', 'unreadable'])+ expect(said).not.toContain('pm-secret')+ expect(said).not.toContain('session')+ retried.stop()+ })+})diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.tsindex 10f31087b..5c630bacf 100644--- a/cli/src/superTabs/inCore/teamPurge.ts+++ b/cli/src/superTabs/inCore/teamPurge.ts@@ -470,7 +470,23 @@ export function ownHomeFolder(homes: string, codexHome: string | null | undefine* The purge of [agentId]'s data, once the Swarm ended it for good, when it was confidential: kept in [record] before the* first deletion and dropped once the sweep finds nothing. A retry finishes from the record, the session gone or not.*/+/** A session as a purge compares it with what it recorded. */+interface HeldRow { agentId: string; sessionId?: string | null; cwd?: string | null; codexHome?: string | null }+/** What this daemon runs now, and what it keeps stopped and may resume. */+export type PurgeSessions = () => { live: readonly HeldRow[]; stopped: readonly HeldRow[] }++/** Whether another session holds what deleting [target] would take: its conversation or engine home, or, while it runs, its+ * folder, whose transcripts and history lines go by that folder. A stopped one that is itself ending doesn't count, or two+ * sessions of one conversation would wait on each other for good (security reviews 1 and 2 of #2680). */+function heldByAnother(target: PurgeTarget, sessions: ReturnType<PurgeSessions>, ending: PurgeRecord): boolean {+ const same = (s: HeldRow) => (!!target.sessionId && s.sessionId === target.sessionId) || (!!target.codexHome && s.codexHome === target.codexHome)+ return sessions.live.some(s => s.agentId !== target.agentId && (same(s) || (!!target.cwd && s.cwd === target.cwd)))+ || sessions.stopped.some(s => s.agentId !== target.agentId && !ending.get(s.agentId) && same(s))+}+export function createConfidentialPurge(deps: {+ /** What else is here now: a purge that would take what another session holds is refused, and stays recorded. */+ sessions?: PurgeSessionsconfidential: (agentId: string) => booleansession: (agentId: string) => { agentId: string; sessionId?: string | null; registeredAt: number; engine: string; cwd: string | null; codexHome?: string | null } | nullpurge: (request: Record<string, unknown>) => Promise<Record<string, unknown>>@@ -498,6 +514,9 @@ export function createConfidentialPurge(deps: {target = { agentId: session.agentId, sessionId: session.sessionId ?? null, cwd: session.cwd, engine: session.engine, codexHome: session.codexHome ?? null }deps.record.put(target)}+ if (deps.sessions && heldByAnother(target, deps.sessions(), deps.record)) {+ return { error: 'SESSION_IN_USE', detail: 'Another session holds what this purge would delete.' }+ }if (session) {const reference = { agentId: session.agentId, sessionId: session.sessionId ?? null, createdAt: session.registeredAt }const review = await deps.purge({ ...reference, mode: 'inspect' })@@ -520,3 +539,66 @@ export function createConfidentialPurge(deps: {}}+/** How long a purge that did not finish waits for its next try, each try the next, and the last from then on. */+const PURGE_RETRY_MS = [1, 2, 5, 15, 30].map(minutes => minutes * 60_000)++/** What the owner's `harness team status` reads of the purges still to finish (team/privacy.ts). A count: the status file is+ * the owner's to read, and never names a session of someone else's project. */+export interface PurgeStatus { pending: number; unreadable: boolean; at: number }++/**+ * Tries again what the record still holds (Echo and Reed on #2675): a host's close gives up after a few tries, and one that+ * ended nothing leaves no host trying at all, while the account stays held. At its start, so a restart picks up the record, and+ * after any purge that leaves one, on a growing wait until none is left. Through [purge] alone, with its reviewed delete. A+ * pass skips an agent that is live again: the reviewed delete stops a live session and erases it, which only a host closing it+ * may ask for (security review 2 of #2680). It stays recorded and is tried again. A record that can't be read names nothing to+ * run, and waits for a person, as it always has. Calls for one agent share a run, so a retry and a host's close never scrub at once.+ */+export function withPurgeRetries(purge: (agentId: string) => Promise<Record<string, unknown>>, deps: {+ record: PurgeRecord+ sessions: PurgeSessions+ report: (status: PurgeStatus) => void+ log: (line: string) => void+ now?: () => number+}): ((agentId: string) => Promise<Record<string, unknown>>) & { stop(): void } {+ const running = new Map<string, Promise<Record<string, unknown>>>()+ let timer: ReturnType<typeof setTimeout> | null = null, tries = 0, passing = false, stopped = false+ const run = (agentId: string) => {+ const known = running.get(agentId)+ if (known) return known+ const started = purge(agentId).finally(() => running.delete(agentId))+ running.set(agentId, started)+ return started+ }+ const settle = () => {+ if (!deps.record.pending().length) tries = 0+ try { deps.report({ pending: deps.record.pending().length, unreadable: deps.record.unknown(), at: (deps.now ?? Date.now)() }) }+ catch (error) { deps.log(`could not report the purges still to finish: ${kindOf(error)}`) }+ if (stopped || timer || passing || !deps.record.pending().length) return+ timer = setTimeout(() => void pass(), PURGE_RETRY_MS[Math.min(tries, PURGE_RETRY_MS.length - 1)]!)+ timer.unref?.()+ }+ const pass = async () => {+ timer = null+ passing = true+ for (const { agentId } of deps.record.pending()) {+ if (stopped) break+ if (deps.sessions().live.some(s => s.agentId === agentId)) continue+ // By its kind alone: a detail can name a path, and this goes in the daemon's log.+ const said = await run(agentId).catch((error: unknown) => ({ error: kindOf(error) }))+ if (typeof said.error === 'string') deps.log(`a purge did not finish, and is tried again: ${said.error}`)+ }+ passing = false+ tries+++ settle()+ }+ const retried = async (agentId: string) => {+ try { return await run(agentId) } finally { settle() }+ }+ settle()+ return Object.assign(retried, { stop: () => { stopped = true; if (timer) clearTimeout(timer); timer = null } })+}++const kindOf = (error: unknown): string => error instanceof Error+ ? typeof (error as NodeJS.ErrnoException).code === 'string' ? (error as NodeJS.ErrnoException).code! : error.name+ : 'unknown failure'diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.tsindex 3ef1f781b..899f2ef19 100644--- a/cli/src/team/command.spec.ts+++ b/cli/src/team/command.spec.ts@@ -239,6 +239,29 @@ describe('harness team status', () => {}})+ // Task #2264: an account held by data not deleted yet said so nowhere a person looks.+ it('says when the data of ended sessions is not deleted yet, and nothing when none is waiting', async () => {+ const said = async (purges?: { pending: number; unreadable: boolean; at: number }) => {+ const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })+ f.status.set(STATUS, { version: 1, ...(purges ? { purges } : {}) })+ await teamCommand(['status'], f.deps)+ return f.out.join('\n')+ }+ const two = await said({ pending: 2, unreadable: false, at: 1_000_000 - 60_000 })+ expect(two).toContain('purges ◍ 2 ended sessions\' data not deleted yet (checked 60s ago)')+ expect(two).toContain('this account takes no other project\'s work until it has')+ expect(await said({ pending: 1, unreadable: false, at: 1_000_000 })).toContain('◍ 1 ended session\'s data not deleted yet')+ const unreadable = await said({ pending: 0, unreadable: true, at: 1_000_000 })+ expect(unreadable).toContain('purges ✗ the record of what is still to delete can\'t be read')+ expect(unreadable).toContain('the Team daemon\'s log says where it was kept')+ expect(await said({ pending: 0, unreadable: false, at: 1_000_000 })).not.toContain('purges ')+ expect(await said()).not.toContain('purges ')+ const json = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })+ json.status.set(STATUS, { version: 1, purges: { pending: 2, unreadable: false, at: 5 } })+ await teamCommand(['status', '--json'], json.deps)+ expect(JSON.parse(json.out[0]!).purges).toEqual({ pending: 2, unreadable: false, at: 5 })+ })+it('says whether the team account\'s engines are installed and signed in, and exactly how to sign them in', async () => {const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })f.status.set(STATUS, { version: 1, engines: { checkedAt: 1_000_000 - 60_000, claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } } })diff --git a/cli/src/team/command.ts b/cli/src/team/command.tsindex 13a023e5a..454d4deae 100644--- a/cli/src/team/command.ts+++ b/cli/src/team/command.ts@@ -482,7 +482,7 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {account: exists, user, realName: config?.realName ?? TEAM_REAL_NAME, home, homePresent: deps.exists(home),label, plist: serviceFile, plistPresent, job, port: config?.port ?? TEAM_PORT,config: config ? layout.configFile : null, ownerHomeMode: homeMode === null ? null : homeMode.toString(8),- signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, engines: report?.engines ?? null, dedicated,+ signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, engines: report?.engines ?? null, purges: report?.purges ?? null, dedicated,agentTmp: agentTmp && { ...agentTmp, mode: agentTmp.mode === null ? null : agentTmp.mode.toString(8) },}))return 0@@ -509,6 +509,7 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {: `${agentTmp.mode === null ? 'not a private folder' : `mode ${agentTmp.mode.toString(8)}`} ✗ your agents may use the shared /tmp: your next agent makes it private, or says why not in the daemon's log`}`)}for (const line of engineLines(report?.engines, (at) => ago(now, at), deps.platform)) deps.out(line)+ for (const line of purgeLines(report?.purges, (at) => ago(now, at))) deps.out(line)deps.out('')deps.out(' What setup made:')for (const line of madeLines(here, owner, ownerHome)) deps.out(` ${line}`)@@ -518,6 +519,19 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {return 0}+/** What `harness team status` says of ended sessions' data not deleted yet (superTabs/inCore/teamPurge.ts): nothing when none+ * waits. It holds the account, so this says why it takes no other project's work. */+function purgeLines(purges: TeamStatus['purges'], ago: (at: number) => string): string[] {+ if (purges?.unreadable) {+ return [' purges ✗ the record of what is still to delete can\'t be read: the Team daemon\'s log says where it was kept.',+ ' Until its owner clears it, this account takes no other project\'s work.']+ }+ if (!purges?.pending) return []+ const count = purges.pending === 1 ? '1 ended session\'s' : `${purges.pending} ended sessions'`+ return [` purges ◍ ${count} data not deleted yet (checked ${ago(purges.at)}). The daemon keeps trying by itself;`,+ ' this account takes no other project\'s work until it has.']+}+/** A terminal app's bundle id as macOS gives it to what the app starts, for the one command that asks again. */const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,127}$/diff --git a/cli/src/team/privacy.spec.ts b/cli/src/team/privacy.spec.tsindex 2dd0f0e0f..a13a43c48 100644--- a/cli/src/team/privacy.spec.ts+++ b/cli/src/team/privacy.spec.ts@@ -152,6 +152,21 @@ describe('status file', () => {expect(statSync(file).mode & 0o777).toBe(0o644)})+ // Task #2264: every report rewrites the file from what it read, so one that dropped this would forget it.+ it('keeps the purges still to finish across another report, and drops a malformed count', () => {+ const dir = mkdtempSync(join(tmpdir(), 'team-status-'))+ cleanup.push(dir)+ const file = join(dir, 'Team', 'status.json')+ writeTeamStatus(file, { purges: { pending: 2, unreadable: false, at: 5 } })+ writeTeamStatus(file, { signIn: { state: 'signed-in', at: 1 } })+ expect(readTeamStatus(file)?.purges).toEqual({ pending: 2, unreadable: false, at: 5 })+ for (const purges of [{ pending: -1, unreadable: false, at: 5 }, { pending: 1.5, unreadable: false, at: 5 }, { pending: 1, unreadable: 'no', at: 5 }, { pending: 1, unreadable: false }, 'two']) {+ expect(readTeamStatus('/x', () => JSON.stringify({ version: 1, purges }))).toEqual({ version: 1 })+ }+ // Only its count: a field the daemon never writes doesn't reach the owner's screen.+ expect(readTeamStatus('/x', () => JSON.stringify({ version: 1, purges: { pending: 1, unreadable: false, at: 5, agent: 'pm' } }))?.purges).toEqual({ pending: 1, unreadable: false, at: 5 })+ })+it('drops what it does not recognise', () => {expect(readTeamStatus('/x', () => 'not json')).toBeNull()expect(readTeamStatus('/x', () => '{"version":2}')).toBeNull()diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.tsindex 0b0af0e7b..1a9b0ef5a 100644--- a/cli/src/team/privacy.ts+++ b/cli/src/team/privacy.ts@@ -136,6 +136,8 @@ export interface TeamStatus {privacy?: PrivacyResult/** Claude Code and Codex in the team account (./engines.ts). */engines?: TeamEngines+ /** The data of ended sessions not deleted yet (superTabs/inCore/teamPurge.ts): a count, never a name. */+ purges?: { pending: number; unreadable: boolean; at: number }}/** The `engines` field of the status file, or undefined when it is not one. */@@ -275,6 +277,11 @@ export function readTeamStatus(path: string, read: (path: string) => string = (aif (privacy) status.privacy = privacyconst engines = enginesOf(value.engines)if (engines) status.engines = engines+ const purges = value.purges as Record<string, unknown> | undefined+ if (purges && typeof purges === 'object' && Number.isSafeInteger(purges.pending) && (purges.pending as number) >= 0+ && typeof purges.unreadable === 'boolean' && typeof purges.at === 'number' && Number.isFinite(purges.at)) {+ status.purges = { pending: purges.pending as number, unreadable: purges.unreadable, at: purges.at }+ }return status}diff --git a/docs/plans/2026-11-03-purge-retry-plan.md b/docs/plans/2026-11-03-purge-retry-plan.mdnew file mode 100644index 000000000..127428524--- /dev/null+++ b/docs/plans/2026-11-03-purge-retry-plan.md@@ -0,0 +1,72 @@+# A Purge That Did Not Finish Is Retried Implementation Plan++> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.++**Goal:** A confidential purge that didn't finish is retried with backoff and on the next start of the Team daemon, and a person can see that it's pending.++**Architecture:** The durable record already exists (`purgeRecord`, `team-purges.json`): it keeps each purge until its sweep finds nothing, and the account stays held while it has any. Nothing reads it to try again. `withPurgeRetries` wraps the purge: at start, and after any purge that leaves the record non-empty, it runs each pending purge on a backoff until none is left. It writes a count to the Team status file, which `harness team status` shows. Calls for the same agent share one run.++**Tech Stack:** TypeScript, Vitest.++**Spec:** Task #2264 (Ken), raised by Echo and Reed on #2675.++## Global Constraints++- The PR body starts with: `Requested by [email protected] through Harness.`+- Two security reviews: Reed and Echo.+- Never run tests that sign this Mac out of the real CLI. Tests use temporary homes.+- Swarm code stays out of `cli/src/core`: `core/main.ts` only calls what the Swarm part offers.+- The status file says a count, never an agent, session or path. No on/off switch.++## Review Focus++1. A retry goes only through the existing purge, with its reviewed delete and its limits. It adds no new way to delete anything, and only ever names ids from the record.+2. A session that came back stays safe: a retry pass skips a live agent, as the reviewed delete would stop and erase it. A purge that would take another session's conversation, engine home or running folder is refused. Either way it stays pending.+3. An unreadable record retries nothing and says so; the account stays held until a person clears it, as today.+4. A retry racing a host's own close of the same agent shares one run, so two never scrub at once.+5. The status file is readable by the owner, so it holds no names.++## Design++- **Growth:** none new: the record already exists. A purge leaves it when it finishes.+- **Concurrency:** one retry pass at a time, and one run per agent. The record is read and written in this one process.+- **Read cost:** the record is in memory. A pass does the purge's own disk work, at most every 30 minutes once backed off.+- **Scale:** N/A because a Team account has few confidential sessions; a pass runs them one after another.+- **Compatibility:** an older `harness team status` ignores the new field, and a newer one reads a file without it as nothing pending.+- **Migration and rollback:** none. Records written before this are picked up at the next start. Rolling back leaves an unused field.+- **Audience:** the status file holds only a count. The record stays private to the Team account.+- **Identity:** runs as the Team user, in its own daemon.+- **Failure:** a pass that fails keeps the record, logs by kind and tries later. A failed status write is logged and tried at the next pass.+- **Platforms:** same code on macOS, Linux and Windows; the status file already has its place on each.++---++### Task 1: Retries++**Files:**+- Modify: `cli/src/superTabs/inCore/teamPurge.ts`, `cli/src/superTabs/inCore/teamApps.ts`, `cli/src/superTabs/inCore.ts`, `cli/src/core/main.ts`+- Test: `cli/src/superTabs/inCore/teamPurge.spec.ts`++**Interfaces:**+- Produces: `withPurgeRetries(purge, { record, sessions, report, log }): ((agentId) => Promise<Record<string, unknown>>) & { stop(): void }`.++- [ ] **Step 1: Write the failing tests:** a failed purge is retried after a restart and clears, removing the engine home; backoff grows and stops once none is pending; one that keeps failing stays recorded and keeps trying; a live session isn't touched, against the real purge service; a conversation, engine home or folder another session holds is refused, without two ending sessions waiting on each other; an unreadable record runs nothing and reports it; two calls for one agent share a run; the report holds only a count.+- [ ] **Step 2: Run them:** `npx vitest run --no-coverage src/superTabs/inCore/teamPurge.spec.ts` in `cli`. Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run them.** Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 2: A person can see it++**Files:**+- Modify: `cli/src/team/privacy.ts`, `cli/src/team/command.ts`+- Test: `cli/src/team/privacy.spec.ts`, `cli/src/team/command.spec.ts`++**Interfaces:**+- Produces: `TeamStatus.purges?: { pending: number; unreadable: boolean; at: number }`.++- [ ] **Step 1: Write the failing tests:** the status file keeps a valid `purges` and drops a malformed one; `harness team status` says pending, says unreadable, and says nothing when none is pending; its JSON carries it.+- [ ] **Step 2: Run them.** Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run them.** Expected: PASS.+- [ ] **Step 5: Commit, run `npm run test:core`, mark the pull request ready** and ask Reed and Echo.