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
Separate harness disk usage and add confirmed worktree cleanup (#593)
Deef4aa40bb8d43
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex c57290fbb..783ca6ad2 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -14,6 +14,7 @@ import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.jsimport { registry, type RegisteredSession } from './lib/registry.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { AgentStopError } from './lib/stopAgentService.js'+import type { PurgeAgentService } from './lib/purgeAgentService.js'import * as mediaPreview from './lib/mediaPreview.js'import * as gitProject from './lib/gitProject.js'import * as machineResources from './lib/machineResources.js'@@ -140,6 +141,40 @@ describe('safe session close RPC', () => {})})+describe('reviewed permanent deletion RPCs', () => {+ afterEach(() => vi.restoreAllMocks())+ it.each(['agent_purge', 'agent_worktree_delete'])('%s requires an owner, explicit identity and a review token', async type => {+ const socket = new BackendSocket('fixture')+ const internals = socket as any, frames: any[] = []+ socket.registerLocalClient('local:purge', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })+ const request = vi.fn(async () => ({ reviewId: 'review', sessionBytes: 4096 }))+ socket.purgeAgentService = { busy: () => false, request, worktreeRequest: request } as unknown as PurgeAgentService+ const payload = { requestId: 'delete', agentId: 'selected', sessionId: 'history', createdAt: 1234, mode: 'inspect' }+ expect(encryptDownFrame(type)).toBe(true)+ expect(encryptRpcResult(type + '_result')).toBe(true)+ await internals.dispatchDown({ type, payload }, 'remote')+ expect(request).not.toHaveBeenCalled()+ const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('device')+ vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue({ type, payload })+ vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: type + '_result', payload: { __e2e: 'sealed' } })+ const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }+ await internals.dispatchDown(sealed, 'remote')+ expect(request).not.toHaveBeenCalled()+ role.mockReturnValue('web')+ await internals.dispatchDown(sealed, 'remote')+ expect(request).toHaveBeenCalledOnce()+ request.mockClear()+ for (const invalid of [{ ...payload, sessionId: undefined }, { ...payload, createdAt: '1234' }, { ...payload, mode: 'delete' }]) {+ await internals.dispatchDown({ type, payload: invalid }, 'local:purge', 'local')+ }+ expect(request).not.toHaveBeenCalled()+ expect(frames.filter(f => f.payload.error === 'INVALID_DELETE_REQUEST')).toHaveLength(3)+ await internals.dispatchDown({ type, payload: { ...payload, mode: 'delete', reviewId: 'review', path: '/reviewed', discardChanges: true } }, 'local:purge', 'local')+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ reviewId: 'review', path: '/reviewed', discardChanges: true }))+ await socket.stop()+ })+})+describe('local model lifecycle RPCs', () => {afterEach(() => vi.restoreAllMocks())it.each(['grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])('dispatches %s and returns its correlated result', async type => {diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 8b0e653df..25216908d 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,3 +1,4 @@+import type { PurgeAgentService } from './lib/purgeAgentService.js'import type { ActivityFrame } from './lib/turnActivity.js'import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'import { MonitorCompletions, type MonitorActivity } from './lib/harnessMonitor.js'@@ -509,6 +510,7 @@ export class BackendSocket {/** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine* process and forgets the session. Keeps recap + agent name. */onDeleteAgent: ((sessionId: string) => void | Promise<void>) | null = null+ purgeAgentService: PurgeAgentService | null = nullcloseAgentService: CloseAgentService | null = nullcleanupPreview: (() => Promise<Record<string, unknown>>) | null = null/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the@@ -1847,6 +1849,11 @@ export class BackendSocket {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)+ const lifecycleTarget = (frame.payload as { agentId?: unknown } | undefined)?.agentId+ if (typeof lifecycleTarget === 'string' && this.purgeAgentService?.busy(lifecycleTarget)+ && ['agent_close', 'agent_delete', 'agent_resume', 'agent_restart', 'agent_retarget', 'agent_update'].includes(type)) {+ reply(type, (frame.payload as { requestId?: unknown }).requestId, { error: 'DELETE_IN_PROGRESS' }); return+ }if (SHARE_REQUEST_TYPES.has(type)) {const p = (frame.payload ?? {}) as Record<string, unknown>const result = await this.harnessSharing?.manage(type, p).catch(() => ({ error: 'SHARING_UNAVAILABLE', detail: 'Sharing is temporarily unavailable. Try again.' }))@@ -2183,9 +2190,8 @@ export class BackendSocket {const projects = await Promise.all(sessions.map((s) => this.toProject(s)))// Older clients/devices keep their live-only contract. The desktop picker// explicitly asks for stopped work and receives no stale terminal routes.- if (payload.includeStopped === true && this.e2ee.sessionRole(connId) !== 'device') {- projects.push(...await Promise.all(stoppedAgents.available(registry.advertised()).map(s => this.toStoppedProject(s))))- }+ const savedSessions = payload.includeStopped === true && this.e2ee.sessionRole(connId) !== 'device' ? stoppedAgents.available(sessions) : []+ projects.push(...await Promise.all(savedSessions.map(s => this.toStoppedProject(s))))// Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as// sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the// order is TOTAL: without it two agents registered in the same millisecond fall through to array@@ -2202,7 +2208,7 @@ export class BackendSocket {void (async () => {const [snapshot, storage] = await Promise.all([this.harnessResourcesReader().catch(() => ({ agents: [], sampledAt: null, shared: [] })),- this.harnessStorageReader(sessions).catch(() => new Map()),+ this.harnessStorageReader([...sessions, ...savedSessions]).catch(() => new Map()),])const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))const byId = new Map(sessions.map(s => [s.agentId, s]))@@ -3096,6 +3102,27 @@ export class BackendSocket {.then(result => reply(type, requestId, result), () => reply(type, requestId, { error: 'CLOSE_FAILED' }))return}+ case 'agent_worktree_delete':+ case 'agent_purge': {+ if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }+ if (!this.purgeAgentService) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }+ const { agentId, sessionId, createdAt, mode, reviewId, path, discardChanges } = payload+ if (typeof agentId !== 'string' || !(sessionId === null || typeof sessionId === 'string')+ || typeof createdAt !== 'number' || !Number.isFinite(createdAt)+ || (mode !== 'inspect' && mode !== 'delete') || (mode === 'delete' && typeof reviewId !== 'string')) {+ reply(type, requestId, { error: 'INVALID_DELETE_REQUEST' }); return+ }+ const operation = type === 'agent_worktree_delete' ? this.purgeAgentService.worktreeRequest.bind(this.purgeAgentService) : this.purgeAgentService.request.bind(this.purgeAgentService)+ const deletion = { agentId, sessionId, createdAt, mode: mode as 'inspect' | 'delete',+ ...(typeof reviewId === 'string' ? { reviewId } : {}),+ ...(typeof path === 'string' ? { path } : {}), discardChanges: discardChanges === true }+ void operation(deletion)+ .then(result => {+ if (result.deleted === true) void this.harnessStorageReader([], true)+ reply(type, requestId, result)+ }, () => reply(type, requestId, { error: 'DELETE_FAILED' }))+ return+ }case 'agent_delete': {const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 7dec0f54a..4dc281b49 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -150,6 +150,7 @@ import { createRetainExitedSession } from './lib/retainExitedSession.js'import { createSessionSync } from './lib/sessionSync.js'import { CloseAgentService, inspectCloseActivity } from './lib/closeAgentService.js'import { OpenTabProtection } from './lib/openTabProtection.js'+import { PurgeAgentService } from './lib/purgeAgentService.js'import { sessionCheckpoints } from './lib/sessionCheckpoint.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'@@ -6242,6 +6243,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {ownerBusy = adopted.busyresumeArgs = adopted.launchArgs}+ if (backend.purgeAgentService?.blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }} catch {@@ -6682,6 +6684,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* indistinguishable from a working one until the bill arrives.*/backend.onRetargetAgent = async ({ agentId, grid }) => {+ if (backend.purgeAgentService?.busy(agentId)) return { ok: false, error: 'AGENT_BUSY' }if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }const session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }@@ -6895,6 +6898,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {forgetSession, markDeleted, clearDeleted,})backend.onDeleteAgent = stopAgent+ backend.purgeAgentService = new PurgeAgentService({+ live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],+ stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,+ restarting: id => restartJobs.busy(id) || stopJobs.has(id),+ deleted: s => {+ if (s.sessionId) { mirror.deleteHistory(s.sessionId); sessionSearch?.deleteHistory(s.sessionId) }+ registry.deleteSavedNames([s.agentId, s.sessionId].filter(Boolean))+ backend.send({ type: 'agent_deleted', payload: { agentId: s.agentId, retained: false } })+ },+ })backend.closeAgentService = new CloseAgentService({registry,openTabs: cleanupTabs,@@ -6924,11 +6937,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { version: 1, agents, kept: sessions.length - agents.length }}- backend.onResumeAgent = createResumeAgentService({+ const resumeAgent = createResumeAgentService({registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,refreshGridWebSearch, clearDeleted, attachDsh,})+ backend.onResumeAgent = (id, permissionMode) => backend.purgeAgentService?.busy(id) || backend.purgeAgentService?.blocksFolder(stoppedAgents.get(id)?.cwd)+ ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resumeAgent(id, permissionMode)/*** Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in@@ -6950,7 +6965,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* from inside the engine's own terminal since launch).*/backend.onRestartAgent = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {- if (stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }+ if (backend.purgeAgentService?.busy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }const session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.tsindex 8ee1739a4..f6f0a6d87 100644--- a/cli/src/lib/commander.spec.ts+++ b/cli/src/lib/commander.spec.ts@@ -46,6 +46,23 @@ describe('CommanderMirror recap events', () => {expect(mirror.recent('session-ask', 3)[0].recap).toBe('1945.')})+ it('permanently removes only the selected conversation from persisted recap history', async () => {+ const options = { send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize: async () => 'Fixture recap', dataDir }+ const mirror = new CommanderMirror(options)+ for (const id of ['selected', 'kept']) mirror.ingest([+ { type: 'turn_started', payload: { userMessage: 'question ' + id } },+ { type: 'text_delta', payload: { content: 'answer ' + id } },+ { type: 'turn_ended', payload: {} },+ ] as LiveEvent[], id)+ await vi.runAllTimersAsync()+ mirror.deleteHistory('selected')+ const reloaded = new CommanderMirror(options)+ expect(reloaded.recent('selected')).toEqual([])+ expect(reloaded.recentAsks('selected')).toEqual([])+ expect(reloaded.recent('kept')).toHaveLength(1)+ expect(reloaded.recentAsks('kept')).toEqual(['question kept'])+ })+it('keeps the question even when the turn produces no summary at all', async () => {// The fault this replaced: the ask was written in the summariser's success branch, so a turn with// no assistant text — or a summariser that returned null — left no record of what was asked.diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex 7704edd9a..a835af804 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -23,6 +23,7 @@ import { join } from 'path'import type { LastTurnText, LiveEvent } from './normalize.js'import { AgentNotifications } from './agentNotifications.js'import { deriveTurnSummary } from './deviceRecap.js'+import { atomicWriteJson } from './registry.js'export type CommanderFrame = {type: 'commander_event'@@ -966,6 +967,17 @@ export class CommanderMirror {}// ── persistence ──────────────────────────────────────────────────────────────────────────────+ deleteHistory(sessionId: string): void {+ this.forget(sessionId)+ if (this.saveTimer) clearTimeout(this.saveTimer)+ this.saveTimer = null+ this.summaries.delete(sessionId)+ this.history.delete(sessionId)+ this.fullTexts.delete(sessionId)+ this.asks.delete(sessionId)+ this.save(true)+ }+private load(): void {try {const obj = JSON.parse(readFileSync(this.file, 'utf-8')) as Record<string, string>@@ -998,14 +1010,24 @@ export class CommanderMirror {this.saveTimer = setTimeout(() => this.save(), 200)}- private save(): void {+ private save(strict = false): void {try {mkdirSync(this.opts.dataDir, { recursive: true, mode: 0o700 })+ if (strict) {+ // Cleanup is often requested on a full disk. Never truncate other sessions' shared+ // history while rewriting these files; failed atomic writes remain safely retryable.+ atomicWriteJson(this.file, Object.fromEntries(this.summaries))+ atomicWriteJson(this.historyFile, Object.fromEntries(this.history))+ atomicWriteJson(this.fullTextFile, Object.fromEntries(this.fullTexts))+ atomicWriteJson(this.askFile, Object.fromEntries(this.asks))+ return+ }writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.summaries), null, 2))writeFileSync(this.historyFile, JSON.stringify(Object.fromEntries(this.history), null, 2))writeFileSync(this.fullTextFile, JSON.stringify(Object.fromEntries(this.fullTexts), null, 2))writeFileSync(this.askFile, JSON.stringify(Object.fromEntries(this.asks), null, 2))} catch (err) {+ if (strict) throw errconsole.error('[commander] save summaries failed:', err)}}diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex a924b7f8b..0bb3cc505 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -18,7 +18,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.-const MACHINE_REQUESTS = new Set(['agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])+const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floordiff --git a/cli/src/lib/harnessTelemetry.spec.ts b/cli/src/lib/harnessTelemetry.spec.tsindex 3fe607af2..e4fec27ca 100644--- a/cli/src/lib/harnessTelemetry.spec.ts+++ b/cli/src/lib/harnessTelemetry.spec.ts@@ -49,3 +49,28 @@ it('storage failures and unknown transcripts remain unknown and do not immediateexpect(values.get('b')?.workspaceBytes).toBeNull()expect(size).toHaveBeenCalledTimes(1)})+it('reports session storage separately, caches it, and refreshes a rotated conversation', async () => {+ const session = vi.fn(async () => 4096)+ const read = createHarnessStorageReader({ now: () => 10000, size: async () => 1e9,+ transcript: async () => 2048, canonical: async p => p, session })+ const rows = [{ agentId: 'a', sessionId: 'first', cwd: '/project', transcriptPath: '/history' }]+ await read(rows)+ await vi.waitFor(async () => expect((await read(rows)).get('a')).toMatchObject({ workspaceBytes: 1e9, sessionBytes: 4096, transcriptBytes: 2048 }))+ expect(session).toHaveBeenCalledTimes(1)+ await read([{ ...rows[0], sessionId: 'second' }])+ expect(session).toHaveBeenCalledTimes(2)+})+it('invalidates disk totals after deletion without accepting a late pre-deletion probe', async () => {+ const pending: Array<(size: number) => void> = []+ const read = createHarnessStorageReader({ now: () => 10000,+ size: () => new Promise(resolve => pending.push(resolve)), transcript: async () => null, canonical: async p => p })+ const rows = [{ agentId: 'a', cwd: '/project' }]+ await read(rows)+ await read([], true)+ await read(rows)+ pending[1](20)+ await Promise.resolve()+ pending[0](1000)+ await Promise.resolve()+ expect((await read(rows)).get('a')?.workspaceBytes).toBe(20)+})diff --git a/cli/src/lib/harnessTelemetry.ts b/cli/src/lib/harnessTelemetry.tsindex 5f6c3cdbe..aa13eb5a6 100644--- a/cli/src/lib/harnessTelemetry.ts+++ b/cli/src/lib/harnessTelemetry.ts@@ -4,6 +4,10 @@ import { isAbsolute } from 'node:path'import { promisify } from 'node:util'import { readMacProcessGpu, type MacProcessGpu } from './macosProcessGpu.js'+import type { RegisteredSession } from './registry.js'+import { sessionCheckpoints } from './sessionCheckpoint.js'+import { sessionDataBytes } from './purgeAgentService.js'+const exec = promisify(execFile)export type ProcessTelemetry = { readBytes: number | null; writeBytes: number | null; gpuMemoryBytes: number | null; gpuPercent?: number | null; macGpu?: MacProcessGpu }const count = (value: string | undefined) => value != null && /^\d+$/.test(value.trim()) && Number.isSafeInteger(Number(value)) ? Number(value) : null@@ -83,13 +87,15 @@ export async function readProcessTelemetry(pids: number[]): Promise<Map<number,return result}-export type StorageReading = { workspaceBytes: number | null; workspacePath: string | null; workspaceSampledAt: string | null; transcriptBytes: number | null }-type Target = { agentId: string; cwd?: string | null; transcriptPath?: string | null }+export type StorageReading = { workspaceBytes: number | null; workspacePath: string | null; workspaceSampledAt: string | null; transcriptBytes: number | null; sessionBytes: number | null }+type Target = Partial<RegisteredSession> & { agentId: string }+type StorageDeps = { now(): number; size(path: string): Promise<number | null>; transcript(path: string): Promise<number | null>; canonical(path: string): Promise<string>; session?(agent: Target): Promise<number | null> }/** Directory sizes are shared by path and read in a bounded queue, at most once* a minute. A process sample never waits for du, and failure is not a zero. */-export function createHarnessStorageReader(deps = {+export function createHarnessStorageReader(deps: StorageDeps = {now: Date.now,+ session: async agent => agent.engine ? sessionDataBytes(agent as RegisteredSession, sessionCheckpoints) : null,size: async (path: string): Promise<number | null> => {if (!isAbsolute(path) || path === '/') return nullconst { stdout } = await exec('du', ['-sk', '-P', path], { timeout: 2500, maxBuffer: 4096 })@@ -100,6 +106,7 @@ export function createHarnessStorageReader(deps = {canonical: async (path: string): Promise<string> => realpath(path),}) {const cache = new Map<string, { at: number; bytes: number | null; pending: boolean }>()+ const sessionCache = new Map<string, { at: number; bytes: number | null; pending: boolean }>()let active = 0const queue: Array<() => Promise<void>> = []function drain() {@@ -108,7 +115,10 @@ export function createHarnessStorageReader(deps = {void queue.shift()!().finally(() => { active--; drain() })}}- return async (agents: readonly Target[]): Promise<Map<string, StorageReading>> => {+ return async (agents: readonly Target[], invalidate = false): Promise<Map<string, StorageReading>> => {+ // A confirmed deletion changes ancestor totals too. Drop queued work and cached values;+ // the two already-running probes finish into detached entries, never into fresh readings.+ if (invalidate) { cache.clear(); sessionCache.clear(); queue.length = 0 }const canonical = new Map(await Promise.all([...new Set(agents.map(a => a.cwd).filter((p): p is string => !!p && isAbsolute(p) && p !== '/'))].map(async path => [path, await deps.canonical(path).catch(() => path)] as const)))const paths = new Set(canonical.values())@@ -124,6 +134,21 @@ export function createHarnessStorageReader(deps = {finally { target.at = deps.now(); target.pending = false }})}+ const sessionKey = (agent: Target) => JSON.stringify([agent.agentId, agent.engine, agent.sessionId, agent.transcriptPath, agent.codexHome, agent.hermesHome])+ const sessionKeys = new Set(agents.map(sessionKey))+ for (const [key, entry] of sessionCache) if (!sessionKeys.has(key) && !entry.pending) sessionCache.delete(key)+ if (deps.session) for (const agent of agents) {+ const key = sessionKey(agent)+ let entry = sessionCache.get(key)+ if (entry?.pending || entry && deps.now() - entry.at < 60_000) continue+ if (!entry) { entry = { at: 0, bytes: null, pending: false }; sessionCache.set(key, entry) }+ entry.pending = true+ const target = entry+ queue.push(async () => {+ try { target.bytes = await deps.session!(agent) } catch { target.bytes = null }+ finally { target.at = deps.now(); target.pending = false }+ })+ }drain()const result = new Map<string, StorageReading>()await Promise.all(agents.map(async agent => {@@ -131,7 +156,7 @@ export function createHarnessStorageReader(deps = {const workspace = workspacePath ? cache.get(workspacePath) : nullconst transcriptBytes = agent.transcriptPath ? await deps.transcript(agent.transcriptPath).catch(() => null) : nullresult.set(agent.agentId, { workspaceBytes: workspace?.bytes ?? null, workspacePath,- workspaceSampledAt: workspace?.at ? new Date(workspace.at).toISOString() : null, transcriptBytes })+ workspaceSampledAt: workspace?.at ? new Date(workspace.at).toISOString() : null, transcriptBytes, sessionBytes: sessionCache.get(sessionKey(agent))?.bytes ?? null })}))return result}diff --git a/cli/src/lib/purgeAgentService.spec.ts b/cli/src/lib/purgeAgentService.spec.tsnew file mode 100644index 000000000..cc2501662--- /dev/null+++ b/cli/src/lib/purgeAgentService.spec.ts@@ -0,0 +1,171 @@+import { existsSync, linkSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { registry, type RegisteredSession } from './registry.js'+import { StoppedAgentStore } from './stoppedAgents.js'+import { SessionCheckpointStore } from './sessionCheckpoint.js'+import { PurgeAgentService, inspectNativeHistory, eraseNativeHistory, sessionDataBytes, type PurgeRequest } from './purgeAgentService.js'+import { builtinSqlite } from './sqliteRead.js'+import type { StopAgentOptions } from './stopAgentService.js'+import * as worktrees from './worktreeDeletion.js'++let root: string, session: RegisteredSession, stopped: StoppedAgentStore, checkpoints: SessionCheckpointStore+let service: PurgeAgentService, target: Omit<PurgeRequest, 'mode'>, now: number+let stop = vi.fn<(id: string, options: StopAgentOptions) => Promise<void>>()+let deleted = vi.fn<(session: RegisteredSession) => void>()+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'harness-purge-'))+ const codexHome = join(root, 'profile'), cwd = join(root, 'project')+ mkdirSync(join(codexHome, 'sessions'), { recursive: true }); mkdirSync(cwd)+ session = registry.openPendingAgent({ engine: 'codex', cwd, codexHome, runtimes: [{ backend: 'tmux', paneId: '%77' }] })!+ Object.assign(session, { sessionId: 'selected-session', launch: { state: 'ready' }, transcriptPath: join(codexHome, 'sessions', 'selected-session.jsonl') })+ writeFileSync(session.transcriptPath!, 'selected conversation')+ writeFileSync(join(codexHome, 'sessions', 'other.jsonl'), 'another conversation')+ writeFileSync(join(cwd, 'project.txt'), 'project files stay')+ stopped = new StoppedAgentStore(join(root, 'stopped'))+ checkpoints = new SessionCheckpointStore(join(root, 'checkpoints'))+ stop = vi.fn(async (id, options) => {+ expect(options.current?.()).toBe(true)+ stopped.save(registry.byAgent(id)!)+ registry.removeAgent(id)+ })+ deleted = vi.fn(); now = 1000+ service = new PurgeAgentService({ live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stopped.list()],+ stopped, checkpoints, stop, restarting: () => false, deleted, now: () => now })+ target = { agentId: session.agentId, sessionId: session.sessionId, createdAt: session.registeredAt }+})+afterEach(() => { for (const row of registry.list()) registry.removeAgent(row.agentId); rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks() })+const review = () => service.request({ ...target, mode: 'inspect' })+const remove = (reviewId: unknown) => service.request({ ...target, mode: 'delete', reviewId: String(reviewId) })++it('previews without stopping, then deletes only reviewed history and checkpoints', async () => {+ await checkpoints.save(session, { screen: 'saved terminal' })+ const files = checkpoints.deletionFiles(session)+ const plan = await review()+ expect(plan.sessionBytes).toBe(await sessionDataBytes(session, checkpoints))+ expect(plan.sessionBytes).toBeGreaterThan(0)+ expect(stop).not.toHaveBeenCalled()+ expect(await remove(plan.reviewId)).toMatchObject({ deleted: true, workspaceKept: true })+ expect(existsSync(session.transcriptPath!)).toBe(false)+ expect(files.every(path => !existsSync(path))).toBe(true)+ expect(existsSync(join(session.codexHome!, 'sessions', 'other.jsonl'))).toBe(true)+ expect(existsSync(join(session.cwd!, 'project.txt'))).toBe(true)+ expect(stopped.get(session.agentId)).toBeNull()+ expect(deleted).toHaveBeenCalledOnce()+ expect(await remove(plan.reviewId)).toHaveProperty('error')+ expect(stop).toHaveBeenCalledOnce()+})+it('rejects an absent, expired, rotated or replaced review before stopping', async () => {+ expect(await remove('never-reviewed')).toHaveProperty('error')+ const expired = await review(); now += 120_001+ expect(await remove(expired.reviewId)).toHaveProperty('error')+ const rotated = await review(); session.sessionId = 'replacement'+ expect(await remove(rotated.reviewId)).toHaveProperty('error')+ session.sessionId = target.sessionId!+ const replaced = await review(); session.cwd = root+ expect(await remove(replaced.reviewId)).toHaveProperty('error')+ expect(stop).not.toHaveBeenCalled()+ expect(existsSync(session.transcriptPath!)).toBe(true)+})+it('keeps history if stopping fails, another harness uses it, or the file was replaced', async () => {+ const plan = await review()+ stop.mockRejectedValueOnce(new Error('process still alive'))+ expect(await remove(plan.reviewId)).toHaveProperty('error')+ expect(existsSync(session.transcriptPath!)).toBe(true)+ const other = { ...session, agentId: 'other-agent' }+ stopped.save(other)+ expect(await review()).toMatchObject({ error: 'DELETE_REFUSED', detail: expect.stringContaining('Another harness') })+ stopped.remove(other.agentId)+ const changed = await review()+ renameSync(session.transcriptPath!, session.transcriptPath! + '.old')+ writeFileSync(session.transcriptPath!, 'different file')+ expect(await remove(changed.reviewId)).toMatchObject({ error: 'DELETE_REFUSED', stopped: true })+ expect(existsSync(session.transcriptPath!)).toBe(true)+ expect(deleted).not.toHaveBeenCalled()+})+it('refuses symlinks, hard links, foreign conversation names and monitor deletion', async () => {+ const original = session.transcriptPath!+ renameSync(original, original + '.old'); symlinkSync(original + '.old', original)+ expect(await review()).toHaveProperty('error')+ rmSync(original); linkSync(original + '.old', original)+ expect(await review()).toHaveProperty('error')+ rmSync(original); renameSync(original + '.old', original)+ session.transcriptPath = join(session.codexHome!, 'sessions', 'other.jsonl')+ expect(await review()).toHaveProperty('error')+ session.transcriptPath = original; session.dsh = 'autonomous/harness-monitor'+ expect(await review()).toHaveProperty('error')+ expect(stop).not.toHaveBeenCalled()+})+it('can explicitly review remaining checkpoints after an interrupted partial deletion', async () => {+ await checkpoints.save(session, { screen: 'keep until confirmed' })+ stopped.save(session); registry.removeAgent(session.agentId)+ rmSync(session.transcriptPath!)+ const plan = await review()+ expect(plan.reviewId).toBeTypeOf('string')+ expect(await remove(plan.reviewId)).toMatchObject({ deleted: true })+ expect(stop).not.toHaveBeenCalled()+ expect(checkpoints.deletionFiles(session)).toEqual([])+})+it('binds worktree deletion to the reviewed path and dirty consent, blocking concurrent lifecycle work', async () => {+ const path = join(root, 'temporary')+ const inspect = vi.spyOn(worktrees, 'inspectWorktree').mockResolvedValue({ path, main: session.cwd!, branch: 'feature', head: 'commit', bytes: 1e9, dirty: true, changes: ['?? draft'], signature: 'review', dev: 1, ino: 2 })+ const erase = vi.spyOn(worktrees, 'removeReviewedWorktree').mockImplementation(async () => {+ expect(service.busy(session.agentId)).toBe(true)+ expect(service.blocksFolder(join(path, 'src'))).toBe(true)+ expect(stopped.beginResume(session.agentId)).toBeNull()+ })+ const plan = await service.worktreeRequest({ ...target, mode: 'inspect' })+ expect(stop).not.toHaveBeenCalled()+ expect(await service.worktreeRequest({ ...target, mode: 'delete', reviewId: String(plan.reviewId), path: session.cwd!, discardChanges: true })).toHaveProperty('error')+ const next = await service.worktreeRequest({ ...target, mode: 'inspect' })+ expect(await service.worktreeRequest({ ...target, mode: 'delete', reviewId: String(next.reviewId), path })).toHaveProperty('error')+ expect(stop).not.toHaveBeenCalled()+ const final = await service.worktreeRequest({ ...target, mode: 'inspect' })+ expect(await service.worktreeRequest({ ...target, mode: 'delete', reviewId: String(final.reviewId), path, discardChanges: true })).toMatchObject({ deleted: true, historyKept: true, branchKept: true })+ expect(erase).toHaveBeenCalledOnce()+ expect(existsSync(session.transcriptPath!)).toBe(true)+ expect(stopped.get(session.agentId)).not.toBeNull()+ expect(service.busy(session.agentId)).toBe(false)+ expect(service.blocksFolder(path)).toBe(false)+ expect(deleted).not.toHaveBeenCalled()+ inspect.mockRestore(); erase.mockRestore()+})++describe('shared native databases', () => {+ const dbFixture = () => {+ const home = join(root, 'hermes'); mkdirSync(home)+ const Database = builtinSqlite()!+ const db = new Database(join(home, 'state.db'), { readOnly: false })+ db.exec("CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT); CREATE TABLE messages(id INTEGER PRIMARY KEY, session_id TEXT REFERENCES sessions(id), content TEXT); INSERT INTO sessions VALUES ('selected-session', NULL), ('keep', NULL); INSERT INTO messages VALUES (1, 'selected-session', 'remove'), (2, 'keep', 'retained');")+ Object.assign(session, { engine: 'hermes', hermesHome: home, transcriptPath: null })+ return db+ }+ it('deletes only one conversation atomically, retaining the shared database and other sessions', async () => {+ const db = dbFixture()+ try {+ const history = await inspectNativeHistory(session)+ expect(history.bytes).toBeGreaterThan(0)+ await eraseNativeHistory(history)+ expect(db.prepare('SELECT id FROM sessions').all()).toEqual([{ id: 'keep' }])+ expect(db.prepare('SELECT content FROM messages').all()).toEqual([{ content: 'retained' }])+ expect(existsSync(join(session.hermesHome!, 'state.db'))).toBe(true)+ } finally { db.close() }+ })+ it('refuses dependent conversations, new dependencies and changed schemas without partial deletion', async () => {+ const db = dbFixture()+ try {+ const history = await inspectNativeHistory(session)+ db.exec("INSERT INTO sessions VALUES ('child', 'selected-session')")+ await expect(eraseNativeHistory(history)).rejects.toThrow()+ await expect(inspectNativeHistory(session)).rejects.toThrow('depend')+ expect(db.prepare('SELECT id FROM messages').all()).toHaveLength(2)+ db.exec("DELETE FROM sessions WHERE id='child'")+ const next = await inspectNativeHistory(session)+ db.exec('CREATE TABLE added(id TEXT REFERENCES sessions(id) ON DELETE CASCADE)')+ await expect(eraseNativeHistory(next)).rejects.toThrow()+ await expect(inspectNativeHistory(session)).rejects.toThrow('Other engine data')+ expect(db.prepare('SELECT id FROM sessions').all()).toHaveLength(2)+ } finally { db.close() }+ })+})diff --git a/cli/src/lib/purgeAgentService.ts b/cli/src/lib/purgeAgentService.tsnew file mode 100644index 000000000..c1d36a21d--- /dev/null+++ b/cli/src/lib/purgeAgentService.ts@@ -0,0 +1,291 @@+/** Permanent, individually reviewed deletion. Project folders are never deletion targets. */+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { existsSync, lstatSync, realpathSync, unlinkSync } from 'node:fs'+import { basename, dirname, join, resolve, sep } from 'node:path'+import { env } from '../config/env.js'+import { hermesDbPath } from '../engines/hermes/home.js'+import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'+import { builtinSqlite, sqliteReadAll } from './sqliteRead.js'+import type { StoppedAgentStore } from './stoppedAgents.js'+import type { SessionCheckpointStore } from './sessionCheckpoint.js'+import type { StopAgentOptions } from './stopAgentService.js'+import { inspectWorktree, removeReviewedWorktree, type WorktreeReview } from './worktreeDeletion.js'++const exec = promisify(execFile)+const identity = (s: RegisteredSession) => JSON.stringify([s.agentId, s.engine, s.sessionId,+ s.registeredAt, s.cwd, s.codexHome, s.hermesHome, s.transcriptPath, s.processIdentity])+const conversation = (s: RegisteredSession) => JSON.stringify([s.engine, s.codexHome, s.hermesHome, s.sessionId])+const fail = (message: string): never => { throw new Error(message) }+type File = { path: string; dev: number; ino: number; bytes: number }+type History = { file?: File; missingFile?: string; database?: string; databaseFile?: File; statements?: string[]; bytes: number | null }+const lit = (value: string) => "'" + value.replace(/'/g, "''") + "'"++function file(path: string): File {+ const info = lstatSync(path)+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1+ || (process.getuid && info.uid !== process.getuid())) fail('The session data is not a private regular file. Nothing was deleted.')+ return { path: realpathSync(path), dev: info.dev, ino: info.ino, bytes: Number.isFinite(info.blocks) ? info.blocks * 512 : info.size }+}++/** Known native history layouts only. A shared database is never removed or vacuumed. */+export async function inspectNativeHistory(s: RegisteredSession): Promise<History> {+ if (!s.sessionId || s.engine === 'terminal') return { bytes: 0 }+ if (engineKeepsTranscriptFile(s.engine)) {+ const path = s.transcriptPath+ if (!path || !validTranscriptPath(s.engine, path, s.codexHome ?? undefined, true)) {+ return fail('The conversation file could not be verified. Refresh before deleting this harness.')+ }+ const name = basename(path), id = s.sessionId+ if (!(basename(dirname(path)) === id || name === id + '.jsonl' || name === id + '.json'+ || name.endsWith('-' + id + '.jsonl') || name.endsWith('_' + id + '.jsonl'))) {+ return fail('The conversation file does not match this harness. Nothing was deleted.')+ }+ // An interrupted deletion can leave checkpoints after the native file has gone.+ // Review the remaining files again, but never delete a newly recreated native file.+ if (!existsSync(path)) return { missingFile: join(realpathSync(dirname(path)), name), bytes: 0 }+ const target = file(path)+ return { file: target, bytes: target.bytes }+ }+ let database: string, sessionTable: string, children: [string, string][]+ const id = lit(s.sessionId)+ switch (s.engine) {+ case 'opencode': case 'kilo':+ database = s.engine === 'opencode' ? join(env.OPENCODE_DATA_DIR, 'opencode.db') : join(env.KILO_DATA_DIR, 'kilo.db')+ sessionTable = 'session'+ children = [['part', `message_id IN (SELECT id FROM message WHERE session_id = ${id})`], ['message', `session_id = ${id}`]]+ break+ case 'hermes':+ database = hermesDbPath(s.hermesHome ?? env.HERMES_HOME)+ sessionTable = 'sessions'; children = [['messages', `session_id = ${id}`]]+ break+ case 'devin':+ database = join(env.DEVIN_HOME, 'sessions.db')+ sessionTable = 'sessions'; children = [['message_nodes', `session_id = ${id}`]]+ break+ default: return fail('This engine does not support verified history deletion yet.')+ }+ const databaseFile = file(database)+ const query = async (sql: string) => {+ const result = await sqliteReadAll(database, sql)+ if (!result.ok) return fail('The engine history could not be verified. Nothing was deleted.')+ return result.rows+ }+ if (s.engine === 'opencode' && (await query("SELECT name FROM sqlite_master WHERE type='table' AND name='session_v2'")).length+ && (await query(`SELECT id FROM session_v2 WHERE id = ${id}`)).length) {+ sessionTable = 'session_v2'; children = [['session_message', `session_id = ${id}`]]+ }+ await query(`SELECT id FROM ${sessionTable} WHERE id = ${id}`)+ if (!builtinSqlite()) await exec('sqlite3', ['--version'], { timeout: 2500, maxBuffer: 4096 })+ const allowedTables = new Set([sessionTable, ...children.map(([table]) => table)])+ if ((await query("SELECT name, tbl_name FROM sqlite_master WHERE type='trigger'")).some(t => allowedTables.has(String(t.tbl_name)))) {+ return fail('This engine uses history triggers that Harness cannot safely verify. Use the engine to delete its conversation.')+ }+ for (const table of await query("SELECT name FROM sqlite_master WHERE type='table'")) {+ const name = String(table.name)+ if (allowedTables.has(name)) continue+ const references = await query(`PRAGMA foreign_key_list("${name.replace(/"/g, '""')}")`)+ if (references.some(r => allowedTables.has(String(r.table)))) {+ return fail('Other engine data references this conversation store. Use the engine to delete its conversation.')+ }+ }+ // A native session can parent other conversations. Refuse rather than cascade into them.+ const columns = await query(`PRAGMA table_info(${sessionTable})`)+ const schemaVersion = Number((await query('PRAGMA schema_version'))[0]?.schema_version)+ if (!Number.isInteger(schemaVersion)) return fail('The engine history schema could not be verified.')+ const guards: string[] = [`INSERT INTO purge_guard SELECT 0 FROM pragma_schema_version WHERE schema_version <> ${schemaVersion};`]+ for (const parent of ['parent_id', 'parent_session_id']) if (columns.some(c => c.name === parent)) {+ const predicate = `${parent} = ${id} AND id <> ${id}`+ if ((await query(`SELECT id FROM ${sessionTable} WHERE ${predicate} LIMIT 1`)).length) {+ return fail('Other conversations depend on this session. Delete those through the engine before deleting this harness.')+ }+ guards.push(`INSERT INTO purge_guard SELECT 0 FROM ${sessionTable} WHERE ${predicate};`)+ }+ // Prepare every required table before asking to stop anything. Unknown schemas fail closed.+ for (const [table, where] of children) await query(`SELECT 1 FROM ${table} WHERE ${where} LIMIT 1`)+ let bytes = 0+ for (const [table, where] of [[sessionTable, `id = ${id}`], ...children]) {+ const fields = await query(`PRAGMA table_info(${table})`)+ const lengths = fields.map(c => `length(CAST(COALESCE("${String(c.name).replace(/"/g, '""')}", '') AS BLOB))`).join(' + ')+ const size = await query(`SELECT COALESCE(SUM(${lengths}), 0) AS bytes FROM ${table} WHERE ${where}`)+ bytes += Number(size[0]?.bytes ?? 0)+ }+ return { database, databaseFile, bytes, statements: [+ 'CREATE TEMP TABLE purge_guard (ok INTEGER CHECK(ok = 1));', ...guards,+ ...children.map(([table, where]) => `DELETE FROM ${table} WHERE ${where};`),+ `DELETE FROM ${sessionTable} WHERE id = ${id};`,+ ] }+}++export async function eraseNativeHistory(history: History): Promise<number> {+ if (history.missingFile && existsSync(history.missingFile)) fail('The conversation file was recreated. Review deletion again.')+ if (history.file) {+ const current = file(history.file.path)+ if (current.dev !== history.file.dev || current.ino !== history.file.ino) fail('The conversation file changed. Refresh and review deletion again.')+ unlinkSync(current.path)+ return current.bytes+ }+ if (history.database) {+ const current = file(history.database)+ if (current.dev !== history.databaseFile?.dev || current.ino !== history.databaseFile?.ino) fail('The engine history store changed. Review deletion again.')+ const sql = ['PRAGMA busy_timeout=1000;', 'PRAGMA foreign_keys=ON;', 'BEGIN IMMEDIATE;', ...history.statements!, 'COMMIT;'].join('\n')+ const Database = builtinSqlite()+ if (Database) {+ const db = new Database(history.database, { readOnly: false })+ try { db.exec(sql) } finally { db.close() }+ } else {+ // -bail rolls back on a schema, constraint or lock failure. Never vacuum a shared store.+ await exec('sqlite3', ['-batch', '-bail', history.database, sql], { timeout: 15_000, maxBuffer: 4096 })+ }+ }+ return 0+}++export async function sessionDataBytes(s: RegisteredSession, checkpoints: SessionCheckpointStore): Promise<number | null> {+ try {+ const history = await inspectNativeHistory(s)+ if (history.bytes == null) return null+ return history.bytes + checkpoints.deletionFiles(s).reduce((n, path) => n + file(path).bytes, 0)+ } catch { return null }+}++export interface PurgeRequest { agentId: string; sessionId: string | null; createdAt: number; mode: 'inspect' | 'delete'; reviewId?: string }+export interface PurgeDeps {+ live(id: string): RegisteredSession | undefined+ sessions(): RegisteredSession[]+ stopped: StoppedAgentStore+ checkpoints: SessionCheckpointStore+ stop(id: string, options: StopAgentOptions): Promise<void>+ restarting(id: string): boolean+ deleted(session: RegisteredSession): void+ inspect?: typeof inspectNativeHistory+ erase?: typeof eraseNativeHistory+ now?: () => number+}++export class PurgeAgentService {+ private readonly reviews = new Map<string, { session: RegisteredSession; signature: string; expires: number; history: History }>()+ private readonly jobs = new Set<string>()+ private readonly worktreeJobs = new Map<string, string>()+ private readonly worktreeReviews = new Map<string, { session: RegisteredSession; signature: string; expires: number; worktree: WorktreeReview }>()+ constructor(private readonly deps: PurgeDeps) {}+ busy(id: string): boolean { return this.jobs.has(id) }+ blocksFolder(cwd: string | null | undefined): boolean {+ if (!cwd) return false+ let path: string+ try { path = realpathSync(cwd) } catch { path = resolve(cwd) }+ return [...this.worktreeJobs.values()].some(root => path === root || path.startsWith(root + sep) || root.startsWith(path + sep))+ }++ async worktreeRequest(request: PurgeRequest & { path?: string; discardChanges?: boolean }): Promise<Record<string, unknown>> {+ let stopped = false+ try {+ if (this.busy(request.agentId)) throw new Error('Wait for the current harness operation to finish.')+ const now = this.deps.now?.() ?? Date.now()+ for (const [id, review] of this.worktreeReviews) if (review.expires <= now) this.worktreeReviews.delete(id)+ const current = this.current(request, false)+ if (request.mode === 'inspect') {+ const signature = identity(current), worktree = await inspectWorktree(current, this.deps.sessions())+ if (identity(this.current(request, false)) !== signature) throw new Error('The harness changed. Review its worktree again.')+ const reviewId = randomUUID()+ if (this.worktreeReviews.size >= 64) this.worktreeReviews.delete(this.worktreeReviews.keys().next().value!)+ this.worktreeReviews.set(reviewId, { session: { ...current }, signature, worktree, expires: now + 120_000 })+ return { reviewId, worktree }+ }+ const review = this.worktreeReviews.get(request.reviewId ?? '')+ this.worktreeReviews.delete(request.reviewId ?? '')+ if (!review || review.signature !== identity(current) || request.path !== review.worktree.path) {+ throw new Error('Confirm the reviewed worktree path before deleting it.')+ }+ if (review.worktree.dirty && request.discardChanges !== true) throw new Error('Confirm discarding uncommitted files before deleting this worktree.')+ this.jobs.add(request.agentId)+ this.worktreeJobs.set(request.agentId, review.worktree.path)+ try {+ if (this.deps.live(request.agentId)) await this.deps.stop(request.agentId, { current: () => {+ const live = this.deps.live(request.agentId)+ return !!live && identity(live) === review.signature+ } })+ if (this.deps.live(request.agentId)) throw new Error('The harness did not stop. Its worktree was kept.')+ stopped = true+ const saved = this.current(request, false), reservation = this.deps.stopped.beginResume(request.agentId)+ if (!reservation) throw new Error('Another operation is using this harness. Its worktree was kept.')+ try { await removeReviewedWorktree(review.worktree, saved, this.deps.sessions(), request.discardChanges === true) }+ finally { this.deps.stopped.finishResume(request.agentId, reservation) }+ return { deleted: true, path: review.worktree.path, historyKept: true, branchKept: true }+ } finally { this.jobs.delete(request.agentId); this.worktreeJobs.delete(request.agentId) }+ } catch (error) {+ return { error: 'WORKTREE_DELETE_REFUSED', stopped, detail: (error instanceof Error ? error.message : 'The worktree could not be deleted.')+ + (stopped ? ' The harness is stopped. Review its worktree again before retrying.' : '') }+ }+ }++ private current(request: PurgeRequest, deletingHistory = true): RegisteredSession {+ const s = this.deps.live(request.agentId) ?? this.deps.stopped.get(request.agentId)+ if (!s || (s.sessionId || null) !== request.sessionId || s.registeredAt !== request.createdAt) return fail('This harness changed. Refresh and review deletion again.')+ if (s.dsh === 'autonomous/harness-monitor' || s.launch?.state === 'starting') return fail('This harness cannot be deleted from this monitor.')+ if (this.deps.restarting(s.agentId)) return fail('Wait for the current harness operation to finish, then try again.')+ if (deletingHistory && s.sessionId && this.deps.sessions().some(other => other.agentId !== s.agentId && other.sessionId === s.sessionId)) {+ return fail('Another harness uses this conversation. Its shared history cannot be deleted here.')+ }+ return s+ }++ async request(request: PurgeRequest): Promise<Record<string, unknown>> {+ let stopped = false+ try {+ if (this.busy(request.agentId)) return { error: 'DELETE_IN_PROGRESS', detail: 'This harness is already being deleted.' }+ const now = this.deps.now?.() ?? Date.now()+ for (const [id, review] of this.reviews) if (review.expires <= now) this.reviews.delete(id)+ const current = this.current(request)+ if (request.mode === 'inspect') {+ const signature = identity(current)+ const history = await (this.deps.inspect ?? inspectNativeHistory)(current)+ if (identity(this.current(request)) !== signature) return fail('The harness changed while checking its data. Try again.')+ const checkpointBytes = this.deps.checkpoints.deletionFiles(current).reduce((n, path) => n + file(path).bytes, 0)+ const reviewId = randomUUID()+ if (this.reviews.size >= 64) this.reviews.delete(this.reviews.keys().next().value!)+ this.reviews.set(reviewId, { session: { ...current }, signature, history, expires: now + 120_000 })+ return { reviewId, sessionBytes: history.bytes == null ? null : history.bytes + checkpointBytes,+ sharedStore: !!history.database, workspaceKept: true, workspacePath: current.cwd }+ }+ const review = this.reviews.get(request.reviewId ?? '')+ this.reviews.delete(request.reviewId ?? '')+ if (!review || review.signature !== identity(current)) return fail('The deletion review expired or changed. Review this harness again.')+ this.jobs.add(request.agentId)+ try {+ if (this.deps.live(request.agentId)) {+ await this.deps.stop(request.agentId, { current: () => {+ const live = this.deps.live(request.agentId)+ return !!live && identity(live) === review.signature+ } })+ }+ if (this.deps.live(request.agentId)) return fail('The harness did not stop. No session data was deleted.')+ stopped = true+ const saved = this.current(request)+ if (conversation(saved) !== conversation(review.session) || saved.transcriptPath !== review.session.transcriptPath) {+ return fail('The saved conversation changed while stopping. Review it before deleting.')+ }+ // Stop has saved its final archive. Reserve it while asynchronous native DB deletion runs.+ const reservation = this.deps.stopped.beginResume(request.agentId)+ if (!reservation) return fail('Another operation is using this saved harness. Nothing was deleted.')+ try {+ const files = this.deps.checkpoints.deletionFiles(saved).map(file)+ let freedBytes = await (this.deps.erase ?? eraseNativeHistory)(review.history)+ for (const target of files) {+ const current = file(target.path)+ if (current.dev !== target.dev || current.ino !== target.ino) return fail('Saved session data changed. Some data may already have been deleted; refresh to check.')+ unlinkSync(target.path); freedBytes += current.bytes+ }+ this.deps.deleted(saved)+ this.deps.stopped.remove(request.agentId)+ return { deleted: true, freedBytes, sharedStore: !!review.history.database, workspaceKept: true }+ } finally { this.deps.stopped.finishResume(request.agentId, reservation) }+ } finally { this.jobs.delete(request.agentId) }+ } catch (error) {+ return { error: 'DELETE_REFUSED', stopped,+ detail: (error instanceof Error ? error.message : 'Could not delete this harness.')+ + (stopped ? ' The harness is stopped; refresh before trying again.' : '') }+ }+ }+}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex cbb80a09d..87a917455 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -734,14 +734,15 @@ export function engineKeepsTranscriptFile(engine: AgentEngine): boolean {return TRANSCRIPT_ROOT[engine] !== null}-export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string): boolean {+export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string, allowMissing = false): boolean {const rootFor = TRANSCRIPT_ROOT[engine]if (!rootFor) return falsetry {- const actual = realpathSync(filePath)+ const missing = allowMissing && !existsSync(filePath)+ const actual = missing ? join(realpathSync(dirname(filePath)), basename(filePath)) : realpathSync(filePath)const root = realpathSync(rootFor(codexHome))- const st = statSync(actual)- if (!st.isFile() || !isWithin(root, actual)) return false+ const st = statSync(missing ? dirname(actual) : actual)+ if (!(missing ? st.isDirectory() : st.isFile()) || !isWithin(root, actual)) return falseif (engine === 'cursor') {const id = basename(actual).replace(/\.jsonl$/, '')if (!id || basename(dirname(actual)) !== id || basename(dirname(dirname(actual))) !== 'agent-transcripts') return false@@ -2015,6 +2016,15 @@ class Registry {return s}+ deleteSavedNames(ids: string[]): void {+ secureStateDirectory(env.ADAPTER_DATA_DIR)+ let existing: Record<string, unknown> = {}+ try { existing = JSON.parse(readPrivateStateFile(NAMES_FILE, 1024 * 1024)) }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }+ for (const id of ids) { delete existing[id]; NAME_OVERRIDES.delete(id) }+ atomicWriteJson(NAMES_FILE, { ...existing, ...Object.fromEntries(NAME_OVERRIDES) })+ }+list(): RegisteredSession[] {return Array.from(this.agents.values())}diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.tsindex e7199da43..4015182b2 100644--- a/cli/src/lib/sessionCheckpoint.ts+++ b/cli/src/lib/sessionCheckpoint.ts@@ -1,5 +1,5 @@/** Disk checkpoints made only when closing a session, never by a resource sampler. */-import { constants } from 'node:fs'+import { constants, existsSync } from 'node:fs'import { chmod, copyFile, lstat, open, rename, rm, stat } from 'node:fs/promises'import { createHash, randomUUID } from 'node:crypto'import { dirname, join } from 'node:path'@@ -67,6 +67,22 @@ export class SessionCheckpointStore {return createHash('sha256').update(JSON.stringify([s.agentId, s.engine, s.codexHome ?? null, s.sessionId])).digest('hex')}+ /** Exact files for this conversation only; no workspace or directory removal. */+ deletionFiles(s: RegisteredSession): string[] {+ if (!existsSync(this.directory)) return []+ secureStateDirectory(this.directory, false)+ const key = this.key(s), manifest = join(this.directory, `${key}.json`)+ const files = [join(this.directory, `${key}.screen.json`)].filter(existsSync)+ if (!existsSync(manifest)) return files+ const saved = JSON.parse(readPrivateStateFile(manifest, 16384)) as Checkpoint+ if (saved.version !== 1 || saved.agentId !== s.agentId || saved.sessionId !== s.sessionId+ || saved.engine !== s.engine || !previousFileSafe(saved.file) || !saved.file.startsWith(key + '-')) {+ throw new Error('The saved checkpoint does not match this harness.')+ }+ const history = join(this.directory, saved.file)+ return [...files, ...(existsSync(history) ? [history] : []), manifest]+ }+async save(s: RegisteredSession, options: { screen?: string | null } = {}): Promise<void> {secureStateDirectory(dirname(this.directory))secureStateDirectory(this.directory)diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.tsindex 1b2b9b5c8..8142c62eb 100644--- a/cli/src/lib/sessionSearch/indexer.spec.ts+++ b/cli/src/lib/sessionSearch/indexer.spec.ts@@ -39,6 +39,17 @@ function setup(initial: string, agents?: () => string[]) {}describe('SessionSearchIndex', () => {+ it('does not resurrect deleted conversation history from an in-flight pass or stale source list', async () => {+ const { index, found, settle, store } = setup(prompt('purge search history', 0) + answer('sensitive fixture', 1))+ await settle()+ expect(found('sensitive')).toEqual(['s1'])+ const pass = index.pass({ agentId: 'agent-1', sessionId: 's1', engine: 'claude', transcriptPath: store.session('s1')!.path, header: 'stale row', changedAt: 2 })+ index.deleteHistory('s1')+ await pass+ await settle()+ expect(found('sensitive')).toEqual([])+ expect(store.session('s1')).toBeUndefined()+ })it('indexes a transcript on the first sweep and picks up only what was added since', async () => {const { path, store, found, settle } = setup(prompt('why does the dial scroll jump', 0) + answer('The delta is doubled.', 1))await settle()diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.tsindex 84b2f2788..33c984413 100644--- a/cli/src/lib/sessionSearch/indexer.ts+++ b/cli/src/lib/sessionSearch/indexer.ts@@ -138,8 +138,18 @@ export class SessionSearchIndex {/** Callers waiting for a session's next pass (`tail`). */private readonly waiters = new Map<string, Array<() => void>>()+ private readonly deletedSessions = new Set<string>()+constructor(private readonly opts: SessionSearchIndexOptions) {}+ deleteHistory(sessionId: string): void {+ this.deletedSessions.add(sessionId)+ this.sources.delete(sessionId)+ this.queue.delete(sessionId)+ this.dirty.delete(sessionId)+ this.opts.store.removeSession(sessionId)+ }+/** The first sweep after `delayMs` (boot has other work), then one every `sweepEveryMs`. */start(delayMs = 15_000): void {const every = this.opts.sweepEveryMs ?? 10 * 60_000@@ -307,7 +317,7 @@ export class SessionSearchIndex {if (!force && Date.now() - this.sourcesReadAt < 5_000) returnconst next = new Map<string, SearchSource>()for (const source of this.opts.sources()) {- if (!source.sessionId) continue+ if (!source.sessionId || this.deletedSessions.has(source.sessionId)) continueconst known = next.get(source.sessionId)// One session can be listed live and stopped at once: the fresher record wins.if (!known || source.changedAt > known.changedAt) next.set(source.sessionId, source)@@ -318,6 +328,7 @@ export class SessionSearchIndex {/** One pass over one session: from where the last one stopped, or from the start. */async pass(source: SearchSource): Promise<void> {+ if (this.deletedSessions.has(source.sessionId)) returnconst store = this.opts.storeconst existing = store.session(source.sessionId)const dirty = this.dirty.delete(source.sessionId)@@ -329,6 +340,7 @@ export class SessionSearchIndex {if (!file || !source.transcriptPath || !normalize) {// Nothing to read (a terminal, a database-backed engine, a missing file): its name is still findable.if (existing?.header === header && existing.agentId === source.agentId) return+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession({sessionId: source.sessionId, agentId: source.agentId, engine: source.engine,path: existing?.path ?? source.transcriptPath ?? '', header,@@ -344,6 +356,7 @@ export class SessionSearchIndex {const samePath = existing?.path === pathif (samePath && existing.size === file.size && existing.mtime === mtime) {if (existing.header !== header || existing.agentId !== source.agentId) {+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession({ ...existing, header, agentId: source.agentId, ...externalFields(source, knownTitle) }, NO_TURN_DELETE, [])}return@@ -387,6 +400,7 @@ export class SessionSearchIndex {// a daemon stopped between them resumes there.for (let start = WRITE_BATCH; start < turns.length; start += WRITE_BATCH) {const next = turns[start]+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession({ ...session, size: next.offset, mtime: 0, resumeOffset: next.offset, resumeTurn: next.turn },start === WRITE_BATCH ? fromTurn : NO_TURN_DELETE,@@ -396,6 +410,7 @@ export class SessionSearchIndex {if (this.stopped) return}const written = Math.floor(Math.max(0, turns.length - 1) / WRITE_BATCH) * WRITE_BATCH+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession(session, written ? NO_TURN_DELETE : fromTurn, turns.slice(written))if (!resume) {this.opts.log?.(`[search] indexed ${source.sessionId.slice(0, 8)} · ${source.engine} · ${closed.length + (open ? 1 : 0)} turns · ${Math.round(file.size / 1024)} KB`)@@ -415,6 +430,7 @@ export class SessionSearchIndex {if (existing && !dirty && existing.mtime === stamp) {const again = source.external ? headed(existing.title ?? '') : { header: source.header }if (existing.header !== again.header || existing.agentId !== source.agentId) {+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession({ ...existing, ...again, agentId: source.agentId }, NO_TURN_DELETE, [])}return@@ -435,6 +451,7 @@ export class SessionSearchIndex {if (existing && existing.size === fingerprint && existing.mtime === stamp&& existing.header === head.header && existing.agentId === source.agentId) returnconst changed = !existing || existing.size !== fingerprint+ if (this.deletedSessions.has(source.sessionId)) returnstore.writeSession({sessionId: source.sessionId, agentId: source.agentId, engine: source.engine, path: '',...head, size: fingerprint, mtime: stamp, resumeOffset: 0, resumeTurn: 0,diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.tsindex e1e7bf192..b6eba9ada 100644--- a/cli/src/lib/stoppedAgents.ts+++ b/cli/src/lib/stoppedAgents.ts@@ -198,6 +198,15 @@ export class StoppedAgentStore {try { fsyncSync(fd) } finally { closeSync(fd) }}+ /** Permanent deletion is separate from Stop, which always retains this record. */+ remove(agentId: string): void {+ if (!SAFE_ID.test(agentId)) throw new Error('Invalid stopped harness identity.')+ if (!this.get(agentId)) return+ unlinkSync(join(this.directory, `${agentId}.json`))+ this.forgetCatalogRecord(agentId)+ this.syncDirectory()+ }+/** Suppress archives whose identity or conversation is already running. */available(live: readonly RegisteredSession[]): RegisteredSession[] {const ids = new Set(live.map(session => session.agentId))diff --git a/cli/src/lib/worktreeDeletion.spec.ts b/cli/src/lib/worktreeDeletion.spec.tsnew file mode 100644index 000000000..ca45918e4--- /dev/null+++ b/cli/src/lib/worktreeDeletion.spec.ts@@ -0,0 +1,71 @@+import { execFile } from 'node:child_process'+import { mkdir, mkdtemp, realpath, rm, stat, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import type { RegisteredSession } from './registry.js'+import { inspectWorktree, removeReviewedWorktree } from './worktreeDeletion.js'++const exec = promisify(execFile)+describe('explicit worktree deletion', { timeout: 30_000 }, () => {+ let root: string, repo: string, tree: string, session: RegisteredSession+ const git = async (cwd: string, ...args: string[]) => (await exec('git', ['-C', cwd,+ '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])).stdout.trim()+ const exists = (path: string) => stat(path).then(() => true, () => false)+ beforeEach(async () => {+ root = await realpath(await mkdtemp(join(tmpdir(), 'harness-worktree-delete-')))+ repo = join(root, 'project'); tree = join(root, 'temporary worktree ')+ await mkdir(repo)+ await git(repo, 'init', '--quiet', '-b', 'main')+ await writeFile(join(repo, 'source'), 'keep main')+ await writeFile(join(repo, '.gitignore'), 'node_modules/\n')+ await git(repo, 'add', '.')+ await git(repo, 'commit', '--quiet', '-m', 'initial')+ await git(repo, 'worktree', 'add', '--quiet', '-b', 'feature', tree)+ session = { agentId: 'selected', cwd: tree } as RegisteredSession+ })+ afterEach(() => rm(root, { recursive: true, force: true }))++ it('removes the reviewed linked checkout and ignored output, retaining main and its branch', async () => {+ await mkdir(join(tree, 'node_modules'))+ await writeFile(join(tree, 'node_modules', 'package'), 'temporary dependencies')+ await writeFile(join(tree, 'source'), 'committed feature')+ await git(tree, 'commit', '--quiet', '-am', 'feature work')+ const review = await inspectWorktree(session, [session])+ expect(review).toMatchObject({ path: tree, main: repo, branch: 'feature', dirty: false })+ expect(review.bytes).toBeGreaterThan(0)+ await removeReviewedWorktree(review, session, [session], false)+ expect(await exists(tree)).toBe(false)+ expect(await exists(join(repo, 'source'))).toBe(true)+ expect(await git(repo, 'show', 'feature:source')).toBe('committed feature')+ })+ it('refuses the main checkout, locked worktrees, overlapping harnesses and nested worktrees', async () => {+ await expect(inspectWorktree({ ...session, cwd: repo }, [session])).rejects.toThrow('main project')+ await git(repo, 'worktree', 'lock', tree)+ await expect(inspectWorktree(session, [session])).rejects.toThrow('locked')+ await git(repo, 'worktree', 'unlock', tree)+ await expect(inspectWorktree(session, [session, { ...session, agentId: 'saved', active: false }])).rejects.toThrow('Another harness')+ await git(repo, 'worktree', 'add', '--quiet', '-b', 'nested', join(tree, 'nested'))+ await expect(inspectWorktree(session, [session])).rejects.toThrow('Another Git worktree')+ })+ it('requires explicit consent for uncommitted files and refuses a stale review', async () => {+ const clean = await inspectWorktree(session, [session])+ await writeFile(join(tree, 'draft'), 'cannot recover')+ await expect(removeReviewedWorktree(clean, session, [session], true)).rejects.toThrow('changed')+ const dirty = await inspectWorktree(session, [session])+ expect(dirty.dirty).toBe(true)+ await expect(removeReviewedWorktree(dirty, session, [session], false)).rejects.toThrow('Confirm discarding')+ expect(await exists(tree)).toBe(true)+ await removeReviewedWorktree(dirty, session, [session], true)+ expect(await exists(tree)).toBe(false)+ })+ it('protects a detached unique commit and conversation data inside a worktree', async () => {+ await expect(inspectWorktree({ ...session, transcriptPath: join(tree, 'source') }, [session])).rejects.toThrow('history')+ await git(tree, 'checkout', '--detach')+ await writeFile(join(tree, 'source'), 'only here')+ await git(tree, 'commit', '--quiet', '-am', 'detached work')+ await expect(inspectWorktree(session, [session])).rejects.toThrow('no saved branch')+ expect(await exists(tree)).toBe(true)+ })+})diff --git a/cli/src/lib/worktreeDeletion.ts b/cli/src/lib/worktreeDeletion.tsnew file mode 100644index 000000000..106020697--- /dev/null+++ b/cli/src/lib/worktreeDeletion.ts@@ -0,0 +1,79 @@+/** Explicit cleanup of a linked Git worktree. Main checkouts and branches are never removed. */+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { lstat, realpath } from 'node:fs/promises'+import { basename, dirname, join, resolve, sep } from 'node:path'+import { createHash } from 'node:crypto'+import { env } from '../config/env.js'+import type { RegisteredSession } from './registry.js'++const exec = promisify(execFile)+const within = (parent: string, path: string) => parent === path || path.startsWith(parent + sep)+async function git(cwd: string, args: string[]): Promise<string> {+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete env[key]+ return (await exec('git', ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-C', cwd, ...args],+ { env, timeout: 30_000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 })).stdout.replace(/\r?\n$/, '')+}+export type WorktreeReview = {+ path: string; main: string; branch: string | null; head: string; bytes: number | null+ dirty: boolean; changes: string[]; signature: string; dev: number; ino: number+}++export async function inspectWorktree(s: RegisteredSession, sessions: readonly RegisteredSession[]): Promise<WorktreeReview> {+ if (!s.cwd) throw new Error('This harness has no working folder.')+ const root = await realpath(await git(s.cwd, ['rev-parse', '--show-toplevel']))+ const [folder, marker] = await Promise.all([lstat(root), lstat(join(root, '.git'))])+ const gitDir = await realpath(resolve(root, await git(root, ['rev-parse', '--git-dir'])))+ const common = await realpath(resolve(root, await git(root, ['rev-parse', '--git-common-dir'])))+ if (!folder.isDirectory() || !marker.isFile() || gitDir === common || basename(common) !== '.git') {+ throw new Error('This is the main project folder, not a temporary Git worktree. It cannot be deleted here.')+ }+ const main = dirname(common)+ if (within(root, main)) throw new Error('The main project is inside this folder. It cannot be deleted here.')+ const worktrees = (await git(main, ['worktree', 'list', '--porcelain', '-z'])).split('\0\0')+ const listed = worktrees.find(block => block.split('\0').includes('worktree ' + root))+ if (!listed || listed.split('\0').some(line => line === 'locked' || line.startsWith('locked ') || line.startsWith('prunable'))) {+ throw new Error('This worktree is locked or no longer registered. It cannot be deleted here.')+ }+ for (const block of worktrees) {+ const path = block.split('\0').find(line => line.startsWith('worktree '))?.slice(9)+ if (path && path !== root && within(root, await realpath(path).catch(() => resolve(path)))) {+ throw new Error('Another Git worktree is inside this folder. It cannot be removed here.')+ }+ }+ for (const other of sessions) {+ if (other.agentId === s.agentId || !other.cwd) continue+ const path = await realpath(other.cwd).catch(() => resolve(other.cwd!))+ if (within(root, path) || within(path, root)) throw new Error('Another harness uses this worktree or an overlapping folder. Its files must be kept.')+ }+ for (const protectedPath of [env.ADAPTER_DATA_DIR, env.CLAUDE_PROJECTS_DIR, env.CODEX_HOME,+ env.OPENCODE_DATA_DIR, env.KILO_DATA_DIR, env.HERMES_HOME, env.DEVIN_HOME, env.CURSOR_HOME,+ env.PI_HOME, env.COMMANDCODE_HOME, env.MUSE_HOME, env.GROK_HOME, env.AGY_HOME,+ env.COPILOT_HOME, env.AMP_SESSIONS_DIR, s.transcriptPath, s.codexHome, s.hermesHome]) {+ if (protectedPath && within(root, await realpath(protectedPath).catch(() => resolve(protectedPath)))) {+ throw new Error('Session history or shared application data is inside this worktree. It cannot be removed here.')+ }+ }+ const branch = await git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => null)+ if (!branch && await git(root, ['rev-list', '--count', 'HEAD', '--not', '--branches', '--remotes']) !== '0') {+ throw new Error('This detached worktree has commits with no saved branch. Create a branch before deleting it.')+ }+ const head = await git(root, ['rev-parse', 'HEAD'])+ const status = await git(root, ['status', '--porcelain', '--untracked-files=normal'])+ const size = await exec('du', ['-sk', '-P', root], { timeout: 2500, maxBuffer: 4096 }).catch(() => null)+ const kb = size && /^(\d+)\s/.exec(size.stdout)?.[1]+ return { path: root, main, branch, head, bytes: kb ? Number(kb) * 1024 : null,+ dirty: status.length > 0, changes: status.split('\n').filter(Boolean).slice(0, 12),+ signature: createHash('sha256').update(JSON.stringify([root, main, branch, head, status])).digest('hex'),+ dev: folder.dev, ino: folder.ino }+}++export async function removeReviewedWorktree(review: WorktreeReview, s: RegisteredSession, sessions: readonly RegisteredSession[], discardChanges: boolean): Promise<void> {+ const current = await inspectWorktree(s, sessions)+ if (current.path !== review.path || current.dev !== review.dev || current.ino !== review.ino || current.signature !== review.signature) {+ throw new Error('The worktree or its changes changed. Review it again before deleting.')+ }+ if (current.dirty && !discardChanges) throw new Error('Confirm discarding the listed uncommitted files before deleting this worktree.')+ await git(current.main, ['worktree', 'remove', ...(current.dirty && discardChanges ? ['--force'] : []), '--', current.path])+}diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.mdindex d82059655..6bb4346ab 100644--- a/desktop/design/desktop-design-system.md+++ b/desktop/design/desktop-design-system.md@@ -382,29 +382,17 @@ names truncate and retain their full-name tooltip. Keep effort in the terminal,and keep the icon targets clear at narrow widths. Tab-strip close behavior isseparate and remains hover-revealed.-**Focused workspace footer** — running harness count and attributable CPU/RAM/GPU/SSD across-connected owned machines, then subscription allowance used at the left; focused machine, project,-branch and PR at the right. Each context field keeps its action. Harness count and every resource-metric select the existing Harness Monitor tab or create it if absent. Process-tree CPU uses 100%-per core; GPU sums reported process utilization, which can exceed 100%. Shared servers count once. Unsupported GPU-attribution stays unknown. RAM/SSD are absolute, rounded whole MB/GB; shared/nested workspace-folders count once per machine. See [workspace status bar](workspace-status-bar.md) for accounting.-Titles stay quiet when several panes are visible. Do not repeat branches in pane headers or-model/effort in the footer. Context honors the selected status face, fields, colors and shell/-Powerline treatment. Recent-harness context uses its monochrome presentation.-Use whole figures, spaces of 0.75 character cells within components, and two cells between parts:-`Harnesses 118 CPU 20% RAM 10 GB GPU 10% SSD 1 GB Claude 100% Codex 90%`.-Labels and numbers use neutral readable ink; no severity color, dot separators, trailing plus or-decimal figures. Harness metrics show — when unavailable; partial totals show the available number-without a prefix, with coverage explained in the tooltip. Subscription figures mean allowance-used and preserve Models' deduplicated accounts, limiting window and-freshness rules. Hover explains scope and units. Clicking subscription usage opens Subscriptions-without switching a model. Narrow widths hide complete groups: SSD, then GPU, then RAM.--Companion and sharing controls follow usage. The companion uses the same gap between controls as-the resource and subscription groups; the gutter in its fixed slot replaces the preceding control's-trailing padding so the artwork has the same visible separation as text. See the full-[status bar contract](workspace-status-bar.md).+**Focused workspace footer** — only the open harness count at the left, such as `Harnesses 118`;+focused machine, project, branch and PR at the right. Count connected owned harnesses, including+idle and starting sessions. Clicking the count reuses Harness Monitor or creates it when absent.+The footer performs no resource polling. CPU, RAM, GPU, workspace/session storage and their detailed+accounting belong in the Monitor. Subscription usage stays available in Models/Subscriptions.++Labels use neutral readable ink. Preserve focused context actions and the selected status face,+fields, colors and shell/Powerline treatment. Companion and sharing controls follow the count;+the companion's fixed gutter replaces the preceding control's trailing padding. See the+[status bar contract](workspace-status-bar.md). Do not repeat branches in pane headers or model/effort+in the footer. Recent-harness context uses its monochrome presentation.**Settings, Store and supporting screens** — the same type, colors and controlsat page scale. Related settings use grouping and whitespace. Existing artwork,diff --git a/desktop/design/images/harness-monitor-storage.png b/desktop/design/images/harness-monitor-storage.pngnew file mode 100644index 000000000..d9331a824Binary files /dev/null and b/desktop/design/images/harness-monitor-storage.png differdiff --git a/desktop/design/images/harness-monitor-worktree-delete.png b/desktop/design/images/harness-monitor-worktree-delete.pngnew file mode 100644index 000000000..f6c640df9Binary files /dev/null and b/desktop/design/images/harness-monitor-worktree-delete.png differdiff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdindex de1b3942e..32e6c911e 100644--- a/desktop/design/workspace-status-bar.md+++ b/desktop/design/workspace-status-bar.md@@ -14,7 +14,7 @@ api ? web ⠹ blender ✓ + Search Bell (✿ Harnesspanes-Harnesses 118 CPU 20% RAM 10 GB GPU 10% SSD 1 GB Claude 100% Codex 90%+Harnesses 118M2 > project > branch > #439```@@ -22,15 +22,17 @@ The context follows the focused pane. The branch stays clickable in thefooter; pane headers do not repeat it. An empty New Tab keeps the footer whenthere are live sessions to inspect.-The left side shows open harnesses (including idle and starting sessions) and their CPU, RAM, GPU and SSD consumption across connected-owned machines, followed by subscription allowance used per account. The focused-pane context-remains at the right. Count each live session even when no tab currently displays it.+The left side shows only the number of open harnesses across connected owned machines, including+idle and starting sessions. Count each live session even when no tab currently displays it. The+focused-pane context remains at the right. Clicking Harnesses selects the existing Harness Monitor+across all tabs/machines, creating one only when absent.-Clicking Harnesses or any resource metric selects the existing Harness Monitor tab across all tabs-and machines. Create one only when absent. Clicking does not open a separate resource popover.-Saved sessions and open/resume actions belong in Open Harness (Cmd-P). The monitor itself starts-with only open sessions, sortable resource and AI metrics, an inspector and a visible × close-button on every row. Closing reviews one harness, ends its work and retains history and files.+Monitor starts with open sessions; a Stopped harnesses filter exposes retained work for cleanup.+Storage is shown as separate Workspace and Session data columns before RAM, CPU and GPU. Explicit+Stop Harness and Delete Harness buttons review one session. Stop retains history and files; Delete+Harness permanently removes the selected conversation data while keeping workspace files.+Inspect → Delete Worktree separately reviews its path, branch, size and uncommitted changes.+See [Harness Monitor](../../store/agents/harness-monitor/README.md) for accounting and safeguards.Use spaces of 0.75 character cells within components and two cells between complete groups,including the count. Adjacent controls contribute one cell of horizontal padding on each side;@@ -39,32 +41,13 @@ already has its own optical gutter. Do not add extra separation. The shared `worand `workspaceBarGroupGapCells` keep Flutter and native views aligned. Use neutralworkspace ink at every usage level. Do not pad numbers or add dots, decimal figures or plus suffixes.-CPU is the sum of attributable process-tree interval use; 100% is one core, so multicore and fleet-totals can exceed 100%. RAM is process-tree resident memory. Nested harness roots are excluded from-the parent and shared Codex servers count once; shared memory pages may still overlap. GPU uses-process GPU time per interval on supported macOS drivers and process utilization on Linux NVIDIA.-Multiple contexts/devices can exceed 100%. First samples and unavailable counters show —;-whole-host GPU activity is not a substitute for attribution. Cloud inference is not local GPU use.--RAM and SSD use rounded whole MB/GB, such as `RAM 10 GB` and `SSD 1 GB` (10.4 rounds to 10).-SSD means allocated workspace disk space, including existing files. Shared and nested canonical-folders count once per machine. It is not free space, capacity or a claim that every host uses an-SSD. Stopping a process keeps its files. Directory sizes use bounded reads cached for one minute.--Unknown readings show —, with valid zero preserved. Partial totals show the available number without-a prefix. The tooltip explains partial coverage, scope, units and shared accounting. Samples expire-after 45 seconds. The count and resource totals cover the same connected owned sessions and never-substitute whole-machine utilization.--Sample connected owners every fifteen seconds while the app is foregrounded. Clear readings and-stop polling when hidden; refresh on return. Coalesce process samples in the owning daemon, verify-PID birth identity and keep telemetry off the terminal-input queue. The viewer samples local-inventory every four seconds and linked machines every fifteen seconds while visible. Reading-token usage uses the existing incremental ledger and does not trigger a new transcript scan.--Native and Flutter footers share data, tooltips and button behavior. At narrow widths remove SSD,-then GPU, then RAM as complete groups, keeping CPU and the full tooltip. Subscription usage remains-visible in wide windows and accessible through Models at every size. Preserve focused context.+The footer reads existing live inventory and never polls resource metrics. The Monitor viewer samples+local inventory every four seconds and linked machines every fifteen seconds while visible, with+bounded storage work cached separately. Native and Flutter footers share the count, tooltip and+navigation. Keep the count usable at narrow widths and preserve focused context. Subscription usage+remains in Models/Subscriptions.++The captures below are historical and include resource groups that have since moved into Monitor.@@ -74,12 +57,10 @@ The previous capture below documents spacing; its whole-machine percentages have-Validation covers harness scope, shared/nested totals, unavailable/late responses, rounding, hidden-polling, tab reuse and native/Flutter clicks. Run `harness_resources_test.dart`,-`harness_monitor_test.dart` and `workspace_status_test.dart`. Set-`HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR` for Flutter fixtures and `HARNESS_RESOURCE_CAPTURE_DIR` for-native captures from `tool/check_swarm_titlebar.sh`. CLI ownership, telemetry and failure checks live-in `harnessResources.spec.ts` and `harnessTelemetry.spec.ts`.+Validation covers harness count, no footer resource polling, tab reuse, full 70/30 Monitor recovery,+and native/Flutter clicks. Run `harness_monitor_summary_test.dart`, `harness_monitor_test.dart` and+`workspace_status_test.dart`; set `HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR` for Flutter captures.+`tool/check_swarm_titlebar.sh` verifies AppKit layout and hidden legacy resource controls.The layout takes cues from [Stats' combined view](https://github.com/exelban/stats/blob/master/Stats/Views/CombinedView.swift)and [Mini widget](https://github.com/exelban/stats/blob/master/Kit/Widgets/Mini.swift): compact modulesdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 5c70e71df..8efb2bca8 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -53,7 +53,6 @@ import '../widgets/notification_inbox.dart';import '../widgets/workspace_notifications_button.dart';import '../state/harness_sessions.dart';import '../state/harness_monitor.dart';-import '../widgets/workspace_harness_resources.dart';import '../state/harness_activity.dart';import '../state/harness_attachments.dart';import '../state/harness_placement.dart';@@ -577,7 +576,8 @@ class _SwarmScreenState extends State<SwarmScreen> {app.deviceNavigationAllowed = _allowDeviceNavigation;app.deviceFormCommand = _deviceFormCommand;_pullRequest = WorkspacePullRequest(app)..addListener(_statusPrefsChanged);- _harnessMonitor = HarnessMonitor(app)..addListener(_monitorChanged);+ _harnessMonitor = HarnessMonitor(app, sampleResources: false)+ ..addListener(_monitorChanged);app.reviewSessionClose = _reviewSessionClose;app.changeCompanionAgent = _changeCompanionAgent;app.canChangeCompanionAgent = _canChangeCompanionAgent;@@ -1762,7 +1762,7 @@ class _SwarmScreenState extends State<SwarmScreen> {void _syncNative() {_syncMachines();- final monitor = _harnessMonitor.summary;+ final monitor = _harnessMonitor;final focused = WorkspacePaneContext.focused(app);final prefs = appearancePrefsStore.value.prompt;final parts = focused?.format(prefs);@@ -1799,19 +1799,6 @@ class _SwarmScreenState extends State<SwarmScreen> {'foreground': terminalTheme.foreground.toARGB32(),'selection': terminalTheme.selection.toARGB32(),},- 'subscriptionUsage': {- 'text': _subscriptionUsage.text,- 'label': _subscriptionUsage.detail,- 'detail': _subscriptionUsage.detail,- 'segments': _subscriptionUsage- .paintSegments(- foreground: terminalTheme.foreground,- surface: grid.AppPalette.swarmField,- )- .map((part) => part.toJson())- .toList(),- 'interactive': _shortcutsEnabled,- },'harnessMonitor': {'text': monitor.label,'label': monitor.detail,@@ -1821,30 +1808,6 @@ class _SwarmScreenState extends State<SwarmScreen> {],'interactive': _shortcutsEnabled,},- 'machineResources': {- 'text': monitor.metricsLabel(),- 'label': monitor.resourceDetail,- 'detail': monitor.resourceDetail,- 'segments': [- {'text': monitor.metricsLabel()},- ],- 'noStorageSegments': [- {'text': monitor.metricsLabel(storage: false)},- ],- 'compactSegments': [- {'text': monitor.metricsLabel(gpu: false, storage: false)},- ],- 'minimalSegments': [- {- 'text': monitor.metricsLabel(- ram: false,- gpu: false,- storage: false,- ),- },- ],- 'interactive': _shortcutsEnabled,- },'footerCovered':!_showWorkspaceFooter ||(!_routeIsCurrent && !_footerPreviewCurrent) ||@@ -7243,7 +7206,6 @@ class _SwarmScreenState extends State<SwarmScreen> {: 0.0;final download = kIsWeb && !_compact(context);final downloadWidth = download ? available * .16 : 0.0;- final usage = _subscriptionUsage;final resourceGap = cell.width * (workspaceBarGroupGapCells - 2);final resourceBudget = math.max(0.0,@@ -7263,10 +7225,6 @@ class _SwarmScreenState extends State<SwarmScreen> {cell.width * 2,resourceBudget * .4,);- final hardwareWidth = resourceBudget * .52;- final usageWidth = constraints.maxWidth < 1050- ? 0.0- : resourceBudget * .22;final hasFooterDaemon = !kIsWeb && _slotShown;final paneContext = Row(mainAxisAlignment: MainAxisAlignment.end,@@ -7319,7 +7277,7 @@ class _SwarmScreenState extends State<SwarmScreen> {child: ListenableBuilder(listenable: _harnessMonitor,builder: (context, _) {- final summary = _harnessMonitor.summary;+ final summary = _harnessMonitor;return WorkspaceBarControl(key: const ValueKey('workspace-harness-monitor'),label: summary.detail,@@ -7351,69 +7309,6 @@ class _SwarmScreenState extends State<SwarmScreen> {},),),- SizedBox(width: resourceGap),- ConstrainedBox(- constraints: BoxConstraints(maxWidth: hardwareWidth),- child: WorkspaceHarnessResources(- key: const ValueKey('workspace-machine-resources'),- monitor: _harnessMonitor,- // The fixed companion slot supplies its own optical gutter.- trailingPadding: hasFooterDaemon && usageWidth == 0- ? 0- : null,- onPressed: _shortcutsEnabled- ? _toggleHarnessControls- : null,- ),- ),- if (usageWidth > 0) ...[- SizedBox(width: resourceGap),- ConstrainedBox(- constraints: BoxConstraints(maxWidth: usageWidth),- child: WorkspaceBarControl(- key: const ValueKey('workspace-subscription-usage'),- label: usage.detail,- tooltip: usage.detail,- onPressed: _shortcutsEnabled- ? () => _toggleModels(- initialTab: ModelsTab.subscriptions,- )- : null,- builder: (context, emphasized) => Padding(- padding: EdgeInsets.only(- left: cell.width,- right: hasFooterDaemon ? 0 : cell.width,- ),- child: SizedBox(- height: workspaceBarControlHeight(context),- child: Center(- widthFactor: 1,- child: Text.rich(- TextSpan(- children: [- for (final part in usage.paintSegments(- foreground: theme.foreground,- surface: grid.AppPalette.swarmField,- ))- workspaceBarGroupTextSpan(- part.text,- cellWidth: cell.width,- style: TextStyle(color: part.foreground),- ),- ],- ),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: workspaceBarTextStyle(- emphasized: emphasized,- ),- ),- ),- ),- ),- ),- ),- ],if (hasFooterDaemon) ...[SizedBox(width: resourceGap),_daemonTabButton(),diff --git a/desktop/lib/state/harness_monitor.dart b/desktop/lib/state/harness_monitor.dartindex 1b2856b53..68f982061 100644--- a/desktop/lib/state/harness_monitor.dart+++ b/desktop/lib/state/harness_monitor.dart@@ -9,12 +9,17 @@ import '../shared/theme/workspace_bar_style.dart'import 'app_state.dart';import 'harness_sessions.dart';-/// A single, demand-driven sampler shared by the footer and its open panel.+/// Live inventory with optional demand-driven resource sampling.+/// The footer uses inventory only; resource readings belong in Harness Monitor./// It never starts an agent, opens a connection, or scans conversation files.class HarnessMonitor extends ChangeNotifier {- HarnessMonitor(this.app, {DateTime Function()? now})- : _now = now ?? DateTime.now;+ HarnessMonitor(+ this.app, {+ DateTime Function()? now,+ this.sampleResources = true,+ }) : _now = now ?? DateTime.now;final AppNotifier app;+ final bool sampleResources;final DateTime Function() _now;final _samples = <String, (MachineState, MachineHarnessResources)>{};Timer? _timer;@@ -77,7 +82,8 @@ class HarnessMonitor extends ChangeNotifier {}) => summary.metricsLabel(ram: ram, gpu: gpu, storage: storage);String get resourceDetail => summary.resourceDetail;- String get detail => summary.detail;+ String get detail =>+ '${live.length} open across connected machines. Click to open Harness Monitor.';void start() {if (_started || _disposed) return;@@ -120,7 +126,7 @@ class HarnessMonitor extends ChangeNotifier {}Future<void> refresh() async {- if (_disposed || _busy || !app.foreground.value) return;+ if (_disposed || _busy || !app.foreground.value || !sampleResources) return;_timer?.cancel();_busy = true;final revision = _revision;diff --git a/desktop/test/harness_monitor_summary_test.dart b/desktop/test/harness_monitor_summary_test.dartindex af688a69f..bb94f5f74 100644--- a/desktop/test/harness_monitor_summary_test.dart+++ b/desktop/test/harness_monitor_summary_test.dart@@ -68,6 +68,17 @@ MachineHarnessResources _resources();void main() {+ test('the footer count never samples resources, including refresh and foreground updates', () async {+ final app = _App()..machine('m', [_live]);+ final monitor = HarnessMonitor(app, sampleResources: false)..start();+ addTearDown(monitor.dispose);+ addTearDown(app.dispose);+ await monitor.refresh();+ app.changed();+ expect(monitor.label, 'Harnesses 1');+ expect(monitor.detail, contains('Click to open Harness Monitor'));+ expect(app.requests, isEmpty);+ });test('one snapshot preserves partial totals, shared servers, machine scope and nested storage', () async {final app = _App();final monitor = _Monitor(app);diff --git a/desktop/test/harness_monitor_test.dart b/desktop/test/harness_monitor_test.dartindex acdfd8398..941a77034 100644--- a/desktop/test/harness_monitor_test.dart+++ b/desktop/test/harness_monitor_test.dart@@ -337,7 +337,7 @@ void main() {);for (final nativeTabs in [false, true]) {- for (final resources in [false, true]) {+ for (final resources in nativeTabs ? [false, true] : [false]) {testWidgets('footer opens and reuses monitor (native=$nativeTabs resources=$resources)',(tester) async {@@ -360,10 +360,6 @@ void main() {),(_) {},);- } else if (resources) {- await tester.tap(- find.byKey(const ValueKey('workspace-machine-resources')),- );} else {await openWorkspaceManagement(tester, 'harnesses');}diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartindex 4c9b20353..db535386e 100644--- a/desktop/test/workspace_status_test.dart+++ b/desktop/test/workspace_status_test.dart@@ -1,5 +1,4 @@import 'dart:io';-import 'dart:async';import 'dart:ui' as ui;import 'dart:convert';@@ -486,7 +485,7 @@ void main() {for (final native in [false, true]) {testWidgets(- 'footer usage updates and opens subscriptions (native=$native)',+ 'footer shows only harness count beside focused work (native=$native)',(tester) async {final updates = <Map>[];const channel = MethodChannel('harness/swarm_tabs');@@ -497,117 +496,62 @@ void main() {});addTearDown(() => messenger.setMockMethodCallHandler(channel, null));final subscriptions = _FooterSubscriptions()- ..values = [- subscription('claude', 'aaaaaa', 0),- subscription('codex', 'bbbbbb', 13),- ];+ ..values = [subscription('codex', 'bbbbbb', 13)];final app = createApp();app.machineStates['m']!.localOnly = true;final pane = app.adoptSessionForTest(terminal('a0', []));addTearDown(app.dispose);addTearDown(subscriptions.dispose);tester.view.devicePixelRatio = 1;- tester.view.physicalSize = const Size(1280, 800);addTearDown(tester.view.reset);- await tester.pumpWidget(- MaterialApp(- theme: grid.buildAppTheme(brightness: Brightness.dark),- home: SwarmScreen(- notifier: app,- nativeTabs: native,- modelsMenu: subscriptions,+ for (final width in [1280.0, 640.0, 480.0]) {+ tester.view.physicalSize = Size(width, 800);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: native,+ modelsMenu: subscriptions,+ ),),- ),- );- await tester.pumpAndSettle();- const label = 'Claude 100% Codex 87%';- if (native) {- expect(updates.last['subscriptionUsage']['text'], label);- final parts = updates.last['subscriptionUsage']['segments'] as List;- expect(parts.map((part) => part['text']), [- 'Claude ',- '100%',- ' Codex ',- '87%',- ]);- expect(parts[0]['foreground'], parts[2]['foreground']);- expect(parts[1]['foreground'], parts[0]['foreground']);- expect(parts[3]['foreground'], parts[0]['foreground']);- expect(updates.last['subscriptionUsage']['detail'], contains('used'));- } else {- expect(find.text(label), findsOneWidget);- final usage = find.byKey(- const ValueKey('workspace-subscription-usage'),);- final context = find.byKey(const ValueKey('workspace-pane-context'));- expect(- tester.getRect(usage).right,- lessThan(tester.getRect(context).left),- );- await captureControls(tester, 'subscription-usage-footer');- for (final width in [480.0, 640.0]) {- tester.view.physicalSize = Size(width, 800);- await tester.pump();- expect(tester.takeException(), isNull);- expect(usage, findsNothing);+ await tester.pumpAndSettle();+ if (native) {+ expect(updates.last['subscriptionUsage'], isNull);+ expect(updates.last['machineResources'], isNull);+ expect(updates.last['harnessMonitor']['text'], 'Harnesses 0');+ } else {+ expect(+ find.byKey(const ValueKey('workspace-subscription-usage')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('workspace-machine-resources')),+ findsNothing,+ );final monitor = find.byKey(const ValueKey('workspace-harness-monitor'),);+ final context = find.byKey(+ const ValueKey('workspace-pane-context'),+ );+ expect(monitor, findsOneWidget);expect(tester.getRect(monitor).right,lessThan(tester.getRect(context).left),);+ if (width == 1280) {+ await captureControls(tester, 'harness-count-footer');+ }}- tester.view.physicalSize = const Size(1280, 800);- }- if (native) {- expect(- updates.last['machineResources']['text'],- 'CPU 0% RAM 0 MB GPU 0% SSD 0 MB',- );- expect(- updates.last['machineResources']['detail'],- contains('open harnesses across connected machines'),- );- expect(updates.last['machineResources']['interactive'], isTrue);- } else {- expect(- find.byKey(const ValueKey('workspace-machine-resources')),- findsOneWidget,- );+ expect(tester.takeException(), isNull);}- // Monitor navigation is exercised with its daemon fixture in harness_monitor_test.- expect(app.focusedPane, same(pane));- expect(app.panes, [pane]);subscriptions.update([subscription('codex', 'bbbbbb', 27)]);await tester.pump();- if (native) {- expect(updates.last['subscriptionUsage']['text'], 'Codex 73%');- final done = Completer<void>();- messenger.handlePlatformMessage(- channel.name,- const StandardMethodCodec().encodeMethodCall(- const MethodCall('subscriptions'),- ),- (_) => done.complete(),- );- await tester.pumpAndSettle();- await done.future;- } else {- expect(find.text('Codex 73%'), findsOneWidget);- await tester.tap(- find.byKey(const ValueKey('workspace-subscription-usage')),- );- await tester.pumpAndSettle();- }- final search = find.byKey(const ValueKey('swarm-search-input'));- expect(- tester.widget<TextField>(search).controller!.text,- ':subscription',- );+ expect(find.text('Codex 73%'), findsNothing);expect(app.focusedPane, same(pane));expect(app.panes, [pane]);- expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());},);diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 8d3d4f661..d0bed773d 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -2666,6 +2666,22 @@ private extension SwarmTabStrip {harnessMonitorButton.performClick(nil)machineResourcesLabel.performClick(nil)try checkTitlebar(calls.count == 2, "A covered or modal footer cannot open the session monitor")+ state["enabled"] = true+ state.removeValue(forKey: "machineResources")+ state.removeValue(forKey: "subscriptionUsage")+ for width in [CGFloat(360), CGFloat(520), CGFloat(1280)] {+ setFrameSize(NSSize(width: width, height: 40))+ update(state)+ try checkTitlebar(!harnessMonitorButton.isHidden && harnessMonitorButton.isEnabled &&+ harnessMonitorButton.frame.maxX <= contextButton.frame.minX &&+ machineResourcesLabel.isHidden && subscriptionUsageButton.isHidden,+ "The count-only footer preserves context and hides omitted resource and usage groups")+ if let capture = ProcessInfo.processInfo.environment["HARNESS_RESOURCE_CAPTURE_DIR"] {+ try statusBar.renderedTree(background: NSColor(white: 0.12, alpha: 1))+ .representation(using: .png, properties: [:])!.write(to:+ URL(fileURLWithPath: capture).appendingPathComponent("native-count-\(Int(width)).png"))+ }+ }update([:])try checkTitlebar(harnessMonitorButton.isHidden && !harnessMonitorButton.isEnabled && machineResourcesLabel.isHidden && !machineResourcesLabel.isEnabled,"Clearing workspace state clears the counter, hardware and actions")diff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.mdindex c24188362..18a95e9ee 100644--- a/store/agents/harness-monitor/AGENTS.md+++ b/store/agents/harness-monitor/AGENTS.md@@ -29,8 +29,8 @@ Rules and pins live in `~/.config/harness/policy.jsonc`; preserve comments whenA timed-out open is uncertain. Check its original receipt; never launch another process to compensate.An offline machine is not a stopped session. Unknown CPU, RAM or tokens are not zero. RAM sums processresident sets (shared pages can be counted twice); CPU is interval process-tree use, with 100% meaning-one core. GPU readings are attributable driver counters; missing counters are unavailable. Storage-includes existing workspace files and remains when a session stops. Last active comes from real+one core. GPU readings are attributable driver counters; missing counters are unavailable. Workspace storage includes project/worktree files; Session data measures conversation history and+checkpoints separately. Both remain when a session stops. Last active comes from realdaemon conversation activity, not file mtime.The default OpenCode model is Muse Spark 1.3 Contributor Free. It is a limited-time offer and allows@@ -38,5 +38,10 @@ Meta to train on prompts and responses. Both the main and small model are explicthat ID. Never silently switch to a paid model. The viewer includes an Assistant model disclosure; users can choose another model withOpenCode's `/models` command.-Never start another viewer: Harness already manages this one. Never delete transcripts or projects.+Never start another viewer: Harness already manages this one. For permanent deletion, direct the+person to the table's Delete Harness confirmation (session data only) or Inspect → Delete Worktree+(path, branch, size and uncommitted-change review). Do not use shell deletion to bypass these reviews.+Never delete a main project folder, branch or another harness's files. Worktree cleanup keeps the+conversation and branch; Delete Harness keeps workspace files. Shared database deletion may reuse+space without shrinking the database file. Never imply all Workspace bytes are session data.Report actual tool results, including refusals and uncertain outcomes, without inventing activity.diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.mdindex 9664c5cad..5ac97452f 100644--- a/store/agents/harness-monitor/README.md+++ b/store/agents/harness-monitor/README.md@@ -1,25 +1,40 @@# Harness Monitor-Inspect active harnesses across connected machines and decide what to stop. The workspace footer's-Harnesses, CPU, RAM, GPU and SSD controls select the existing Harness Monitor tab, creating one when-needed. The tab uses the standard 70% viewer / 30% assistant split. Use the pane Zoom icon for a full-width table. Opening the table submits no model prompt.--The table lists only currently open harnesses on connected machines, including idle, working,-waiting and starting sessions. Closed sessions and offline history never appear in this table.-Harness, Status, CPU, RAM, GPU and SSD come first, followed by Agent, Tokens,-Machine, Project and Branch. RAM is the initial default sort. Filter by machine or activity, search session-metadata, and choose Overview, Resources or AI usage. Click a header to sort; unknown readings sort-last in either direction. Drag a separator or use its arrow keys to resize a column. Columns and-widths persist; search and status reset on entry. The harness name stays visible during horizontal-scrolling. Arrow keys select; Enter or double-click opens the inspector. It includes process IDs,-parent IDs and resource readings. Each row has a visible × close button that stays available during-horizontal scrolling. Saved sessions remain available in Open Harness (Cmd-P).--The × button reviews that harness before asking its owning daemon to stop the validated process-and close its panes. A confirmed close removes the row and updates the totals.-Conversation history, launch settings and files remain. The daemon checks conversation identity again-before stopping. Offline or disconnected sessions cannot be stopped. Freeze updates holds the displayed readings-without affecting work, and disables closing until live updates return.+Inspect harnesses across connected machines and decide what to stop or delete. The workspace footer+shows only **Harnesses N**; click it to select the existing Harness Monitor tab, creating one when+needed. The footer does not poll resource metrics. The tab retains the standard 70% viewer / 30%+assistant split, including loading, failures and restore. Opening it submits no model prompt.++The default view lists open harnesses. **Stopped harnesses** exposes retained sessions for cleanup;+offline inventory never enables actions. Storage comes first: **Workspace**, **Session data**, then+RAM, CPU and GPU. Workspace size is the default descending sort. Project/worktree files and+conversation data are never combined into one disk figure. Shared folders repeat on individual+rows but count once in workspace totals.++Search, machine/activity filters, sortable/resizable columns and Overview, Resources and AI usage+presets remain available. Unknown readings sort last. Arrow keys select; Enter or double-click+opens Inspect. Freeze updates disables actions until live readings return.++Each row has **Stop Harness** and **Delete Harness** buttons:++- Stop Harness ends running work and closes its panes, keeping history, configuration and files.+- Delete Harness first previews the selected conversation's native history and Harness checkpoints+ on the owning daemon. Confirmation stops it, then permanently removes those files or supported+ database rows, search history, saved metadata and the retained harness. Project/worktree files+ stay. Some native stores have unsupported schemas or dependent conversations; deletion is refused+ rather than affecting other history. Shared database space becomes reusable but its file may not+ shrink immediately. Engine-wide caches and older conversations from `/clear` are not removed.+- **Inspect → Delete Worktree…** is separate. Its review shows the exact checkout path, branch, full+ worktree size and uncommitted changes. Type the full path to confirm; dirty worktrees also require+ explicit consent to discard all uncommitted and untracked files. Ignored dependencies/build output+ are removed too. The owning daemon stops the selected harness, revalidates the checkout and uses+ `git worktree remove`. It keeps the main checkout, branch, commits and conversation history.+ Recreate the checkout to resume later. Main folders, locked worktrees, nested worktrees, checkouts+ used by other live or saved harnesses, and detached commits without a saved branch are protected.++Deletion is one harness at a time, never automatic. Reviews expire after two minutes and are bound+to the machine, harness and conversation. Changed identities, paths or worktree status require a new+review. Cancel is the default. A lost response is uncertain and is never automatically retried.## Metric definitions@@ -29,7 +44,8 @@ without affecting work, and disables closing until live updates return.| RAM | Process-tree resident memory, in rounded MB/GB. Shared pages can overlap. Nested harness roots are excluded from their parent. Shared Codex servers appear separately and count once. || GPU % | GPU use of the harness process tree. macOS reads IOAccelerator clients owned by each PID: Apple Silicon AppUsage and Intel/AMD accumulatedGPUTime counters. GPU nanoseconds divided by the sample interval give percent. Linux reads NVIDIA process utilization. Summed use can exceed 100% across contexts/devices. Initial samples, context changes, resets and unavailable drivers show —. Cloud inference is not local GPU use. || GPU memory | NVIDIA compute allocations on supported Linux drivers. macOS and unsupported counters show —. |-| SSD | Allocated workspace disk space, including pre-existing files, from bounded du reads cached for one minute. Shared and nested canonical folders count once per machine in totals. Stopping does not release this space. SSD is a display label, not a hardware-media probe. |+| Workspace | Allocated disk space of the entire working folder (project, linked worktree or subfolder), from bounded `du` reads cached for one minute. Shared and nested canonical folders count once per machine in totals. Inspect reviews the full worktree root before deletion. |+| Session data | Allocated conversation-file and checkpoint bytes, or estimated conversation content within a shared native database plus checkpoints. Excludes project/worktree files. Cached for one minute; unsupported or unreadable stores show —. || Disk read/s / write/s | Physical process-tree I/O deltas from Linux /proc/<pid>/io. Restricted counters, resets and macOS show —. || Transcript | Individual conversation-file size when reported. Shared databases show —. || Tokens | Conversation input plus output, with cached input counted once. Claude, Codex and OpenCode use the existing incremental daemon ledger. Other frameworks remain visible with unavailable token fields. |@@ -41,17 +57,13 @@ Model, framework, machine, project, branch, folder, process count, start time anprovide context. There is no invented dollar cost: subscription plans, caching and provider pricescannot be inferred reliably from total tokens.-Totals describe the shown open harnesses and their shared servers. ≥ marks partial totals; — means-unavailable, never measured zero. Footer totals cover the open harnesses in its count across-connected owned machines. CPU/GPU use whole percentages; RAM/SSD use whole MB/GB (10.4 GB → 10 GB).-They do not include unrelated applications or whole-machine utilization.-+Totals describe the filtered harnesses and their shared servers. ≥ marks partial totals; — means+unavailable, never measured zero. CPU/GPU use whole percentages; storage and RAM use rounded MB/GB.The viewer polls local inventory every four seconds and linked machines every fifteen seconds while-visible. The foreground desktop footer samples every fifteen seconds; hidden apps clear readings and-stop polling. The daemon coalesces process reads, verifies PID birth identity, bounds macOS IORegistry/NVIDIA commands-and directory walks, and keeps telemetry off the terminal-input queue. No extra transcript scan is-started by the table or footer. Older daemons retain basic inventory but require updating for new-metrics. Identity and all stop actions remain machine-scoped through the paired bridge.+visible. Storage work is cached and bounded separately; it does not wait on the terminal-input queue.+The daemon verifies PID birth identity and bounds process probes and directory walks. Older daemons+retain basic inventory but require updating for new metrics and deletion actions. Actions stay+machine-scoped through the paired bridge; remote deletion requires an encrypted owner connection.## Design references and checks@@ -66,9 +78,9 @@ to locate IOAccelerator data and [GPUI's process GPU probe](https://github.com/lto verify the per-process counters. Stats' whole-device percentages are never included in harness totals.`npm test` uses isolated policy/state fixtures. `node test/preview.mjs` serves synthetic sessions and-simulated stops, without a daemon bridge or model call. Daemon checks live in harnessResources,+simulated stops and deletions, without a daemon bridge or model call. Daemon checks live in harnessResources,harnessTelemetry, agentTokenUsage and backendSocket specs. Desktop tests cover footer scope,-rounding, hidden polling and tab reuse; `tool/check_swarm_titlebar.sh` checks native clicks/layout.+count-only behavior, layout and tab reuse; `tool/check_swarm_titlebar.sh` checks native clicks/layout.Real Linux NVIDIA counters still require hardware validation; parser fixtures do not establishsupport for every driver.On macOS, `cd cli && RUN_MACOS_GPU=1 npm test -- src/lib/macosProcessGpu.integration.spec.ts`diff --git a/store/agents/harness-monitor/harness.json b/store/agents/harness-monitor/harness.jsonindex 2eec0b840..0e3ed3163 100644--- a/store/agents/harness-monitor/harness.json+++ b/store/agents/harness-monitor/harness.json@@ -4,7 +4,7 @@"name": "Harness Monitor","category": "Compute","author": "Autonomous",- "description": "Inspect active harnesses across your machines. Sort CPU, RAM, GPU, storage and conversation usage, inspect processes, and stop selected work while keeping history and files.",+ "description": "Inspect harnesses across your machines. See workspace and session storage separately, stop work, or review permanent session and Git worktree cleanup.","engine": "opencode","workspace": {"template": "template",diff --git a/store/agents/harness-monitor/lib/actions.mjs b/store/agents/harness-monitor/lib/actions.mjsindex 683da89c2..e3e25c9ae 100644--- a/store/agents/harness-monitor/lib/actions.mjs+++ b/store/agents/harness-monitor/lib/actions.mjs@@ -16,7 +16,7 @@ async function fresh(row, list) {const agent = agents.find(a => a.id === row.agentId)if (!agent) throw new Error('This harness is no longer in the daemon inventory. Refresh and try again.')// A stopped/reopened or rotated conversation is a different target from the one the person reviewed.- if ((agent.sessionId || null) !== (row.sessionId || null)) throw new Error('This conversation changed. Refresh and review it before acting.')+ if ((agent.sessionId || null) !== (row.sessionId || null) || (row.createdAt != null && Date.parse(agent.createdAt) !== row.createdAt)) throw new Error('This conversation changed. Refresh and review it before acting.')return mergeRows([agent], { machine: { machineId: row.machineId, name: row.machine }, local: row.local,state: { pins: row.pinned ? [row.id] : [] } })[0]}@@ -88,3 +88,37 @@ async function openOnce(row, { list = listAgents, rpc = request, intent = openInreturn receipt(row, 'open', 'Open is not confirmed yet. Check again to read the same operation.', { creationId: operation.creationId, unconfirmed: true })} catch (error) { return receipt(row, 'open', error.message) }}++/** Preview and deletion both stay on the owning daemon; only it knows the native storage paths. */+export async function previewDelete(row, { list = listAgents, rpc = request } = {}) {+ try {+ const current = await fresh(row, list)+ if (!current.canDelete) return receipt(row, 'delete-review', current.unavailable || 'This harness cannot be deleted yet.')+ const result = await rpc(row.machineId, 'agent_purge', {+ agentId: row.agentId, sessionId: row.sessionId, createdAt: row.createdAt, mode: 'inspect',+ })+ if (!result.reviewId) return receipt(row, 'delete-review', 'The daemon did not confirm which session data would be deleted.')+ return { ...receipt(row, 'delete-review', 'Review permanent deletion.'), ...result, ok: true, refused: false }+ } catch (error) { return receipt(row, 'delete-review', error.code === 'UNSUPPORTED' ? 'Update Harness on the owning machine to enable deletion.' : error.message) }+}+export async function deleteHarness(row, { reviewId, rpc = request } = {}) {+ try {+ if (typeof reviewId !== 'string' || !reviewId) return receipt(row, 'delete', 'Review this harness before deleting it.')+ const result = await rpc(row.machineId, 'agent_purge', {+ agentId: row.agentId, sessionId: row.sessionId, createdAt: row.createdAt, mode: 'delete', reviewId,+ })+ if (result.deleted !== true) return receipt(row, 'delete', 'Deletion was not confirmed. Refresh before trying again.')+ return { ...receipt(row, 'delete', 'Session data deleted. Project files kept.'), ...result, ok: true, refused: false }+ } catch (error) { return receipt(row, 'delete', error.message + ' Refresh to check; deletion is never retried automatically.') }+}++export async function worktreeAction(row, { reviewId, path, discardChanges = false, rpc = request } = {}) {+ const inspect = !reviewId+ try {+ const result = await rpc(row.machineId, 'agent_worktree_delete', { agentId: row.agentId,+ sessionId: row.sessionId, createdAt: row.createdAt, mode: inspect ? 'inspect' : 'delete',+ ...(reviewId ? { reviewId, path, discardChanges } : {}) })+ if (inspect ? !result.reviewId : result.deleted !== true) throw new Error('The worktree operation was not confirmed. Refresh before trying again.')+ return { ...receipt(row, inspect ? 'worktree-review' : 'worktree-delete', inspect ? 'Review worktree cleanup.' : 'Worktree deleted. Branch and history kept.'), ...result, ok: true, refused: false }+ } catch (error) { return receipt(row, 'worktree-delete', error.message) }+}diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjsindex 7674d6c1b..e061cf758 100644--- a/store/agents/harness-monitor/lib/inventory.mjs+++ b/store/agents/harness-monitor/lib/inventory.mjs@@ -68,7 +68,7 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, nodiskReadBytesPerSecond: online && !stopped ? reading(monitor?.diskReadBytesPerSecond) : null,diskWriteBytesPerSecond: online && !stopped ? reading(monitor?.diskWriteBytesPerSecond) : null,workspaceBytes: reading(monitor?.workspaceBytes), workspacePath: monitor?.workspacePath ?? cwd, workspaceSampledAt: time(monitor?.workspaceSampledAt),- transcriptBytes: reading(monitor?.transcriptBytes),+ sessionBytes: reading(monitor?.sessionBytes), transcriptBytes: reading(monitor?.transcriptBytes),processes: online && !stopped && Array.isArray(monitor?.processes) ? monitor.processes : [],tokenUpdatedAt: time(agent.tokenUsage?.updatedAt),inputTokens: reading(agent.tokenUsage?.inputTokens), outputTokens: reading(agent.tokenUsage?.outputTokens),@@ -79,6 +79,7 @@ export function mergeRows(agents, { state = {}, machine = null, local = true, noverdict: agent.verdict?.ready ?? null,machine: machine?.name ?? 'This machine', machineId: machine?.machineId ?? null,local, online, self, canStop: canControl && terminalAvailable,+ canDelete: canControl && time(agent.createdAt) != null && (terminalAvailable || stopped),canOpen: online && (terminalAvailable || (stopped && agent.resumeMode != null)), resumeMode: agent.resumeMode ?? null,unavailable: !online ? 'Reconnect this machine.' : self ? 'Manage this assistant from its monitor tab.' : agent.launch?.detail ?? null,}diff --git a/store/agents/harness-monitor/test/actions.test.mjs b/store/agents/harness-monitor/test/actions.test.mjsindex 7b8f66b6e..fccfb369f 100644--- a/store/agents/harness-monitor/test/actions.test.mjs+++ b/store/agents/harness-monitor/test/actions.test.mjs@@ -1,14 +1,31 @@import assert from 'node:assert/strict'import { test } from 'node:test'-import { stop, open } from '../lib/actions.mjs'+import { stop, open, previewDelete, deleteHarness, worktreeAction } from '../lib/actions.mjs'import { mergeRows } from '../lib/inventory.mjs'import { frame } from './fixtures.mjs'const observed = Date.now()-const agent = extra => frame({ updatedAt: observed, resumeMode: 'conversation', monitor: { activity: 'idle', activityKnown: true }, ...extra })+const agent = extra => frame({ createdAt: new Date(observed - 1000).toISOString(), updatedAt: observed, resumeMode: 'conversation', monitor: { activity: 'idle', activityKnown: true }, ...extra })const row = extra => mergeRows([agent(extra)], { machine: { machineId: 'remote', name: 'Office' }, local: false })[0]const intent = async () => ({ creationId: 'same-operation', path: '/fixture', existing: false })const clearIntent = async () => {}+test('deletion binds the review to the owning daemon and never retries a lost response', async () => {+ const selected = row(), calls = []+ const rpc = async (...args) => { calls.push(args); return { reviewId: 'reviewed', sessionBytes: 4096 } }+ assert.equal((await previewDelete(selected, { list: async () => [agent()], rpc })).reviewId, 'reviewed')+ assert.deepEqual(calls[0], ['remote', 'agent_purge', { agentId: selected.agentId, sessionId: selected.sessionId, createdAt: selected.createdAt, mode: 'inspect' }])+ const lost = async (...args) => { calls.push(args); throw new Error('connection lost') }+ assert.equal((await deleteHarness(selected, { rpc: lost })).ok, false)+ assert.equal(calls.length, 1)+ const result = await deleteHarness(selected, { reviewId: 'reviewed', rpc: lost })+ assert.equal(result.ok, false); assert.match(result.detail, /never retried/)+ assert.equal(calls.length, 2)+ assert.equal(calls[1][2].reviewId, 'reviewed')+ await worktreeAction(selected, { reviewId: 'tree', path: '/exact/path', discardChanges: true, rpc: lost })+ assert.equal(calls.length, 3)+ assert.deepEqual(calls[2], ['remote', 'agent_worktree_delete', { agentId: selected.agentId, sessionId: selected.sessionId, createdAt: selected.createdAt, mode: 'delete', reviewId: 'tree', path: '/exact/path', discardChanges: true }])+})+test('remote stop uses daemon identity, never a signal or tmux command', async () => {const calls = []const result = await stop(row(), { list: async () => [agent()], rpc: async (...args) => { calls.push(args); return { deleted: true } } })diff --git a/store/agents/harness-monitor/test/page.test.mjs b/store/agents/harness-monitor/test/page.test.mjsindex 7da558d87..f76cc302a 100644--- a/store/agents/harness-monitor/test/page.test.mjs+++ b/store/agents/harness-monitor/test/page.test.mjs@@ -62,11 +62,11 @@ test('the stylesheet defines dark in both the ways the app can ask for it', asyntest('the verbs the pane offers are the verbs the server accepts', async () => {const [js, server] = await Promise.all([read('viewer/app.js'), read('viewer.mjs')])- const allowed = new Set(server.match(/const VERBS = new Set\(\[([^\]]+)\]\)/)[1].match(/'[a-z]+'/g).map((word) => word.slice(1, -1)))- for (const match of js.matchAll(/\bverb:\s*'([a-z]+)'/g)) {+ const allowed = new Set(server.match(/const VERBS = new Set\(\[([^\]]+)\]\)/)[1].match(/'[a-z-]+'/g).map((word) => word.slice(1, -1)))+ for (const match of js.matchAll(/\bverb:\s*'([a-z-]+)'/g)) {if (match[1] !== 'clear') assert.ok(allowed.has(match[1]), `the server does not accept ${match[1]}`)}- for (const forbidden of ['delete', 'kill', 'remove']) assert.equal(allowed.has(forbidden), false)+ for (const forbidden of ['kill', 'remove']) assert.equal(allowed.has(forbidden), false)})/**diff --git a/store/agents/harness-monitor/test/preview.mjs b/store/agents/harness-monitor/test/preview.mjsindex ba7fec220..9e7c27007 100644--- a/store/agents/harness-monitor/test/preview.mjs+++ b/store/agents/harness-monitor/test/preview.mjs@@ -18,14 +18,19 @@ const rows = Array.from({ length: Number(process.env.PREVIEW_ROWS || 24) }, (_,selectedModel: ['gpt-6', 'claude-sonnet-4-6', 'muse-spark-1.3-contributor-free', 'auto'][i % 4],createdAt: new Date(Date.now() - 86400000 * 3).toISOString(), updatedAt: new Date(Date.now() - i * 85000).toISOString(),tokenUsage: { totalTokens: i % 3 ? 578000 : 3500000, inputTokens: i % 3 ? 420000 : 3200000, outputTokens: i % 3 ? 158000 : 300000, cachedTokens: i % 3 ? 190000 : 2100000, updatedAt: new Date().toISOString() },- monitor: { activity: activities[i % activities.length], activityKnown: true, cpu: [126, 3, 0, 12, 64, 0][i % 6], rssBytes: (i % 6 + 1) * 460 * 1024 ** 2, pid: 3400 + i, processCount: 2, gpuPercent: i === 0 ? null : i % 2 ? 6 : i % 6 ? 0 : 24, gpuMemoryBytes: i % 2 ? 2400000000 : null, workspaceBytes: (i % 3 + 1) * 1700000000, workspacePath: '/home/demo/project-' + (i % 3), transcriptBytes: 2400000, sampledAt: new Date().toISOString(), processes: [{ pid: 3400 + i, parent: 1, cpuPercent: [126, 3, 0, 12, 64, 0][i % 6], memoryBytes: (i % 6 + 1) * 460 * 1024 ** 2 - 80000000 }, { pid: 4400 + i, parent: 3400 + i, cpuPercent: 0, memoryBytes: 80000000 }] },+ monitor: { activity: activities[i % activities.length], activityKnown: true, cpu: [126, 3, 0, 12, 64, 0][i % 6], rssBytes: (i % 6 + 1) * 460 * 1024 ** 2, pid: 3400 + i, processCount: 2, gpuPercent: i === 0 ? null : i % 2 ? 6 : i % 6 ? 0 : 24, gpuMemoryBytes: i % 2 ? 2400000000 : null, workspaceBytes: (i % 3 + 1) * 1700000000, workspacePath: '/home/demo/project-' + (i % 3), transcriptBytes: 2400000, sessionBytes: (i + 1) * 4000000, sampledAt: new Date().toISOString(), processes: [{ pid: 3400 + i, parent: 1, cpuPercent: [126, 3, 0, 12, 64, 0][i % 6], memoryBytes: (i % 6 + 1) * 460 * 1024 ** 2 - 80000000 }, { pid: 4400 + i, parent: 3400 + i, cpuPercent: 0, memoryBytes: 80000000 }] },}], { machine: { machineId: i % 2 ? 'office' : 'm2', name: i % 2 ? 'Linux · 4090' : 'MacBook Pro' }, local: false, online: i % 17 !== 16 })[0])const viewer = createViewer({ workspace, port: Number(process.env.PREVIEW_PORT || 0), intervalMs: 3000,collect: async () => ({ rows, shared: [{ id: 'shared-codex', name: 'Shared Codex server', machine: 'MacBook Pro', machineId: 'm2', agentIds: ['session-0', 'session-4'], online: true, cpu: 2, rssBytes: 340000000, gpuPercent: 0 }], problems: [], machines: [] }),verbs: { stop: async row => {Object.assign(row, { state: 'stopped', live: false, activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })return { ok: true, action: 'stop', id: row.id, name: row.name }- }, open: async () => ({ ok: false, detail: 'Use the host integration fixture to open.' }) },+ }, previewDelete: async row => ({ ok: true, id: row.id, reviewId: 'synthetic-delete', sessionBytes: row.sessionBytes, sharedStore: row.engine === 'opencode' }),+ deleteHarness: async row => { rows.splice(rows.indexOf(row), 1); return { ok: true, id: row.id, deleted: true } },+ worktreeAction: async (row, options) => options?.reviewId+ ? { ok: true, id: row.id, deleted: true }+ : { ok: true, id: row.id, reviewId: 'synthetic-worktree', worktree: { path: '/home/demo/worktrees/feature', main: '/home/demo/code/openharness', branch: 'feature/storage', bytes: 3200000000, dirty: true, changes: [' M src/app.ts', '?? draft.txt'] } },+ open: async () => ({ ok: false, detail: 'Use the host integration fixture to open.' }) },})console.log('Synthetic preview: http://127.0.0.1:' + await viewer.start())for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => viewer.close().then(() => process.exit(0)))diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjsindex 5a1054cf0..149a7f334 100644--- a/store/agents/harness-monitor/test/server.test.mjs+++ b/store/agents/harness-monitor/test/server.test.mjs@@ -172,6 +172,29 @@ test('a policy is validated before it is written', async (t) => {assert.match(rules, /"pinned": true/, 'the pane may only change the thresholds it draws, never a guard')})+test('permanent deletion requires one explicit target, matching identity, and a review token', async t => {+ const target = row({ id: 'a1', createdAt: 1234 }), calls = []+ const previewDelete = async target => { calls.push('review'); return { ok: true, id: target.id, reviewId: 'review-token' } }+ const deleteHarness = async (target, options) => { calls.push(options.reviewId); return { ok: true, id: target.id, deleted: true } }+ const worktreeAction = async (target, options) => { calls.push(options); return { ok: true, id: target.id, deleted: true } }+ const { viewer, base } = await serve([target], { verbs: { previewDelete, deleteHarness, worktreeAction } })+ t.after(() => viewer.close())+ const request = payload => post(base, viewer.token, '/api/act', payload)+ const approved = { ids: ['a1'], manual: true, expected: [target] }+ for (const verb of ['delete', 'delete-review', 'worktree-review', 'worktree-delete']) {+ assert.ok((await request({ verb, ids: ['a1'] })).error)+ assert.ok((await request({ ...approved, verb, ids: ['a1', 'a2'] })).error)+ const changed = await request({ ...approved, verb, reviewId: 'token', expected: [{ ...target, createdAt: 5678 }] })+ assert.equal(changed.results[0].ok, false)+ }+ assert.ok((await request({ ...approved, verb: 'delete' })).error)+ assert.deepEqual(calls, [])+ assert.equal((await request({ ...approved, verb: 'delete-review' })).results[0].reviewId, 'review-token')+ assert.equal((await request({ ...approved, verb: 'delete', reviewId: 'review-token' })).results[0].deleted, true)+ assert.equal((await request({ ...approved, verb: 'worktree-delete', reviewId: 'worktree-token', path: '/reviewed/path', discardChanges: true })).results[0].deleted, true)+ assert.deepEqual(calls, ['review', 'review-token', { reviewId: 'worktree-token', path: '/reviewed/path', discardChanges: true }])+})+test('the pane header verdict is written from the same plan the page draws', async (t) => {const { viewer, workspace } = await serve()t.after(() => viewer.close())diff --git a/store/agents/harness-monitor/test/table.test.mjs b/store/agents/harness-monitor/test/table.test.mjsindex b191e0f0b..35a61bc98 100644--- a/store/agents/harness-monitor/test/table.test.mjs+++ b/store/agents/harness-monitor/test/table.test.mjs@@ -30,7 +30,7 @@ test('every filter excludes saved history, exited processes and cached offline s{ ...history, id: 'stale-live-flag', live: true },{ ...rows[0], id: 'offline-state', state: 'offline' }]assert.deepEqual(visibleRows([...rows, ...closed]).map(r => r.id).sort(), ['m1/a', 'm1/b', 'm2/a'])- for (const filter of ['all', 'working', 'idle', 'stopped', 'offline']) {+ for (const filter of ['all', 'working', 'idle', 'offline']) {assert.equal(visibleRows(closed, { filter }).length, 0)}assert.equal(visibleRows([...rows, ...closed], { query: 'Old' }).length, 0)@@ -54,3 +54,9 @@ test('shared and nested workspace paths count once on each owning machine', () =assert.equal(formatValue('rssBytes', 10.4e9), '10 GB')assert.equal(formatValue('cpu', 126.4), '126%')})++test('stopped filter makes saved harnesses available for permanent deletion', () => {+ const saved = { id: 'saved', name: 'History', state: 'stopped', activity: 'stopped', live: false }+ assert.deepEqual(visibleRows([...rows, saved], { filter: 'stopped' }), [saved])+ assert.deepEqual(visibleRows([{ ...saved, online: false }], { filter: 'stopped' }), [])+})diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjsindex 913476e1f..27db6af26 100644--- a/store/agents/harness-monitor/viewer.mjs+++ b/store/agents/harness-monitor/viewer.mjs@@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises'import { homedir } from 'node:os'import { dirname, join, resolve } from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'-import { stop, open } from './lib/actions.mjs'+import { stop, open, previewDelete, deleteHarness, worktreeAction } from './lib/actions.mjs'import { cleanupReviews } from './lib/cleanup.mjs'import { closeBridges } from './lib/bridge.mjs'import { collect as collectFleet, summarize, tilde } from './lib/inventory.mjs'@@ -14,9 +14,9 @@ import { DEFAULT_POLICY, decide, normalizePolicy } from './lib/policy.mjs'import { pin, readLog, readState, record, savePolicyValues, writeState, writeVerdict } from './lib/state.mjs'const PACKAGE = dirname(fileURLToPath(import.meta.url))-const VERBS = new Set(['stop', 'open', 'pin', 'unpin'])+const VERBS = new Set(['stop', 'open', 'pin', 'unpin', 'delete-review', 'delete', 'worktree-review', 'worktree-delete'])-export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { stop, open }, cleanup = cleanupReviews() }) {+export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { stop, open, previewDelete, deleteHarness, worktreeAction }, cleanup = cleanupReviews() }) {const token = randomBytes(24).toString('base64url')const clients = new Set()const cache = new Map()@@ -112,12 +112,15 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntreturn result}const act = payload => write(() => actOnce(payload))- async function actOnce({ verb, ids, manual = false, expected }) {+ async function actOnce({ verb, ids, manual = false, expected, reviewId, path, discardChanges }) {if (!VERBS.has(verb)) return { error: `Not a verb Harness Monitor has: ${verb}` }const targets = [...new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === 'string'))].slice(0, 64)if (!targets.length) return { error: 'Name at least one harness.' }const explicit = manual === true && targets.length === 1- const reviewed = new Map((Array.isArray(expected) ? expected : snapshot.rows).filter(row => row && typeof row.id === 'string').map(({ id, sessionId, lastActivity }) => [id, { sessionId, lastActivity }]))+ const deleting = ['delete', 'delete-review', 'worktree-review', 'worktree-delete'].includes(verb)+ if (deleting && (!explicit || !Array.isArray(expected) || expected.length !== 1)) return { error: 'Review one harness at a time before deleting.' }+ if (['delete', 'worktree-delete'].includes(verb) && (typeof reviewId !== 'string' || !reviewId)) return { error: 'Review this harness before deleting it.' }+ const reviewed = new Map((Array.isArray(expected) ? expected : snapshot.rows).filter(row => row && typeof row.id === 'string').map(({ id, sessionId, lastActivity, createdAt }) => [id, { sessionId, lastActivity, createdAt }]))// Bulk actions are restricted to what is still in the reviewed cleanup plan.if (verb === 'stop' && !explicit) {await polling@@ -133,7 +136,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntconst eligible = new Set(snapshot.plan.filter(entry => entry.action === 'stop').map(entry => entry.id))for (const row of rows) {const review = reviewed.get(row.id)- if (verb === 'stop' && (!review || review.sessionId !== row.sessionId || (!explicit && review.lastActivity !== row.lastActivity))) {+ if ((verb === 'stop' || deleting) && (!review || review.sessionId !== row.sessionId || (deleting && review.createdAt !== row.createdAt) || (!explicit && review.lastActivity !== row.lastActivity))) {results.push({ id: row.id, name: row.name, action: verb, ok: false, refused: true, detail: 'This session changed since you reviewed it. Refresh and review it again.' })continue}@@ -146,7 +149,11 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntresults.push({ ok: true, action: verb, id: row.id, name: row.name, detail: verb === 'pin' ? 'never stopped by the policy' : 'the policy may stop it again' })continue}- const result = verb === 'stop' ? await verbs.stop(row, { policy, force: explicit }) : await verbs.open(row)+ const result = verb === 'stop' ? await verbs.stop(row, { policy, force: explicit })+ : verb === 'delete-review' ? await verbs.previewDelete(row)+ : verb === 'delete' ? await verbs.deleteHarness(row, { reviewId })+ : verb === 'worktree-review' ? await verbs.worktreeAction(row)+ : verb === 'worktree-delete' ? await verbs.worktreeAction(row, { reviewId, path, discardChanges }) : await verbs.open(row)results.push(result)}if (verb === 'pin' || verb === 'unpin') await writeState(workspace, next)diff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.cssindex 58e7a7987..080e93ef4 100644--- a/store/agents/harness-monitor/viewer/app.css+++ b/store/agents/harness-monitor/viewer/app.css@@ -3,7 +3,7 @@:root[data-theme="dark"] { color-scheme:dark; --bg:#242528; --row:#1d1e21; --alt:#222326; --text:#eeeff2; --muted:#aaadb5; --line:#393b40; --hover:#303238; --selection:#243e60; --accent:#8dbaff; --yellow:#e5bf70; --red:#ff949a; --green:#8bcc9e; --cyan:#8dc7e4; }* { box-sizing:border-box; }[hidden] { display:none !important; }-body { margin:0; background: var(--bg); color:var(--text); height:100dvh; display:flex; flex-direction:column; overflow:hidden; }+body { margin:0; background: var(--bg); color:var(--text); height:100dvh; display:flex; flex-direction:column; overflow-x:hidden; overflow-y:auto; }button,input,select,summary { font:inherit; color:inherit; }button,select,summary { min-height:32px; background:transparent; border:1px solid transparent; border-radius:16px; padding:6px 11px; cursor:pointer; white-space:nowrap; }button:hover,summary:hover,select:hover { background:var(--hover); }@@ -53,9 +53,10 @@ table { border-collapse:separate; border-spacing:0; table-layout:fixed; min-widt#table th:first-child { z-index:4; }#table th.row-actions,#table td.row-actions { position:sticky; right:0; z-index:2; padding:4px 10px; text-align:center; border-left:1px solid var(--line); }#table th.row-actions { z-index:4; }-.close-harness { display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; min-height:32px; padding:0; border:1px solid var(--line); border-radius:8px; color:var(--text); }-.close-harness span { font:22px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; }-.close-harness:hover:not(:disabled),.close-harness:focus-visible { color:var(--red); border-color:var(--red); background:var(--row); }+.row-actions button { min-height:30px; border:1px solid var(--line); border-radius:8px; padding:5px 9px; font-size:12px; }+.row-actions button + button { margin-left:6px; }+.row-actions button:hover:not(:disabled) { background:var(--row); border-color:currentColor; }+@media (max-width:620px) { .row-actions button { display:block; width:100%; } .row-actions button + button { margin:4px 0 0; } #table th:first-child,#table td:first-child { position:static; } }#table td:first-child strong { display:block; overflow:hidden; text-overflow:ellipsis; }#table td:first-child strong { font-weight:500; }.numeric { text-align:right; }@@ -107,6 +108,14 @@ p { line-height:1.5; }.processes th { color:var(--muted); }.metric-note { grid-column:1/-1; font-size:12px; margin:0; }#stop-result { color:var(--yellow); }+#stop-storage { overflow-wrap:anywhere; }+.worktree-details { display:grid; grid-template-columns:auto minmax(0,1fr); gap:10px 16px; font-size:12px; }+.worktree-details dt { color:var(--muted); }+.worktree-details dd { margin:0; overflow-wrap:anywhere; }+#worktree-review label { display:block; margin:16px 0 8px; line-height:1.5; }+#worktree-review [hidden] { display:none; }+#worktree-path { width:100%; padding:9px; border:1px solid var(--line); border-radius:8px; background:var(--row); color:var(--text); font:inherit; }+#worktree-changes { max-height:140px; overflow:auto; padding:10px; background:var(--row); white-space:pre-wrap; overflow-wrap:anywhere; font-size:12px; }.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }@media (max-width:800px) { nav { gap:5px; } .spacer { display:none; } .summary-scope { width:100%; margin:0; } #summary { gap:12px 22px; } }@media (max-width:540px) { header { flex-wrap:wrap; gap:12px; padding:14px 12px; } .search-field { width:100%; margin:0; } nav { padding:0 8px 10px; } .segmented { width:100%; margin:0 0 5px; } .segmented button { flex:1; } #inspect-content { grid-template-columns:1fr; } #summary { padding:12px; } footer { padding:8px 12px; } }diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.jsindex cb4d43c47..0cae9d880 100644--- a/store/agents/harness-monitor/viewer/app.js+++ b/store/agents/harness-monitor/viewer/app.js@@ -7,17 +7,19 @@ const dom = {refresh: el('refresh'), freeze: el('freeze'), live: el('live-status'), inspect: el('inspect'),summary: el('summary'), shared: el('shared'), sharedTitle: el('shared-title'), sharedBody: el('shared-body'),inspector: el('inspector'), inspectTitle: el('inspect-title'), inspectContext: el('inspect-context'),- inspectContent: el('inspect-content'), inspectClose: el('inspect-close'), inspectStop: el('inspect-stop'),+ inspectContent: el('inspect-content'), inspectClose: el('inspect-close'), inspectStop: el('inspect-stop'), inspectDelete: el('inspect-delete'),stopDialog: el('stop-dialog'), stopTitle: el('stop-title'), stopContext: el('stop-context'), stopResult: el('stop-result'),- stopCancel: el('stop-cancel'), stopConfirm: el('stop-confirm'),+ stopCancel: el('stop-cancel'), stopConfirm: el('stop-confirm'), stopDescription: el('stop-description'), stopStorage: el('stop-storage'),+ inspectWorktree: el('inspect-worktree'), worktreeReview: el('worktree-review'), worktreeDetails: el('worktree-details'),+ worktreeChanges: el('worktree-changes'), worktreeDiscardLabel: el('worktree-discard-label'), worktreeDiscard: el('worktree-discard'), worktreePath: el('worktree-path'),}const token = document.querySelector('meta[name="hps-token"]').content-const STORAGE_KEY = 'harness-monitor.process-table.v4'+const STORAGE_KEY = 'harness-monitor.process-table.v5'let saved = {}try { saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') || {} } catch { /* optional preference storage */ }const state = {- rows: [], snapshot: null, query: '', filter: 'all', machine: 'all', // Only currently open harnesses, in every view.- sort: COLUMNS.some(c => c.key === saved.sort) ? saved.sort : 'rssBytes', direction: saved.direction === 1 ? 1 : -1,+ rows: [], snapshot: null, query: '', filter: 'all', machine: 'all',+ sort: COLUMNS.some(c => c.key === saved.sort) ? saved.sort : 'workspaceBytes', direction: saved.direction === 1 ? 1 : -1,preset: Object.hasOwn(PRESETS, saved.preset) ? saved.preset : 'overview',visible: new Set(Array.isArray(saved.visible) ? saved.visible : PRESETS.overview), widths: {},selected: null, inspecting: null, busy: new Set(), nodes: new Map(), shown: [],@@ -41,16 +43,17 @@ async function post(path, payload) {if (!response.ok || result.error) throw new Error(result.error || 'Request failed. Refresh and try again.')return result}-const CLOSE_WIDTH = 56+const actionWidth = () => innerWidth <= 620 ? 156 : 274+window.addEventListener('resize', resizeColumns)const activeColumns = () => {const ordered = PRESETS[state.preset]return ordered ? ordered.map(key => COLUMNS.find(c => c.key === key)): COLUMNS.filter(c => c.required || state.visible.has(c.key))}function resizeColumns() {- for (const col of dom.colgroup.children) col.style.width = (col.dataset.key === 'close' ? CLOSE_WIDTH : state.widths[col.dataset.key]) + 'px'+ for (const col of dom.colgroup.children) col.style.width = (col.dataset.key === 'close' ? actionWidth() : state.widths[col.dataset.key]) + 'px'for (const header of dom.head.querySelectorAll('th')) header.querySelector('.resize')?.setAttribute('aria-valuenow', String(state.widths[header.dataset.key]))- dom.table.style.width = activeColumns().reduce((sum, c) => sum + state.widths[c.key], CLOSE_WIDTH) + 'px'+ dom.table.style.width = activeColumns().reduce((sum, c) => sum + state.widths[c.key], actionWidth()) + 'px'}function buildColumns() {dom.colgroup.replaceChildren(); dom.head.replaceChildren(); state.nodes.clear(); dom.body.replaceChildren()@@ -75,7 +78,7 @@ function buildColumns() {}const closeWidth = element('col'); closeWidth.dataset.key = 'close'; dom.colgroup.append(closeWidth)const closeHeader = element('th', null, 'row-actions'); closeHeader.scope = 'col'- closeHeader.append(element('span', 'Close harness', 'sr-only')); tr.append(closeHeader)+ closeHeader.append(element('span', 'Actions')); tr.append(closeHeader)dom.head.append(tr); resizeColumns(); render()}function columnMenu() {@@ -107,7 +110,7 @@ function setPreset(preset) {state.preset = preset; state.visible = new Set(PRESETS[preset]);for (const col of COLUMNS) state.widths[col.key] = col.widthif (preset === 'ai') { state.sort = 'tokens'; state.direction = -1 }- else { state.sort = 'rssBytes'; state.direction = -1 }+ else { state.sort = 'workspaceBytes'; state.direction = -1 }persist(); columnMenu(); buildColumns()}for (const button of document.querySelectorAll('[data-preset]')) button.onclick = () => setPreset(button.dataset.preset)@@ -127,24 +130,29 @@ function createRow(row) {}tr.append(td)}- const actions = element('td', null, 'row-actions'), close = element('button', null, 'close-harness')- close.type = 'button'- const mark = element('span', '×'); mark.setAttribute('aria-hidden', 'true'); close.append(mark)- close.onclick = event => { event.stopPropagation(); state.selected = row.id; select(); reviewStop(row.id) }- actions.append(close); tr.append(actions)+ const actions = element('td', null, 'row-actions')+ for (const [verb, label] of [['stop', 'Stop Harness'], ['delete', 'Delete Harness']]) {+ const button = element('button', label, verb === 'delete' ? 'delete-harness danger' : 'stop-harness')+ button.type = 'button'; button.dataset.action = verb+ button.onclick = event => { event.stopPropagation(); state.selected = row.id; select(); reviewAction(row.id, verb) }+ actions.append(button)+ }+ tr.append(actions)return tr}function updateRow(tr, row) {for (const td of tr.children) {const key = td.dataset.key, col = COLUMNS.find(c => c.key === key)if (td.classList.contains('row-actions')) {- const close = td.firstChild- close.disabled = !canStop(row)- close.setAttribute('aria-label', 'Close ' + row.name)- close.title = state.busy.has(row.id) ? 'Closing…' : state.frozen ? 'Turn on live updates before closing.'- : !state.connected || !currentSnapshot() ? 'Reconnect before closing.'- : row.unavailable || (row.canStop ? 'Close ' + row.name : 'This harness is not ready to close.')- close.setAttribute('aria-busy', String(state.busy.has(row.id)))+ for (const button of td.children) {+ const deleting = button.dataset.action === 'delete'+ button.disabled = !(deleting ? canDelete(row) : canStop(row))+ button.setAttribute('aria-label', (deleting ? 'Delete Harness: ' : 'Stop Harness: ') + row.name)+ button.title = state.busy.has(row.id) ? 'Please wait…' : state.frozen ? 'Turn on live updates before acting.'+ : !state.connected || !currentSnapshot() ? 'Reconnect before acting.'+ : row.unavailable || (deleting ? 'Review permanent deletion of session data. Project files are kept.' : 'Stop running work. History and files are kept.')+ button.setAttribute('aria-busy', String(state.busy.has(row.id)))+ }} else if (key === 'name') {text(td.children[0], row.name)td.title = [row.name, row.home, row.model].filter(Boolean).join('\n')@@ -169,6 +177,7 @@ function updateRow(tr, row) {const currentSelection = () => state.shown.find(r => r.id === state.selected)const currentSnapshot = () => ['ok', 'degraded'].includes(state.snapshot?.status)const canStop = row => row?.canStop && isLive(row) && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)+const canDelete = row => row?.canDelete && row.online !== false && state.connected && currentSnapshot() && !state.frozen && !state.busy.has(row.id)function select() {for (const [id, node] of state.nodes) node.setAttribute('aria-selected', String(id === state.selected))dom.inspect.disabled = !currentSelection()@@ -180,10 +189,11 @@ function summary() {const resources = [...rows, ...shared]dom.summary.replaceChildren()for (const [label, total, format, hint] of [- ['CPU', sumReading(resources, 'cpu'), n => Math.round(n) + '%', '100% is one core. Shared servers count once.'],+ ['Workspace', storageTotal(rows), bytes, 'Disk space used by working folders. Shared and nested folders count once per machine. Inspect a harness to review worktree cleanup.'],+ ['Session data', sumReading(rows, 'sessionBytes'), bytes, 'Conversation history and checkpoints. Shared database content is approximate; project and worktree files are excluded.'],['RAM', sumReading(resources, 'rssBytes'), memory, 'Resident memory including child processes and shared servers once. Shared memory pages can overlap.'],+ ['CPU', sumReading(resources, 'cpu'), n => Math.round(n) + '%', '100% is one core. Shared servers count once.'],['GPU', sumReading(resources, 'gpuPercent'), n => Math.round(n) + '%', 'Harness process GPU use on supported macOS and Linux NVIDIA drivers. First samples and unavailable counters show —. Cloud model GPU usage is not reported.'],- ['SSD', storageTotal(rows.map(r => r.online === false ? { ...r, workspaceBytes: null } : r)), bytes, 'Workspace disk space. Shared and nested folders count once per machine. Stopping does not delete files.'],['Tokens', sumReading(rows, 'tokens'), number, 'Conversation totals for shown sessions. Cached input is included once.'],]) {const item = element('div', null, 'total'); item.title = hint + ' ≥ means a partial total.'@@ -225,7 +235,7 @@ function render() {text(dom.empty.firstElementChild, !ready ? 'Connecting to your machines…' : filtered ? 'No matching harnesses' : 'No open harnesses')text(dom.empty.lastElementChild, !ready ? 'Open harnesses will appear here.' : filtered ? 'Try another search, machine, or status.' : 'Harnesses appear here while they are open, including when idle.')const active = state.rows.filter(isLive).length- text(dom.count, `${filtered ? state.shown.length + ' of ' : ''}${active} open ${active === 1 ? 'harness' : 'harnesses'}`)+ text(dom.count, state.filter === 'stopped' ? `${state.shown.length} stopped harnesses` : `${filtered ? state.shown.length + ' of ' : ''}${active} open ${active === 1 ? 'harness' : 'harnesses'}`)text(dom.updated, state.frozen ? 'Updates frozen' : state.receivedAt ? 'Updated ' + age(state.receivedAt) : 'Connecting…')text(dom.live, state.frozen ? 'Frozen' : !state.connected ? 'Reconnecting' : state.snapshot?.status === 'starting' ? 'Connecting' : !currentSnapshot() ? 'Unavailable' : 'Live')dom.live.classList.toggle('inactive', state.frozen || !state.connected || !currentSnapshot())@@ -239,6 +249,8 @@ function inspect(id) {function renderInspector() {const row = state.rows.find(r => r.id === state.inspecting)dom.inspectStop.disabled = !canStop(row)+ dom.inspectDelete.disabled = !canDelete(row)+ dom.inspectWorktree.disabled = !canDelete(row)if (!row) { text(dom.inspectContext, 'This harness is no longer open.'); return }text(dom.inspectTitle, row.name)text(dom.inspectContext, [engineNames[row.engine] || row.engine, row.machine, ACTIVITY[row.activity]?.[1]].filter(Boolean).join(' · '))@@ -267,38 +279,85 @@ function renderInspector() {if (row.processCount > row.processes.length) processes.append(element('p', `Showing ${row.processes.length} of ${row.processCount} processes.`, 'muted'))}dom.inspectContent.append(processes)- const notes = element('p', 'GPU readings describe attributable processes on the owning machine, not a cloud model. Storage includes existing workspace files and remains after stopping. Missing readings are unavailable, not zero.', 'muted metric-note')+ const notes = element('p', 'Session data is conversation history and checkpoints. Workspace is the project or worktree folder. Delete Harness keeps workspace files. Delete Worktree separately reviews the checkout path, branch and uncommitted changes; the main project folder is protected. Missing readings are unavailable, not zero.', 'muted metric-note')dom.inspectContent.append(notes)}-function reviewStop(id) {- const row = state.rows.find(r => r.id === id); if (!canStop(row)) return- state.review = { id: row.id, sessionId: row.sessionId, lastActivity: row.lastActivity, name: row.name }- text(dom.stopTitle, 'Close “' + row.name + '”?')- text(dom.stopContext, `${row.machine} · ${ACTIVITY[row.activity]?.[1] || 'Unknown'} · ${memory(row.rssBytes)} RAM · ${number(row.tokens)} tokens`)- text(dom.stopResult, ''); dom.stopConfirm.disabled = false; dom.stopCancel.disabled = false+async function reviewAction(id, verb = 'stop') {+ const row = state.rows.find(r => r.id === id), deleting = verb === 'delete', worktree = verb === 'worktree-delete'+ if (!(deleting || worktree ? canDelete(row) : canStop(row))) return+ const review = { id: row.id, sessionId: row.sessionId, createdAt: row.createdAt, lastActivity: row.lastActivity, name: row.name, verb }+ state.review = review+ text(dom.stopTitle, worktree ? 'Delete worktree for “' + row.name + '”?' : (deleting ? 'Delete' : 'Stop') + ' “' + row.name + '”?')+ text(dom.stopContext, `${row.machine} · ${ACTIVITY[row.activity]?.[1] || 'Unknown'}`)+ text(dom.stopDescription, worktree ? 'Permanently remove this Git worktree and everything inside it, including ignored files such as dependencies and build output. This harness will stop. Its branch, commits and conversation history are kept.'+ : deleting ? 'Are you sure you want to permanently delete this harness and its saved conversation? Running work will stop. This cannot be undone.'+ : 'Its running work will end and its panes will close. Conversation history and project files are kept.')+ text(dom.stopStorage, deleting ? `Project and worktree files are kept. Workspace: ${row.workspacePath || row.home || 'unavailable'} (${bytes(row.workspaceBytes)}).` : '')+ text(dom.stopConfirm, worktree ? 'Delete Worktree' : deleting ? 'Delete Harness' : 'Stop Harness')+ text(dom.stopResult, worktree ? 'Checking the worktree and other harnesses…' : deleting ? 'Checking saved session data…' : '')+ dom.worktreeReview.hidden = true; dom.worktreePath.value = ''; dom.worktreeDiscard.checked = false+ dom.stopConfirm.disabled = deleting || worktree; dom.stopCancel.disabled = falsedom.stopDialog.showModal()+ if (!deleting && !worktree) return+ try {+ const reply = await post('/api/act', { verb: worktree ? 'worktree-review' : 'delete-review', ids: [review.id], manual: true, expected: [review] })+ if (state.review !== review || !dom.stopDialog.open) return+ const result = reply.results?.find(r => r.id === review.id)+ if (!result?.ok || !result.reviewId) throw new Error(result?.detail || 'Could not check session data. Refresh and try again.')+ review.reviewId = result.reviewId+ if (worktree) {+ if (!result.worktree?.path) throw new Error('The worktree path could not be verified.')+ review.worktree = result.worktree+ dom.worktreeDetails.replaceChildren()+ for (const [label, value] of [['Delete folder', review.worktree.path], ['Disk space', bytes(review.worktree.bytes)], ['Branch kept', review.worktree.branch || 'Detached; commits are saved on a branch'], ['Main project kept', review.worktree.main]]) {+ dom.worktreeDetails.append(element('dt', label), element('dd', value))+ }+ text(dom.worktreeChanges, review.worktree.changes.join('\n'))+ dom.worktreeChanges.hidden = !review.worktree.dirty+ dom.worktreeDiscardLabel.hidden = !review.worktree.dirty+ dom.worktreeReview.hidden = false+ text(dom.stopResult, review.worktree.dirty ? 'Uncommitted changes are present (up to 12 entries shown). They cannot be recovered from Git after deletion.' : 'The worktree has no uncommitted changes. Recreate its checkout to resume work later.')+ return+ }+ text(dom.stopResult, result.sharedStore ? `Approximately ${bytes(result.sessionBytes)} of session data will be removed. Shared database space can be reused; its file may not shrink immediately.`+ : `Session files to delete: approximately ${bytes(result.sessionBytes)}. The final size may change as running work stops.`)+ dom.stopConfirm.disabled = false+ } catch (error) { if (state.review === review && dom.stopDialog.open) text(dom.stopResult, error.message) }}dom.inspect.onclick = () => inspect(state.selected)-dom.inspectStop.onclick = () => reviewStop(state.inspecting)+dom.inspectStop.onclick = () => reviewAction(state.inspecting)+dom.inspectDelete.onclick = () => reviewAction(state.inspecting, 'delete')+dom.inspectWorktree.onclick = () => reviewAction(state.inspecting, 'worktree-delete')+function validateWorktreeConfirmation() {+ const review = state.review+ if (review?.verb === 'worktree-delete') dom.stopConfirm.disabled = !review.worktree || !review.reviewId+ || state.busy.has(review.id) || dom.worktreePath.value !== review.worktree.path || (review.worktree.dirty && !dom.worktreeDiscard.checked)+}+dom.worktreePath.oninput = validateWorktreeConfirmation+dom.worktreeDiscard.onchange = validateWorktreeConfirmationdom.inspectClose.onclick = () => dom.inspector.close()-dom.stopCancel.onclick = () => dom.stopDialog.close()-dom.stopDialog.addEventListener('cancel', event => { if (state.busy.has(state.review?.id)) event.preventDefault() })+dom.stopCancel.onclick = () => { state.review = null; dom.stopDialog.close() }+dom.stopDialog.addEventListener('cancel', event => { if (state.busy.has(state.review?.id)) event.preventDefault(); else state.review = null })dom.stopConfirm.onclick = async () => {const review = state.reviewif (!review || state.busy.has(review.id)) return- const row = state.rows.find(r => r.id === review.id)- if (!canStop(row) || row.sessionId !== review.sessionId) {+ const deleting = review.verb === 'delete', worktree = review.verb === 'worktree-delete', row = state.rows.find(r => r.id === review.id)+ if (worktree && (!review.worktree || dom.worktreePath.value !== review.worktree.path || (review.worktree.dirty && !dom.worktreeDiscard.checked))) return+ if (!(deleting || worktree ? canDelete(row) : canStop(row)) || row.sessionId !== review.sessionId || row.createdAt !== review.createdAt || ((deleting || worktree) && !review.reviewId)) {text(dom.stopResult, 'This session or connection changed. Cancel, refresh and review it again.')- dom.stopConfirm.disabled = true- return+ dom.stopConfirm.disabled = true; return}- state.busy.add(review.id); dom.stopConfirm.disabled = true; dom.stopCancel.disabled = true; text(dom.stopResult, 'Closing…'); render()+ state.busy.add(review.id); dom.stopConfirm.disabled = true; dom.stopCancel.disabled = true+ text(dom.stopResult, worktree ? 'Stopping and deleting the worktree…' : deleting ? 'Deleting session data…' : 'Stopping…'); render()try {- const reply = await post('/api/act', { verb: 'stop', ids: [review.id], manual: true, expected: [review] })+ const reply = await post('/api/act', { verb: review.verb, ids: [review.id], manual: true, expected: [review], reviewId: review.reviewId,+ ...(worktree ? { path: dom.worktreePath.value, discardChanges: dom.worktreeDiscard.checked } : {}) })const result = reply.results?.find(r => r.id === review.id)- if (!result?.ok) { text(dom.stopResult, result?.detail || 'Close was not confirmed. Refresh to check.'); return }- state.rows = state.rows.filter(r => r.id !== review.id || r.sessionId !== review.sessionId)- message('Closed ' + review.name + '. History and files kept.'); dom.stopDialog.close()+ if (!result?.ok) { text(dom.stopResult, result?.detail || 'The action was not confirmed. Refresh to check.'); return }+ if (deleting) state.rows = state.rows.filter(r => r.id !== review.id || r.sessionId !== review.sessionId)+ else { const stopped = state.rows.find(r => r.id === review.id); if (stopped) Object.assign(stopped, { state: 'stopped', activity: 'stopped', live: false, canStop: false, ...(worktree ? { workspaceBytes: null } : {}) }) }+ message(worktree ? 'Worktree deleted. Branch and conversation history kept.' : deleting ? 'Deleted ' + review.name + '. Project files kept.' : 'Stopped ' + review.name + '. History and files kept.')+ state.review = null; dom.stopDialog.close()if (dom.inspector.open && state.inspecting === review.id) dom.inspector.close()dom.grid.focus({ preventScroll: true })} catch (error) { text(dom.stopResult, error.message + ' Refresh to check before trying again.') }@@ -314,7 +373,7 @@ dom.grid.onkeydown = event => {const next = event.key === 'Home' ? 0 : event.key === 'End' ? state.shown.length - 1 : Math.max(0, Math.min(state.shown.length - 1, index + (event.key === 'ArrowUp' ? -1 : 1)))state.selected = state.shown[next]?.id ?? null; select(); state.nodes.get(state.selected)?.scrollIntoView({ block: 'nearest', inline: 'nearest' })} else if (event.key === 'Enter' && state.selected) { event.preventDefault(); inspect(state.selected) }- else if (['Delete', 'Backspace'].includes(event.key) && state.selected) { event.preventDefault(); reviewStop(state.selected) }+ else if (['Delete', 'Backspace'].includes(event.key) && state.selected) { event.preventDefault(); reviewAction(state.selected, 'delete') }}document.addEventListener('keydown', event => {if (event.key === 'Escape' && dom.columns.open) { dom.columns.open = false; dom.columns.querySelector('summary').focus() }@@ -332,7 +391,7 @@ dom.freeze.onclick = () => {render()}function applySnapshot(snapshot) {- state.snapshot = snapshot; state.rows = (snapshot.rows ?? []).filter(isLive); state.receivedAt = Date.now()+ state.snapshot = snapshot; state.rows = (snapshot.rows ?? []).filter(row => row.online !== false); state.receivedAt = Date.now()const machines = new Map((snapshot.machines ?? []).map(m => [m.machineId, m.name]))for (const row of state.rows) machines.set(row.machineId, row.machine)const signature = JSON.stringify([...machines])diff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.htmlindex d0d9c1520..8852af446 100644--- a/store/agents/harness-monitor/viewer/index.html+++ b/store/agents/harness-monitor/viewer/index.html@@ -20,7 +20,7 @@<div class="segmented" role="group" aria-label="Column presets"><button data-preset="overview" aria-pressed="true">Overview</button><button data-preset="resources" aria-pressed="false">Resources</button><button data-preset="ai" aria-pressed="false">AI usage</button></div><label class="sr-only" for="machine">Machine</label><select id="machine"><option value="all">All machines</option></select><label class="sr-only" for="filter">Status</label><select id="filter">- <option value="all">All open harnesses</option><option value="working">Working</option><option value="needsInput">Needs you</option>+ <option value="all">Open harnesses</option><option value="stopped">Stopped harnesses</option><option value="working">Working</option><option value="needsInput">Needs you</option><option value="idle">Idle</option><option value="done">Done</option><option value="starting">Starting</option><option value="failed">Failed</option><option value="unknown">Unknown</option></select><span class="spacer"></span>@@ -29,7 +29,7 @@<button id="freeze" title="Hold the displayed readings; running work continues">Freeze updates</button><button id="refresh" title="Refresh all machines">Refresh</button></nav><div id="problems" role="status" hidden></div>- <main id="grid" tabindex="0" aria-label="Open harnesses. Arrow keys select, Enter inspects, Delete reviews closing.">+ <main id="grid" tabindex="0" aria-label="Open harnesses. Arrow keys select, Enter inspects, Delete reviews permanent deletion."><table id="table" aria-label="Open harnesses"><colgroup id="colgroup"></colgroup><thead id="head"></thead><tbody id="body"></tbody></table><div id="empty"><strong>Connecting to your machines…</strong><p>Open harnesses will appear here.</p></div></main>@@ -39,12 +39,19 @@<dialog id="inspector" aria-labelledby="inspect-title"><div class="dialog-heading"><h2 id="inspect-title">Harness details</h2><button id="inspect-close" aria-label="Close details">Close</button></div><p id="inspect-context" class="muted"></p><div id="inspect-content"></div>- <div class="dialog-actions"><button id="inspect-stop" class="danger">Close harness…</button></div>+ <div class="dialog-actions"><button id="inspect-worktree" class="danger">Delete Worktree…</button><button id="inspect-stop">Stop Harness</button><button id="inspect-delete" class="danger">Delete Harness</button></div></dialog><dialog id="stop-dialog" aria-labelledby="stop-title">- <h2 id="stop-title">Close harness?</h2><p id="stop-context"></p><p>Its running work will end and its panes will close. Conversation history and workspace files are kept.</p>+ <h2 id="stop-title">Stop harness?</h2><p id="stop-context"></p><p id="stop-description"></p><p id="stop-storage" class="muted"></p>+ <div id="worktree-review" hidden>+ <dl id="worktree-details" class="worktree-details"></dl>+ <pre id="worktree-changes" hidden></pre>+ <label id="worktree-discard-label" hidden><input id="worktree-discard" type="checkbox"> Permanently discard all uncommitted changes and untracked files.</label>+ <label for="worktree-path">Type the full worktree path to confirm</label>+ <input id="worktree-path" type="text" autocomplete="off" spellcheck="false">+ </div><p id="stop-result" role="status" aria-live="polite"></p>- <div class="dialog-actions"><button id="stop-cancel" autofocus>Cancel</button><button id="stop-confirm" class="danger filled">Close harness</button></div>+ <div class="dialog-actions"><button id="stop-cancel" autofocus>Cancel</button><button id="stop-confirm" class="danger filled">Stop Harness</button></div></dialog><script type="module" src="app.js"></script></body>diff --git a/store/agents/harness-monitor/viewer/table.js b/store/agents/harness-monitor/viewer/table.jsindex 22d8be551..de5906e1e 100644--- a/store/agents/harness-monitor/viewer/table.js+++ b/store/agents/harness-monitor/viewer/table.js@@ -8,10 +8,11 @@ export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧',export const COLUMNS = [{ key: 'name', label: 'Harness', width: 230, required: true, group: 'Session' },{ key: 'activity', label: 'Status', width: 112, group: 'Session' },- { key: 'cpu', label: 'CPU %', width: 80, numeric: true, group: 'Resources', help: 'Interval CPU of this process tree. 100% is one core; multiple cores can exceed 100%.' },+ { key: 'workspaceBytes', label: 'Workspace', width: 120, numeric: true, group: 'Resources', help: 'Disk space used by the entire working folder: a project, worktree or subfolder. Shared folders repeat per row. Inspect to review separate Git worktree cleanup. Delete Harness keeps these files.' },+ { key: 'sessionBytes', label: 'Session data', width: 130, numeric: true, group: 'Resources', help: 'Conversation history and Harness checkpoints stored on disk. Database sizes estimate conversation content, not the whole shared database. Deletion keeps project files. — means not measured.' },{ key: 'rssBytes', label: 'RAM', width: 88, numeric: true, group: 'Resources', help: 'Resident memory, including child processes. Shared memory pages can overlap. Shared servers appear separately.' },+ { key: 'cpu', label: 'CPU %', width: 80, numeric: true, group: 'Resources', help: 'Interval CPU of this process tree. 100% is one core; multiple cores can exceed 100%.' },{ key: 'gpuPercent', label: 'GPU %', width: 80, numeric: true, group: 'Resources', help: 'GPU use of this process tree: GPU time per interval on supported macOS drivers, utilization on Linux NVIDIA. Can exceed 100% across processes or devices. First samples and unavailable counters show —. Cloud model GPU usage is not reported.' },- { key: 'workspaceBytes', label: 'SSD', width: 88, numeric: true, group: 'Resources', help: 'Workspace disk space, including existing files. Shared folders repeat per row but count once in totals. Updated at most once a minute; stopping keeps these files.' },{ key: 'engine', label: 'Agent', width: 118, group: 'Session' },{ key: 'tokens', label: 'Tokens', width: 98, numeric: true, group: 'AI usage', help: 'Total conversation input and output, including cached input once. Reported by the owning agent; — means unreported.' },{ key: 'machine', label: 'Machine', width: 120, group: 'Session' },@@ -36,18 +37,18 @@ export const COLUMNS = []export const PRESETS = {overview: COLUMNS.filter(c => !c.optional).map(c => c.key),- resources: ['name', 'activity', 'cpu', 'rssBytes', 'gpuPercent', 'workspaceBytes', 'gpuMemoryBytes', 'diskReadBytesPerSecond', 'diskWriteBytesPerSecond', 'processCount', 'machine'],+ resources: ['name', 'activity', 'workspaceBytes', 'sessionBytes', 'rssBytes', 'cpu', 'gpuPercent', 'gpuMemoryBytes', 'diskReadBytesPerSecond', 'diskWriteBytesPerSecond', 'processCount', 'machine'],ai: ['name', 'activity', 'engine', 'machine', 'model', 'tokens', 'tokensPerMinute', 'inputTokens', 'outputTokens', 'cachedTokens', 'lastActivity'],}// Activity describes what an open harness is doing, not whether it is open.-// Saved history and cached offline inventory never become process rows.+// Saved harnesses appear only in the explicit Stopped harnesses view.export const isLive = row => row.online !== false&& !['stopped', 'offline', 'gone'].includes(row.state)&& !['stopped', 'offline'].includes(row.activity)&& (row.live ?? ['running', 'terminal', 'starting'].includes(row.state))-export function visibleRows(rows, { query = '', filter = 'all', machine = 'all', sort = 'rssBytes', direction = -1 } = {}) {+export function visibleRows(rows, { query = '', filter = 'all', machine = 'all', sort = 'workspaceBytes', direction = -1 } = {}) {const q = query.trim().toLocaleLowerCase(), rank = Object.keys(ACTIVITY)- return rows.filter(row => isLive(row) && (machine === 'all' || row.machineId === machine)+ return rows.filter(row => (filter === 'stopped' ? row.online !== false && row.state === 'stopped' : isLive(row)) && (machine === 'all' || row.machineId === machine)&& (filter === 'all' || row.activity === filter)&& (!q || [row.name, row.title, row.engine, row.machine, row.project, row.branch, row.model, row.agentId, row.sessionId, row.home].some(v => String(v ?? '').toLocaleLowerCase().includes(q))))@@ -72,7 +73,7 @@ export const age = (stamp, now = Date.now()) => {}export function formatValue(key, value) {if (['cpu', 'gpuPercent'].includes(key)) return percent(value)- if (['rssBytes', 'workspaceBytes', 'gpuMemoryBytes', 'transcriptBytes'].includes(key)) return bytes(value)+ if (['rssBytes', 'sessionBytes', 'workspaceBytes', 'gpuMemoryBytes', 'transcriptBytes'].includes(key)) return bytes(value)if (key.endsWith('PerSecond')) return value == null ? '—' : bytes(value) + '/s'if (['tokens', 'inputTokens', 'outputTokens', 'cachedTokens', 'tokensPerMinute'].includes(key)) return number(value)if (['lastActivity', 'createdAt'].includes(key)) return age(value)