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
Count free and reclaimable memory on macOS; release agents closed by hand (#1542)
0xken150ac558817b17
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 0270030de..1d6a99efd 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -134,7 +134,7 @@ describe('the core API services stand on', () => {advertised: vi.fn(() => [row('live')]),terminalAvailable: vi.fn((agentId: string) => agentId === 'live'),} as unknown as CoreApiDeps['registry'],- stoppedAgents: { list: vi.fn(() => [row('stopped')]) } as unknown as CoreApiDeps['stoppedAgents'],+ stoppedAgents: { list: vi.fn(() => [row('stopped')]), ids: vi.fn(() => ['stopped']) } as unknown as CoreApiDeps['stoppedAgents'],databaseHistory: vi.fn(),syncSession: vi.fn(),runtimeModels: vi.fn(async () => []),@@ -206,6 +206,10 @@ describe('the core API services stand on', () => {expect(await core.agents.stopped!('live')).toBe(false)expect(await core.agents.stopped!('unknown')).toBe(false)expect(await core.agents.stopped!('stopped')).toBe(true)+ // Gone is neither live nor kept: an agent closed by hand, never a live or stopped one.+ expect(await core.agents.gone!('live')).toBe(false)+ expect(await core.agents.gone!('stopped')).toBe(false)+ expect(await core.agents.gone!('closed-by-hand')).toBe(true)expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])expect(core.agents.displayName).toBe(projectDisplayName)expect(core.transcripts.databaseHistory).toBe(deps.databaseHistory)diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex e0028f25c..cb1b01db1 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -164,6 +164,9 @@ export interface CoreApi {/** Fresh native lifecycle evidence. Absence from a live snapshot alone is* not a stop: a saved stopped record must also exist in the core. */stopped?(agentId: string): Promise<boolean>+ /** The agent is neither live nor kept as a stopped record: closed by hand, or its record deleted. Only for an agent+ * the caller already knows was created; it does not prove an agent that is still starting is gone. */+ gone?(agentId: string): Promise<boolean>/** The exact durable native creation receipt. Null means unavailable, never* proof that a launch was missing, cancelled or failed. */creationStatus?(creationId: string): Promise<CreationObservation | null>@@ -1727,7 +1730,7 @@ export interface CoreApiDeps {conversations?: ConversationReadsdataDir: stringregistry: Pick<typeof registry, 'list' | 'byAgent' | 'resolve' | 'advertised' | 'terminalAvailable'>- stoppedAgents: Pick<StoppedAgentStore, 'list'>+ stoppedAgents: Pick<StoppedAgentStore, 'list' | 'ids'>databaseHistory: CoreApi['transcripts']['databaseHistory']syncSession: CoreApi['agents']['sync']runtimeModels: CoreApi['agents']['runtimeModels']@@ -1818,6 +1821,7 @@ export function createCoreApi({agents: {all: () => [...registry.list(), ...stoppedAgents.list()],stopped: async id => !registry.byAgent(id) && stoppedAgents.list().some(s => s.agentId === id),+ gone: async id => !registry.byAgent(id) && !stoppedAgents.ids().includes(id),live: () => registry.list(),displayName: projectDisplayName,byAgent: (agentId) => registry.byAgent(agentId),diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.tsindex a3836f6cd..6d85e422a 100644--- a/cli/src/core/experimentQueries.spec.ts+++ b/cli/src/core/experimentQueries.spec.ts@@ -69,6 +69,14 @@ describe('what an experiment in its own process may ask of the core', () => {expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'stopped', { agentId: 'unknown' })).toEqual({ stopped: false })})+ it('says an agent is gone only on fresh evidence, and not for a core that cannot tell', async () => {+ const core = fakeCore({ agents: { gone: async id => id === 'closed' } })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'gone', { agentId: 'closed' })).toEqual({ gone: true })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'gone', { agentId: 'live' })).toEqual({ gone: false })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'gone', {})).toEqual({ gone: false })+ expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'gone', { agentId: 'closed' })).toEqual({ gone: false })+ })+it('bounds native observation queries and keeps an older core unavailable', async () => {const cursor = { epoch: 'fixture-observation-epoch', sequence: 0 }const page = { cursor, observations: [], gap: false }, nativeTurns = vi.fn(async () => page)diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.tsindex 302851a14..992194b3c 100644--- a/cli/src/core/experimentQueries.ts+++ b/cli/src/core/experimentQueries.ts@@ -34,7 +34,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'type Payload = Record<string, unknown>type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>-const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention'])+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention'])const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])const text = (value: unknown): string => (typeof value === 'string' ? value : '')@@ -82,6 +82,8 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet}case 'stopped':return { stopped: !!text(payload.agentId) && await core.agents.stopped?.(text(payload.agentId)) === true }+ case 'gone':+ return { gone: !!text(payload.agentId) && await core.agents.gone?.(text(payload.agentId)) === true }case 'creation_status':return { observation: await core.agents.creationStatus?.(text(payload.creationId)) ?? null }case 'native_turns': {diff --git a/cli/src/lib/machineHardware.spec.ts b/cli/src/lib/machineHardware.spec.tsindex ea94c01bd..a182b38ea 100644--- a/cli/src/lib/machineHardware.spec.ts+++ b/cli/src/lib/machineHardware.spec.ts@@ -12,6 +12,7 @@ vi.mock('node:os', () => ({ totalmem: () => 8 * 1024 ** 3, freemem: () => 1024 *const platform = Object.getOwnPropertyDescriptor(process, 'platform')!const vm = `Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages free: 10.Pages active: 100.Pages inactive: 80.Pages speculative: 20.@@ -26,9 +27,9 @@ afterEach(() => {})describe('host memory counters', () => {- it('subtracts reclaimable cache on macOS and reads pressure and swap separately', () => {+ it('counts reclaimable cache on macOS and reads pressure and swap separately', () => {expect(parseDarwinMemory(vm, 8 * 1024 ** 3, '2\ntotal = 2048.00M used = 512.50M free = 1535.50M')).toEqual({- total: 8 * 1024 ** 3, available: 8 * 1024 ** 3 - 180 * 16384,+ total: 8 * 1024 ** 3, available: 110 * 16384,pressure: 'warning', swapUsedBytes: 512.5 * 1024 ** 2,})expect(parseDarwinMemory(vm, 8 * 1024 ** 3, '4')?.pressure).toBe('critical')@@ -37,6 +38,48 @@ describe('host memory counters', () => {expect(parseDarwinMemory(vm, 10, '')).toBeNull()})+ it('counts free, inactive, speculative and purgeable pages as available on a real 32 GiB Mac, with pressure still read', () => {+ // Captured with vm_stat on Ken's Mac, 2026-10-22: the old reading was 4.97 GiB available.+ const captured = `Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages free: 3903.+Pages active: 461392.+Pages inactive: 454033.+Pages speculative: 4048.+Pages throttled: 0.+Pages wired down: 317343.+Pages purgeable: 2.+"Translation faults": 71752690153.+Pages copy-on-write: 6554736573.+Pages zero filled: 16855483380.+Pages reactivated: 15019288823.+Pages purged: 330844917.+File-backed pages: 266250.+Anonymous pages: 653223.+Pages stored in compressor: 3299063.+Pages occupied by compressor: 801186.+Decompressions: 14988704555.+Compressions: 15710187605.+Pageins: 1010109106.+Pageouts: 7338882.+Swapins: 95450347.+Swapouts: 100622631.+`+ const reading = parseDarwinMemory(captured, 32 * 1024 ** 3, '2\ntotal = 16384.00M used = 15304.62M free = 1079.38M (encrypted)')!+ expect(reading.available).toBe((3903 + 454033 + 4048) * 16384)+ expect(reading.available / 1024 ** 3).toBeCloseTo(7.05, 2)+ expect(reading.pressure).toBe('warning')+ expect(parseDarwinMemory(captured, 32 * 1024 ** 3, '4')).toMatchObject({ available: reading.available, pressure: 'critical' })+ })++ it('takes the larger of two overlapping views, never their sum, and no more than what is not wired or compressed', () => {+ const only = (text: string) => parseDarwinMemory(text, 8 * 1024 ** 3, '')!.available+ // Speculative pages (20) are in the file-backed count too: 10 free + max(80 + 20, 300 + 10), not 10 + 80 + 20 + 300.+ expect(only(vm.replace('File-backed pages: 90', 'File-backed pages: 300'))).toBe((10 + 310) * 16384)+ expect(only(vm.replace('Pages wired down: 50', 'Pages wired down: 524200'))).toBe(8 * 1024 ** 3 - (524200 + 30) * 16384)+ expect(parseDarwinMemory(vm.replace('Pages wired down: 50', 'Pages wired down: 999999'), 8 * 1024 ** 3, '')).toBeNull()+ expect(parseDarwinMemory(vm.replace('Pages free: 10.\n', ''), 8 * 1024 ** 3, '')).toBeNull()+ })+it('uses Linux available memory rather than counting cache as used', () => {expect(parseLinuxMemory('MemAvailable: 4096 kB\nSwapTotal: 1024 kB\nSwapFree: 512 kB\n', 8 * 1024 ** 2)).toEqual({ total: 8 * 1024 ** 2, available: 4 * 1024 ** 2, swapUsedBytes: 512 * 1024 })diff --git a/cli/src/lib/machineHardware.ts b/cli/src/lib/machineHardware.tsindex c4ef0079a..b81714810 100644--- a/cli/src/lib/machineHardware.ts+++ b/cli/src/lib/machineHardware.ts@@ -66,16 +66,23 @@ export function parseDarwinMemory(vm: string, total: number, sysctl: string): Meif (!pageSize || !Number.isFinite(total) || total <= 0) return nullconst counts = new Map<string, number>()for (const match of vm.matchAll(/^([^:\n]+):\s+(\d+)\.?\s*$/gm)) counts.set(match[1].trim(), Number(match[2]))- const keys = ['Pages active', 'Pages inactive', 'Pages speculative', 'Pages wired down',- 'Pages occupied by compressor', 'Pages purgeable', 'File-backed pages']+ const keys = ['Pages free', 'Pages inactive', 'Pages speculative', 'Pages wired down', 'Pages occupied by compressor', 'Pages purgeable', 'File-backed pages']if (keys.some(key => !counts.has(key))) return null- const used = (keys.slice(0, 5).reduce((sum, key) => sum + counts.get(key)!, 0)- - counts.get('Pages purgeable')! - counts.get('File-backed pages')!) * pageSize- if (!Number.isFinite(used) || used < 0 || used > total) return null+ const page = (key: string) => counts.get(key)!+ // Free pages, plus what the kernel can drop or recycle. Two overlapping views of that: the inactive and+ // speculative queues, and the file-backed and purgeable pages, which sit across the active, inactive and+ // speculative queues. Adding them would count some pages twice, so take the larger. Inactive anonymous pages are+ // only freed by compressing or swapping them, so this is an upper estimate, bounded by the memory that is+ // neither wired nor held by the compressor (counting compressed pages as used read 5 GiB on a 32 GiB Mac+ // with 7 GiB free or reclaimable, 2026-10-22).+ const reclaimable = (page('Pages free') + Math.max(page('Pages inactive') + page('Pages speculative'),+ page('File-backed pages') + page('Pages purgeable'))) * pageSize+ const available = Math.min(reclaimable, total - (page('Pages wired down') + page('Pages occupied by compressor')) * pageSize)+ if (!Number.isFinite(available) || available < 0) return nullconst pressureLevel = /^\s*([124])\s*$/m.exec(sysctl)?.[1]const swap = /used\s*=\s*([\d.]+)([KMG])\b/.exec(sysctl)const swapValue = number(swap?.[1])- return { total, available: total - used,+ return { total, available,pressure: pressureLevel === '1' ? 'normal' : pressureLevel === '2' ? 'warning' : pressureLevel === '4' ? 'critical' : null,swapUsedBytes: swap && swapValue != null ? swapValue * ({ K: KiB, M: MiB, G: KiB ** 3 }[swap[2]]!) : null,}diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex 931510246..39ea87057 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -343,6 +343,16 @@ it('asks for native stop evidence and treats an absent or failed link as unknownexpect(await processCoreApi('/data', 'superTabs').agents.stopped!('a')).toBe(false)})+it('asks whether an agent is gone and treats an absent or failed link as not gone', async () => {+ const ask = vi.fn(async (): Promise<Record<string, unknown>> => ({ gone: true }))+ const api = processCoreApi('/data', 'superTabs', { ask })+ expect(await api.agents.gone!('a')).toBe(true)+ expect(ask).toHaveBeenLastCalledWith('gone', { agentId: 'a' })+ ask.mockRejectedValueOnce(new Error('offline'))+ expect(await api.agents.gone!('a')).toBe(false)+ expect(await processCoreApi('/data', 'superTabs').agents.gone!('a')).toBe(false)+})+it('carries the exact native close identity through the service process and fails closed without the core', async () => {const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: '2026-10-22T00:00:00.000Z' }const ask = vi.fn(async () => ({ closed: true as const }))diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex f719da9f1..fc9756216 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -123,6 +123,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViecloseSwarm: async request => await (ask?.('close_swarm', { ...request }) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' })).catch(() => ({ error: 'SERVICE_UNAVAILABLE' })),stopped: async agentId => (await ask?.('stopped', { agentId }).catch(() => null))?.stopped === true,+ gone: async agentId => (await ask?.('gone', { agentId }).catch(() => null))?.gone === true,creationStatus: async creationId => creationObservation(creationId,(await ask?.('creation_status', { creationId }).catch(() => null))?.observation),resolve: (id) => resolveAgent(live(), id),diff --git a/cli/src/superTabs/reservations.spec.ts b/cli/src/superTabs/reservations.spec.tsindex 14c5a5a34..d0c4f1f90 100644--- a/cli/src/superTabs/reservations.spec.ts+++ b/cli/src/superTabs/reservations.spec.ts@@ -16,17 +16,18 @@ const id = (n: number) => `fixture-creation-${n}`const input = (n = 1, memory = 60, disk = 60) => ({ creationId: id(n), cwd: '/fixture/repo', requirements: { memoryBytes: memory, diskBytes: disk, maxCpuPercent: 80 } })function setup() {const directory = mkdtempSync(join(tmpdir(), 'super-tab-capacity-')); folders.push(directory)- const native = new Map<string, CreationObservation | null>(), stopped = new Set<string>()+ const native = new Map<string, CreationObservation | null>(), stopped = new Set<string>(), gone = new Set<string>()const core = fakeCore({ dataDir: directory, agents: {creationStatus: vi.fn(async key => native.has(key) ? native.get(key)! : { creationId: key, state: 'missing' as const }),stopped: vi.fn(async key => stopped.has(key)),+ gone: vi.fn(async key => gone.has(key)),} })const resources: MachineResources = { cpuPercent: 20, memoryTotalBytes: 150, memoryUsedBytes: 50 }const deps = { resources: vi.fn(async () => resources),disk: vi.fn(async (cwd: string) => ({ freeBytes: 100, volume: cwd === '/second-volume' ? 'second' : 'first', path: cwd })),sqlite: () => builtinSqlite() as never }const open = () => { const book = new CapacityReservations(core, 'machine-1', deps); books.push(book); return book }- return { directory, file: join(directory, 'super-tabs/capacity.sqlite'), core, native, stopped, resources, deps, open }+ return { directory, file: join(directory, 'super-tabs/capacity.sqlite'), core, native, stopped, gone, resources, deps, open }}it('serializes simultaneous starts across books and accounts for their declared budgets', async () => {@@ -90,6 +91,38 @@ it('recovers a harness that started and stopped before the service observed itsexpect(await book.reserve(input(2))).toMatchObject({ ok: true })})+it('releases the memory of an agent the person closed by hand, on the next reserve, and keeps a running one', async () => {+ const f = setup(), book = f.open()+ await book.reserve(input(1, 100))+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'closed-by-hand' })+ expect(await book.reserve(input(2, 100))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('memory') })+ f.gone.add('closed-by-hand')+ expect(await book.reserve(input(2, 100))).toMatchObject({ ok: true })+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'closed-by-hand', released: true })+ f.native.set(id(2), { creationId: id(2), state: 'pending' })+ f.gone.add('never-asked')+ expect(await book.reserve(input(3, 100))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })+})++it('frees the disk of an agent the person closed by hand together with its memory', async () => {+ const f = setup(), book = f.open()+ await book.reserve(input(1, 0, 60))+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'closed-by-hand' })+ expect(await book.reserve(input(2, 0, 60))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('disk') })+ f.gone.add('closed-by-hand')+ expect(await book.reserve(input(2, 0, 60))).toMatchObject({ ok: true })+})++it('does not release on a gone answer that fails or that an older core cannot give', async () => {+ const f = setup(), book = f.open()+ await book.reserve(input(1, 100))+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'native' })+ vi.mocked(f.core.agents.gone!).mockRejectedValueOnce(new Error('offline'))+ expect(await book.reserve(input(2, 100))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })+ delete (f.core.agents as { gone?: unknown }).gone+ expect(await book.reserve(input(2, 100))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })+})+it('reserves disk on its destination volume and keeps separate volumes independent', async () => {const f = setup(), book = f.open()await book.reserve(input(1, 0, 60))diff --git a/cli/src/superTabs/reservations.ts b/cli/src/superTabs/reservations.tsindex 84361392e..8b759f668 100644--- a/cli/src/superTabs/reservations.ts+++ b/cli/src/superTabs/reservations.ts@@ -132,8 +132,10 @@ export class CapacityReservations implements ReservationBook {const observation = await this.native(row.creation_id)const harnessId = observation?.state === 'created' ? observation.agentId : row.harness_idif (row.harness_id && harnessId !== row.harness_id) throw new Error('The native creation identity changed. Inspect this machine before starting more agents.')+ // A stopped agent keeps its record; one the person closed by hand does not, and neither is running.const released = observation?.state === 'failed' || observation?.state === 'cancelled'|| (!!harnessId && await this.core.agents.stopped?.(harnessId).catch(() => false) === true)+ || (observation?.state === 'created' && await this.core.agents.gone?.(harnessId!).catch(() => false) === true)return { row, harnessId, released }}))this.transaction(() => {