Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(reaper): see the host's real pressure, not one instance's slice
enesd7b5a3b914a0
diff --git a/src/core/pty-background-write.test.ts b/src/core/pty-background-write.test.tsindex 0c617e1a4..819f07974 100644--- a/src/core/pty-background-write.test.ts+++ b/src/core/pty-background-write.test.ts@@ -435,7 +435,10 @@ describe('background writes into released sessions', () => {await m.backgroundWrite('node-1', 'ls\n')const NOW = 1_000_000- const OLD = NOW - 100_000 // well past the 6h grace window+ const OLD = NOW - 100_000 // well past the 6h grace window: no PANE OUTPUT since then+ // `#{session_activity}` stays FRESH, the shape a live host always has — the reaper gates on+ // last pane output now, not on when a client last attached. See SessionInfo.activitySec.+ const FRESH = NOW - 60const killed: Array<{ socket: string; target: string }> = []const reaper = createSessionReaper({tmuxBin: () => m.getTmuxBin(),@@ -451,7 +454,7 @@ describe('background writes into released sessions', () => {}// `nt-node-1` reads as attached because our shared client IS one; `nt-node-9` is genuinely// attached (somebody is looking at it) and must survive.- return `nt-node-1|1|${OLD}\nnt-node-9|1|${OLD}`+ return `nt-node-1|1|${FRESH}|${OLD}\nnt-node-9|1|${FRESH}|${OLD}`},readMem: () => ({ availableMb: 100, totalMb: 8000 }), // under the watermark: real pressureenv: {},diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.tsindex 3492ba241..f1fa4a31e 100644--- a/src/core/pty-shadow.test.ts+++ b/src/core/pty-shadow.test.ts@@ -423,14 +423,17 @@ describe('control-mode shadow clients for released sessions', () => {await m.shadowAttach('node-1')const NOW = 1_000_000- const OLD = NOW - 100_000 // well past the 6h grace window+ const OLD = NOW - 100_000 // well past the 6h grace window: no PANE OUTPUT since then+ // `#{session_activity}` stays FRESH, the shape a live host always has — the reaper gates on+ // last pane output now, not on when a client last attached. See SessionInfo.activitySec.+ const FRESH = NOW - 60const listings: Record<string, string> = {// `nt-node-1` reads as attached because our shadow IS a real tmux client; `nt-node-9` is a// genuinely attached session (somebody is looking at it) and must survive.- 'node-terminal': `nt-node-1|1|${OLD}\nnt-node-9|1|${OLD}`,+ 'node-terminal': `nt-node-1|1|${FRESH}|${OLD}\nnt-node-9|1|${FRESH}|${OLD}`,// The SAME NAME on the SSH-remote socket, attached for real. Shadows only ever live on the// local socket, so the exclusion must not follow the name across sockets.- 'nodeterm-rmt': `nt-node-1|1|${OLD}`+ 'nodeterm-rmt': `nt-node-1|1|${FRESH}|${OLD}`}const killed: Array<{ socket: string; target: string }> = []const reaper = createSessionReaper({@@ -469,7 +472,8 @@ describe('control-mode shadow clients for released sessions', () => {await m.shadowAttach('node-2')const NOW = 1_000_000- const OLD = NOW - 100_000+ const OLD = NOW - 100_000 // no PANE OUTPUT since then+ const FRESH = NOW - 60 // …while `#{session_activity}` stays fresh, as it always is in productionconst killed: string[] = []let listings = 0const reaper = createSessionReaper({@@ -485,7 +489,7 @@ describe('control-mode shadow clients for released sessions', () => {// must never name it. nt-node-2 is shadow-only when the plan is made and gains a real// client before the kill — precisely what the kill-time re-verify exists for.const nodeTwo = listings++ === 0 ? 1 : 2- return `nt-node-1|2|${OLD}\nnt-node-2|${nodeTwo}|${OLD}`+ return `nt-node-1|2|${FRESH}|${OLD}\nnt-node-2|${nodeTwo}|${FRESH}|${OLD}`},readMem: () => ({ availableMb: 100, totalMb: 8000 }), // under the watermark: real pressureenv: {},diff --git a/src/core/session-budget.test.ts b/src/core/session-budget.test.tsindex 9b2aab719..5b7f8c370 100644--- a/src/core/session-budget.test.ts+++ b/src/core/session-budget.test.ts@@ -6,6 +6,7 @@ import {parseSessionList,sessionBudgetConfig,createSessionReaper,+ hostUnderMemoryPressure,readMemInfo,type SessionInfo,type SessionBudgetConfig@@ -19,14 +20,31 @@ const cfg = (over: Partial<SessionBudgetConfig> = {}): SessionBudgetConfig => ({maxDetached: 48,graceSec: 6 * 3600,batchMax: 8,+ swapFreeRatio: 0.2,+ swapAvailRatio: 0.25,+ psiFullAvg60: 10,...over})-/** An nt- session idle for `idleH` hours, with `clients` attached (0 = detached). */+/**+ * An nt- session whose PANE has been silent for `idleH` hours, with `clients` attached.+ *+ * **`activitySec` is deliberately always FRESH (60 s old), no matter how long the session has been+ * silent** — that is the shape every session on a live host has, because tmux bumps+ * `#{session_activity}` on every client attach and nodeterm attaches constantly (measured: across+ * 67 production sessions the OLDEST `session_activity` was 33 minutes, while the oldest+ * `#{window_activity}` was 37 hours).+ *+ * Encoding it in the shared helper makes the whole suite a regression test for the clock: if this+ * module ever goes back to gating on `activitySec`, nothing is ever past grace and every eligibility+ * assertion below turns red at once. A helper that set both stamps to the same value would let that+ * revert pass — the two clocks have to disagree here, because they disagree in production.+ */const idle = (name: string, idleH: number, clients = 0): SessionInfo => ({name,clients,- activitySec: NOW - idleH * 3600+ activitySec: NOW - 60,+ outputSec: NOW - idleH * 3600})const lowMem = { availableMb: 500, totalMb: 64_000 }@@ -114,24 +132,212 @@ describe('planReap (pure policy)', () => {})})+describe('the two clocks (the measurement this whole change rests on)', () => {+ // 2026-08-15, production host: `nt-term-msrblsui-9` had NO pane output for 18.1 hours while+ // `session_activity` read 15 minutes, because nodeterm had just re-attached a client to it.+ const realHostSession: SessionInfo = {+ name: 'nt-term-msrblsui-9',+ clients: 0,+ activitySec: NOW - 15 * 60, // what tmux says: 15 minutes+ outputSec: NOW - 18 * 3600 // what the pane says: 18 hours of silence+ }++ it('reaps a session tmux calls fresh when its pane has been silent past grace', () => {+ expect(planReap([realHostSession], lowMem, NOW, cfg())).toEqual(['nt-term-msrblsui-9'])+ })++ it('SPARES a session tmux calls stale when its pane is actually producing output', () => {+ // The mirror image, and the reason this is not merely "use the older number": a session whose+ // client detached hours ago but whose agent is still printing must survive. Gating on+ // `activitySec` would kill it.+ const working: SessionInfo = {+ name: 'nt-busy',+ clients: 0,+ activitySec: NOW - 40 * 3600, // no client has attached in nearly two days+ outputSec: NOW - 30 // …but the pane wrote something 30 seconds ago+ }+ expect(planReap([working], lowMem, NOW, cfg())).toEqual([])+ })++ it('orders by silence, not by attach time', () => {+ const a: SessionInfo = { name: 'nt-a', clients: 0, activitySec: NOW - 3600, outputSec: NOW - 10 * 3600 }+ const b: SessionInfo = { name: 'nt-b', clients: 0, activitySec: NOW - 90000, outputSec: NOW - 40 * 3600 }+ // `b` is the least-recently-ACTIVE by output and must die first, even though `a` looks older+ // on the attach clock's ordering.+ expect(planReap([a, b], lowMem, NOW, cfg({ batchMax: 1 }))).toEqual(['nt-b'])+ })+})+describe('parseSessionList', () => {- it('parses names, CLIENT COUNTS and activity, skipping malformed lines', () => {- const out = parseSessionList('nt-a|0|1753000000\nnt-b|2|1753000100\n\njunk\nx|y|z\n')+ it('parses names, CLIENT COUNTS, activity and OUTPUT time, skipping malformed lines', () => {+ const out = parseSessionList(+ 'nt-a|0|1753000000|1752900000\nnt-b|2|1753000100|1753000100\n\njunk\nx|y|z|w\nnt-c|0|1753000000\n'+ )expect(out).toEqual([- { name: 'nt-a', clients: 0, activitySec: 1_753_000_000 },- { name: 'nt-b', clients: 2, activitySec: 1_753_000_100 }+ { name: 'nt-a', clients: 0, activitySec: 1_753_000_000, outputSec: 1_752_900_000 },+ { name: 'nt-b', clients: 2, activitySec: 1_753_000_100, outputSec: 1_753_000_100 }])+ // `nt-c` carried the OLD three-field shape. It is dropped rather than defaulted, so a format+ // that ever regresses produces no candidates instead of candidates with a fabricated clock.+ expect(out.map((s) => s.name)).not.toContain('nt-c')+ })++ it('rejects a row with MORE than four fields rather than parsing the first four', () => {+ // The length check is pinned EXACTLY, as the original parser pinned its own. A row carrying an+ // unexpected fifth field is a row in a format we do not understand, and the safe answer is to+ // contribute no candidate rather than to trust four columns that happen to look plausible.+ //+ // Note the shape of this row: its first four fields are all individually VALID, so the numeric+ // guards below cannot reject it. Only the exact-length check can — which is what makes this an+ // assertion about that check rather than about the guards. (A row like `nt-a|b|0|1|2` proves+ // nothing here: `Number('b')` is NaN and the client-count guard rejects it either way.)+ expect(parseSessionList('nt-a|0|1753000000|1752900000|extra')).toEqual([])+ expect(parseSessionList(`nt-ok|0|${NOW - 60}|${NOW - 40 * 3600}`)).toHaveLength(1)+ })++ it('reduces a multi-window session to ONE row holding its most recent output', () => {+ // Verified against tmux: `list-windows -a` emits one line per window, and a two-window session+ // carries two distinct `#{window_activity}` stamps. A session is silent only when ALL of its+ // windows are, so the newest wins — and it must win regardless of which order they arrive in.+ const newestLast = parseSessionList('nt-a|0|1753000000|1752900000\nnt-a|0|1753000000|1752999000')+ const newestFirst = parseSessionList('nt-a|0|1753000000|1752999000\nnt-a|0|1753000000|1752900000')+ expect(newestLast).toEqual([{ name: 'nt-a', clients: 0, activitySec: 1_753_000_000, outputSec: 1_752_999_000 }])+ expect(newestFirst).toEqual(newestLast)+ })++ it('a session with a busy second window is NOT reaped for its quiet first one', () => {+ // The behavioural consequence of the reduce, asserted through planReap rather than the parser:+ // window 0 has been silent for 40 h, window 1 wrote a second ago.+ const sessions = parseSessionList(+ `nt-two|0|${NOW - 60}|${NOW - 40 * 3600}\nnt-two|0|${NOW - 60}|${NOW - 1}`+ )+ expect(planReap(sessions, lowMem, NOW, cfg())).toEqual([])+ })+})++describe('hostUnderMemoryPressure', () => {+ const c = cfg({ minAvailableMb: 6416 }) // 10% of a 64 GB host++ // The live production reading, 2026-08-15: 12.6 GB available of 62.7 GB (well above the+ // watermark), swap 73.9% consumed, PSI quiet. Nothing is wrong right now, so nothing may fire —+ // this is the guard against a fix that simply reaps more.+ const healthyToday = { availableMb: 13_481, totalMb: 64_158, swapTotalMb: 8192, swapFreeMb: 2140, psiFullAvg60: 0 }++ // The reading this task was opened on: 10.5 GB available (16.7%), swap 84% consumed.+ const swapSpent = { availableMb: 10_752, totalMb: 64_158, swapTotalMb: 8192, swapFreeMb: 1331, psiFullAvg60: 0 }++ it('a failed read is never pressure', () => {+ expect(hostUnderMemoryPressure(null, c)).toBe(false)+ })++ it('the available-memory watermark still fires on its own', () => {+ expect(hostUnderMemoryPressure({ availableMb: 500, totalMb: 64_158 }, c)).toBe(true)+ })++ it("today's host — above the watermark, swap 74% spent, PSI quiet — is NOT pressure", () => {+ expect(hostUnderMemoryPressure(healthyToday, c)).toBe(false)+ })++ it('swap 84% spent WITH low available memory IS pressure (the state the old reader called healthy)', () => {+ expect(hostUnderMemoryPressure(swapSpent, c)).toBe(true)+ // …and the old instrument, which is exactly `availableMb` against the watermark, says no.+ expect(swapSpent.availableMb < c.minAvailableMb).toBe(false)+ })++ it('either half of the swap term alone is benign', () => {+ // Swap spent, but memory is plentiful: cold pages parked in swap on a healthy host.+ expect(hostUnderMemoryPressure({ ...swapSpent, availableMb: 40_000 }, c)).toBe(false)+ // Memory lowish, but swap untouched: the reserve is still there.+ expect(hostUnderMemoryPressure({ ...swapSpent, swapFreeMb: 8000 }, c)).toBe(false)+ })++ it('a host with NO swap configured never trips the swap term (0/0 is not exhaustion)', () => {+ expect(hostUnderMemoryPressure({ ...swapSpent, swapTotalMb: 0, swapFreeMb: 0 }, c)).toBe(false)+ })++ it('absent swap fields are no signal, not zero', () => {+ const { swapTotalMb: _t, swapFreeMb: _f, ...noSwap } = swapSpent+ expect(hostUnderMemoryPressure(noSwap, c)).toBe(false)+ })++ it('HALF a swap reading is no signal either, in both directions', () => {+ // `MemInfo` is a shared type and its swap pair is optional, so a caller that is not+ // `parseMemInfoText` (the SSH leg, a future reader) can hand over one half. Neither half alone+ // may be completed with a default: filling the missing TOTAL invents a denominator, and filling+ // the missing FREE with 0 states that swap is exhausted. Both would make this term fire on a+ // host nobody measured. Pinned explicitly because the arithmetic happens to yield NaN today —+ // a guard that only works by accident of NaN is not a guard.+ const { swapFreeMb: _f, ...totalOnly } = swapSpent+ const { swapTotalMb: _t, ...freeOnly } = swapSpent+ expect(hostUnderMemoryPressure(totalOnly, c)).toBe(false)+ expect(hostUnderMemoryPressure(freeOnly, c)).toBe(false)+ })++ it('PSI full avg60 past the bar is pressure on its own; absent PSI is not', () => {+ expect(hostUnderMemoryPressure({ availableMb: 40_000, totalMb: 64_158, psiFullAvg60: 25 }, c)).toBe(true)+ expect(hostUnderMemoryPressure({ availableMb: 40_000, totalMb: 64_158, psiFullAvg60: 0 }, c)).toBe(false)+ expect(hostUnderMemoryPressure({ availableMb: 40_000, totalMb: 64_158 }, c)).toBe(false)+ })++ it('a darwin-shaped reading (no swap, no PSI fields) can only ever use the watermark', () => {+ // parseVmStat populates neither, so macOS cannot start firing on a signal never measured there.+ const darwinish = { availableMb: 3000, totalMb: 24_576 }+ expect(hostUnderMemoryPressure(darwinish, cfg({ minAvailableMb: 2458 }))).toBe(false)+ expect(hostUnderMemoryPressure({ ...darwinish, availableMb: 100 }, cfg({ minAvailableMb: 2458 }))).toBe(true)+ })++ it('the new terms can be switched off, and off means off', () => {+ expect(hostUnderMemoryPressure(swapSpent, cfg({ minAvailableMb: 6416, swapFreeRatio: 0 }))).toBe(false)+ const psiOnly = { availableMb: 40_000, totalMb: 64_158, psiFullAvg60: 25 }+ expect(hostUnderMemoryPressure(psiOnly, cfg({ minAvailableMb: 6416, psiFullAvg60: 0 }))).toBe(false)+ })++ it('drives planReap: the same sessions live or die on the swap reading alone', () => {+ const sessions = [idle('nt-silent', 40)]+ expect(planReap(sessions, healthyToday, NOW, cfg({ minAvailableMb: 6416 }))).toEqual([])+ expect(planReap(sessions, swapSpent, NOW, cfg({ minAvailableMb: 6416 }))).toEqual(['nt-silent'])})})describe('sessionBudgetConfig', () => {- it('defaults: 10% of RAM watermark (floor 1GB), cap 48, grace 6h, batch 8', () => {- const c = sessionBudgetConfig({}, 64_000)- expect(c).toEqual({ disabled: false, minAvailableMb: 6400, maxDetached: 48, graceSec: 21_600, batchMax: 8 })- expect(sessionBudgetConfig({}, 4000).minAvailableMb).toBe(1024)+ const memOf = (totalMb: number) => ({ availableMb: Math.round(totalMb / 2), totalMb })++ it('defaults: 10% of RAM watermark (floor 1GB), grace 6h, batch 8', () => {+ const c = sessionBudgetConfig({}, memOf(64_000), 0)+ expect(c).toEqual({+ disabled: false,+ minAvailableMb: 6400,+ maxDetached: 33,+ graceSec: 21_600,+ batchMax: 8,+ swapFreeRatio: 0.2,+ swapAvailRatio: 0.25,+ psiFullAvg60: 10+ })+ expect(sessionBudgetConfig({}, memOf(4000), 0).minAvailableMb).toBe(1024)})- it('env overrides win; junk values fall back', () => {+ it('the detached cap SCALES WITH THE HOST instead of being the constant 48', () => {+ // A share of host RAM over a nominal session cost, clamped to [8, 48]. The point is that a+ // 16 GB laptop and a 62 GB server stop getting the same number: 48 detached agent sessions is+ // ~23 GB of nominal RSS, i.e. more than a 16 GB machine physically has.+ expect(sessionBudgetConfig({}, memOf(64_158), 0).maxDetached).toBe(33) // the production host+ expect(sessionBudgetConfig({}, memOf(16_384), 0).maxDetached).toBe(8)+ expect(sessionBudgetConfig({}, memOf(8192), 0).maxDetached).toBe(8) // floor holds a small host usable+ // The ceiling is the historical constant, so this can only ever LOWER a cap, never raise one.+ expect(sessionBudgetConfig({}, memOf(1_000_000), 0).maxDetached).toBe(48)+ })++ it('NO host reading (darwin) keeps the historical 48 rather than deriving from os.totalmem()', () => {+ // Deriving here would silently change reaping on macOS — a cap of 12 on a 24 GB Mac — off a+ // host figure whose meaning there this module has been burned by twice. The fallback total is+ // still used for the watermark, which is the number that HAS a defined meaning.+ const c = sessionBudgetConfig({}, null, 24_576)+ expect(c.maxDetached).toBe(48)+ expect(c.minAvailableMb).toBe(2458)+ })++ it('env overrides win; junk values fall back to the DERIVED cap, not to 48', () => {const c = sessionBudgetConfig({NODETERM_SESSION_MIN_AVAILABLE_MB: '3000',@@ -139,12 +345,24 @@ describe('sessionBudgetConfig', () => {NODETERM_SESSION_GRACE_HOURS: '12',NODETERM_SESSION_REAP_DISABLED: '1'},- 64_000+ memOf(64_000),+ 0)expect(c.minAvailableMb).toBe(3000)- expect(c.maxDetached).toBe(48)+ expect(c.maxDetached).toBe(33)expect(c.graceSec).toBe(43_200)expect(c.disabled).toBe(true)+ expect(sessionBudgetConfig({ NODETERM_SESSION_MAX_DETACHED: '5' }, memOf(64_000), 0).maxDetached).toBe(5)+ })++ it('the swap and PSI terms are tunable, and junk falls back', () => {+ const c = (env: Record<string, string>) => sessionBudgetConfig(env, memOf(64_000), 0)+ expect(c({ NODETERM_SESSION_SWAP_FREE_PCT: '35' }).swapFreeRatio) .toBeCloseTo(0.35)+ expect(c({ NODETERM_SESSION_PSI_FULL_AVG60: '40' }).psiFullAvg60).toBe(40)+ for (const v of ['abc', '', '0', '-3']) {+ expect(c({ NODETERM_SESSION_SWAP_FREE_PCT: v }).swapFreeRatio).toBeCloseTo(0.2)+ expect(c({ NODETERM_SESSION_PSI_FULL_AVG60: v }).psiFullAvg60).toBe(10)+ }})})@@ -162,7 +380,7 @@ function fakeWorld(listings: Record<string, string[]>): {exec: async (_bin, args) => {calls.push({ args })const socket = args[1]- if (args[2] === 'list-sessions') {+ if (args[2] === 'list-windows') {const lines = listings[socket]if (!lines) throw new Error('no server running')return lines.join('\n')@@ -174,6 +392,14 @@ function fakeWorld(listings: Record<string, string[]>): {const OLD = String(NOW - 100 * 3600)+/**+ * One `list-windows -a` row. `session_activity` is pinned FRESH (60 s) for the same reason the+ * `idle` helper pins it: that is the only shape a live host ever presents, so the service tests+ * exercise the honest clock rather than a stamp that would never be stale in production.+ */+const row = (name: string, clients: number, silentSince: number | string): string =>+ `${name}|${clients}|${NOW - 60}|${silentSince}`+describe('createSessionReaper (service)', () => {const base = {readMem: () => ({ availableMb: 100, totalMb: 64_000 }),@@ -184,8 +410,8 @@ describe('createSessionReaper (service)', () => {it('sweeps every socket, kills planned sessions on the right socket with exact-match targets', async () => {const w = fakeWorld({- 'node-terminal': [`nt-local|0|${OLD}`],- 'nodeterm-rmt': [`nt-remote|0|${OLD}`]+ 'node-terminal': [row('nt-local', 0, OLD)],+ 'nodeterm-rmt': [row('nt-remote', 0, OLD)]})const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', exec: w.exec })expect(await reaper.sweep()).toBe(2)@@ -200,12 +426,12 @@ describe('createSessionReaper (service)', () => {let first = trueconst w = fakeWorld({})const exec = async (bin: string, args: string[]): Promise<string> => {- if (args[2] === 'list-sessions' && args[1] === 'node-terminal') {+ if (args[2] === 'list-windows' && args[1] === 'node-terminal') {if (first) {first = false- return `nt-x|0|${OLD}`+ return row('nt-x', 0, OLD)}- return `nt-x|1|${OLD}` // now attached+ return row('nt-x', 1, OLD) // now attached}return w.exec(bin, args)}@@ -215,7 +441,7 @@ describe('createSessionReaper (service)', () => {})it('a socket whose listing fails contributes no candidates; the other socket still sweeps', async () => {- const w = fakeWorld({ 'nodeterm-rmt': [`nt-r|0|${OLD}`] }) // node-terminal listing throws+ const w = fakeWorld({ 'nodeterm-rmt': [row('nt-r', 0, OLD)] }) // node-terminal listing throwsconst reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', exec: w.exec })expect(await reaper.sweep()).toBe(1)const kills = w.calls.filter((c) => c.args[2] === 'kill-session')@@ -223,7 +449,7 @@ describe('createSessionReaper (service)', () => {})it('kill switch: disabled env runs no tmux commands at all', async () => {- const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })+ const w = fakeWorld({ 'node-terminal': [row('nt-x', 0, OLD)] })const reaper = createSessionReaper({...base,env: { NODETERM_SESSION_REAP_DISABLED: '1' },@@ -235,14 +461,14 @@ describe('createSessionReaper (service)', () => {})it('tmux unavailable (bin=null) → quiet no-op', async () => {- const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })+ const w = fakeWorld({ 'node-terminal': [row('nt-x', 0, OLD)] })const reaper = createSessionReaper({ ...base, tmuxBin: () => null, exec: w.exec })expect(await reaper.sweep()).toBe(0)expect(w.calls).toHaveLength(0)})it('a failing kill is tolerated and does not abort the rest of the batch', async () => {- const w = fakeWorld({ 'node-terminal': [`nt-a|0|${OLD}`, `nt-b|0|${String(NOW - 99 * 3600)}`] })+ const w = fakeWorld({ 'node-terminal': [row('nt-a', 0, OLD), row('nt-b', 0, NOW - 99 * 3600)] })const exec = async (bin: string, args: string[]): Promise<string> => {if (args[2] === 'kill-session' && args[4] === '=nt-a') throw new Error('gone already')return w.exec(bin, args)@@ -252,7 +478,7 @@ describe('createSessionReaper (service)', () => {})it('healthy memory + under cap → lists but never kills', async () => {- const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })+ const w = fakeWorld({ 'node-terminal': [row('nt-x', 0, OLD)] })const reaper = createSessionReaper({...base,readMem: () => ({ availableMb: 30_000, totalMb: 64_000 }),@@ -264,7 +490,7 @@ describe('createSessionReaper (service)', () => {})it('…but the same host sweeps under an explicit external pressure reason', async () => {- const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })+ const w = fakeWorld({ 'node-terminal': [row('nt-x', 0, OLD)] })const reaper = createSessionReaper({...base,readMem: () => ({ availableMb: 30_000, totalMb: 64_000 }),@@ -277,7 +503,7 @@ describe('createSessionReaper (service)', () => {it('an external reason never overrides the attached/grace exemptions', async () => {const w = fakeWorld({- 'node-terminal': [`nt-watched|1|${OLD}`, `nt-fresh|0|${NOW - 60}`]+ 'node-terminal': [row('nt-watched', 1, OLD), row('nt-fresh', 0, NOW - 60)]})const reaper = createSessionReaper({...base,@@ -295,7 +521,8 @@ describe('planReap with no memory signal (the darwin shape)', () => {const idle = (name: string, hoursAgo: number): SessionInfo => ({name,clients: 0,- activitySec: 1_000_000 - hoursAgo * 3600+ activitySec: 1_000_000 - 60,+ outputSec: 1_000_000 - hoursAgo * 3600})it('culls NOTHING on memory grounds when the reader reports null', () => {@@ -303,16 +530,22 @@ describe('planReap with no memory signal (the darwin shape)', () => {// compressed, macOS's own graph GREEN). hostMemReader returns null there, and null must mean// "no pressure signal", never "no memory". Absence of evidence may not cull a session.const sessions = Array.from({ length: 20 }, (_, i) => idle(`nt-old-${i}`, 48))- const cfg = sessionBudgetConfig({}, 24576)+ const cfg = sessionBudgetConfig({}, null, 24576)expect(planReap(sessions, null, 1_000_000, cfg)).toEqual([])})it('still culls past the detached-count cap without any memory signal', () => {// The cap is not memory-based, so it survives — that is what keeps the reaper useful on macOS.const sessions = Array.from({ length: 60 }, (_, i) => idle(`nt-old-${i}`, 48))- const cfg = sessionBudgetConfig({}, 24576)+ const cfg = sessionBudgetConfig({}, null, 24576)expect(planReap(sessions, null, 1_000_000, cfg).length).toBeGreaterThan(0)})++ it('…and that cap is still the historical 48 there, not a figure derived from os.totalmem()', () => {+ // 60 detached sessions against a cap of 48 is 12 over; a derived cap (24 GB → 12) would make it+ // 48 over and reap a full batch on a Mac that has done nothing wrong.+ expect(sessionBudgetConfig({}, null, 24576).maxDetached).toBe(48)+ })})describe("the reaper's default memory reader", () => {@@ -359,7 +592,7 @@ describe('darwin default reader: no byte reading may ever reap (behavioural)', (// produce bytes at all (hostMemReader's darwin null) keeps these sessions alive. This encodes// "memory fullness must never reap on macOS" without depending on the host's current load.const w = fakeWorld({- 'node-terminal': Array.from({ length: 20 }, (_, i) => `nt-idle-${i}|0|${OLD}`)+ 'node-terminal': Array.from({ length: 20 }, (_, i) => row(`nt-idle-${i}`, 0, OLD))})const reaper = createSessionReaper({tmuxBin: () => 'tmux',@@ -376,7 +609,9 @@ describe('darwin default reader: no byte reading may ever reap (behavioural)', (})describe('sessionBudgetConfig with fractional env values', () => {- const cfg = (env: Record<string, string>) => sessionBudgetConfig(env, 24576)+ // `null` mem, so the cap default is the historical 48 and these assertions keep testing the+ // env-parsing trap they were written for rather than the new derivation.+ const cfg = (env: Record<string, string>) => sessionBudgetConfig(env, null, 24576)it('a fractional MAX_DETACHED falls back — it must never become a cap of ZERO', () => {// Math.floor(0.5) === 0, and a cap of zero is not a smaller cap: every detached session countsdiff --git a/src/core/session-budget.ts b/src/core/session-budget.tsindex b0e41fd59..d29aec923 100644--- a/src/core/session-budget.ts+++ b/src/core/session-budget.ts@@ -5,7 +5,12 @@// This is the tmux counterpart of the renderer's WebGL budget (`terminal/webgl-budget.ts`), and it// deliberately reuses that design's rules rather than inventing an expiry policy:// - a bounded budget, enforced only when exceeded — never a calendar-based expiry;-// - eviction picks the LEAST-RECENTLY-ACTIVE holder;+// - eviction picks the LEAST-RECENTLY-ACTIVE holder — where ACTIVE means the pane last produced+// OUTPUT. tmux's `#{session_activity}` looks like that number and is not: it is bumped by every+// client ATTACH, and nodeterm attaches on every reconnect, so on a live host it never ages past+// a few minutes. Gating on it made this whole module a no-op — measured, and worse than a+// no-op: with a short grace it reaped the session that was printing and spared the abandoned+// one. `SessionInfo.outputSec` (`#{window_activity}`) is the honest clock; see its doc.// - an ATTACHED session (someone is looking at it) is never evicted, exactly like a visible// WebGL holder; a recently-active one is protected by a grace window (the release delay).// "Attached" means a WATCHER: this app's own control-mode shadows are tmux clients too, and@@ -36,7 +41,7 @@ const runAsync = promisify(execFile)// second reader would let them disagree about how much RAM is free.export { readMemInfo, type MemInfo } from './session-memory'-/** One tmux session as reported by `list-sessions`. `activitySec` is epoch seconds. */+/** One tmux session, reduced from `list-windows -a`. All stamps are epoch seconds. */export interface SessionInfo {name: string/**@@ -51,7 +56,35 @@ export interface SessionInfo {* whoever the other client belongs to.*/clients: number+ /**+ * `#{session_activity}`. **Kept for the log line and NOTHING else — it is not an idleness+ * signal, and this module must never gate a kill on it again.**+ *+ * MEASURED on this host, 2026-08-15, on a private throwaway socket (a real socket was never+ * swept): tmux bumps `session_activity` to `now` every time a CLIENT ATTACHES, with no pane+ * output involved. A control-mode `-C attach-session` moved it 1786793595 → 1786793620; a pty+ * attach moved it again to 1786793787; `#{window_activity}` did not move for either. Pure reads —+ * `capture-pane`, `list-panes`, `list-sessions`, `display-message`, `has-session` — moved+ * neither, and neither did `resize-window`.+ *+ * nodeterm attaches constantly: every painter is a `tmux new-session -A -s nt-<node>`, which+ * ATTACHES when the session already exists, and a desktop reconnecting over SSH does it to every+ * session at once (measured: one sshd holding 49 pts clients, all `client_created` identical).+ * So on a live host this stamp measures WHEN NODETERM LAST LOOKED, not when the agent last did+ * anything. Across 67 nt- sessions the oldest `session_activity` was 33 MINUTES while the oldest+ * `window_activity` was 37 HOURS, and one session read 469 s on this clock against 133 513 s on+ * the honest one.+ */activitySec: number+ /**+ * **The idleness signal: when a pane in this session last actually produced output.**+ *+ * The max `#{window_activity}` across the session's windows (a session can have several, and the+ * most recently active one is what "this session is idle" has to mean). Unlike `activitySec`,+ * nothing nodeterm does to LOOK at a session moves it — verified against attach, detach, resize+ * and every read above — so it answers the question the grace window is actually asking.+ */+ outputSec: number}export interface SessionBudgetConfig {@@ -61,7 +94,17 @@ export interface SessionBudgetConfig {minAvailableMb: number/** Backstop: max detached nt- sessions across sockets; excess is reaped even without pressure. */maxDetached: number- /** A session with activity newer than this is never reaped (protects same-day project switches). */+ /**+ * Swap term: pressure when the free fraction of swap falls to or below this AND available memory+ * is at or below `swapAvailRatio` of total. `0` disables the term.+ */+ swapFreeRatio: number+ /** The available-memory half of the swap term (see `hostUnderMemoryPressure`). */+ swapAvailRatio: number+ /** PSI term: pressure when `/proc/pressure/memory` `full avg60` reaches this. `0` disables it. */+ psiFullAvg60: number+ /** A session whose pane produced OUTPUT more recently than this is never reaped (protects+ * same-day project switches). Measured against `SessionInfo.outputSec`, never `activitySec`. */graceSec: number/** Max kills per sweep — convergence is gradual and re-evaluated each sweep. */batchMax: number@@ -95,28 +138,161 @@ function envHours(env: NodeJS.ProcessEnv, key: string, fallbackHours: number): nreturn Math.round((Number.isFinite(n) && n > 0 ? n : fallbackHours) * 3600)}+/**+ * A NOMINAL agent session's cost, in MB of process-tree RSS. Not a limit and not a prediction of+ * any one session — purely the divisor that turns "a share of this host's RAM" into "a number of+ * sessions". MEASURED on the 62.7 GB production host, 2026-08-15: 67 live `nt-` sessions on root's+ * `nodeterm-rmt` socket held 32 877 MB of tree RSS, a mean of 491 MB (the module header's older+ * field note — ~335 MB for the CLI plus 30-200 MB of MCP children — brackets the same figure).+ */+export const NOMINAL_SESSION_MB = 491++/**+ * The share of HOST memory one instance may hold in detached sessions before its count backstop+ * starts trimming. See `sessionBudgetConfig` for why this is a per-instance share of a host number+ * and not a host-wide count.+ */+export const HOST_SHARE = 0.25++/** Floor and ceiling for the derived cap. The ceiling is the historical constant, so this change+ * can only ever LOWER a cap, never raise one; the floor keeps a small host usable. */+export const MAX_DETACHED_FLOOR = 8+export const MAX_DETACHED_CEILING = 48+/*** Defaults, overridable per host via env (systemd `Environment=` lines):* NODETERM_SESSION_MIN_AVAILABLE_MB (default: 10% of total RAM, floor 1 GB)- * NODETERM_SESSION_MAX_DETACHED (default: 48)+ * NODETERM_SESSION_MAX_DETACHED (default: derived from host RAM, see below; 48 with no reading)* NODETERM_SESSION_GRACE_HOURS (default: 6)* NODETERM_SESSION_REAP_BATCH (default: 8)+ * NODETERM_SESSION_SWAP_FREE_PCT (default: 20 — the swap term; 0 disables)+ * NODETERM_SESSION_PSI_FULL_AVG60 (default: 10 — the PSI term; 0 disables)* NODETERM_SESSION_REAP_DISABLED=1 (kill switch)+ *+ * ── WHY THE DETACHED CAP IS A HOST-SCALED PER-INSTANCE NUMBER, NOT A HOST-WIDE COUNT ────────────+ *+ * The cap used to be the constant 48, and on a shared host that is a cap on nothing: each nodeterm+ * instance runs as its own uid and sees only its own tmux socket, so seven instances each sat one+ * session under their own 48 while the machine drowned. The obvious fix — count the host's sessions+ * instead of ours — was MEASURED and is not available:+ *+ * - the per-uid socket dirs are 0700 (`/tmp/tmux-1002` is `drwx------ projects`), and a second+ * uid attempting to list one gets `Permission denied`;+ * - `/proc` is mounted `hidepid=invisible`, so a non-root uid cannot even SEE another user's+ * processes — user `projects` counted 62 processes host-wide and 62 of its own.+ *+ * So no instance can enumerate, or even detect, another instance's sessions. A truly host-wide+ * COUNT is unreachable without a shared broker, and inventing one is a much larger change than+ * this. What every uid CAN read — verified as an unprivileged user on the same host — is+ * `/proc/meminfo` and `/proc/pressure/memory`. **The host-wide facts are the MEMORY facts, so the+ * host-aware trigger is the memory one (`hostUnderMemoryPressure`), and that is the load-bearing+ * half of this change.** Every instance sees the same pressure at the same moment and each trims+ * its own sessions, which converges without any of them seeing the others.+ *+ * The count cap is then demoted to what it honestly is: a per-instance sanity backstop. It still+ * stops being a constant, because a constant is wrong in the other direction too — 48 detached+ * agent sessions is ~23 GB of nominal RSS, which is most of a 32 GB laptop and all of a 16 GB one.+ * Derived instead as `HOST_SHARE` of host RAM divided by `NOMINAL_SESSION_MB`, clamped to+ * [8, 48]. On the 62.7 GB host that is 32 (down from 48); on a 24 GB Mac it would be 12, which is+ * exactly why it is NOT derived when there is no host reading — see the `mem === null` case below.+ *+ * Seven instances at 25% each over-subscribe the machine, and that is deliberate rather than+ * overlooked: an instance cannot know how many peers it has, and a share small enough to be safe+ * with seven would cripple the single-user desktop that is the common case. Over-subscription is+ * safe here precisely BECAUSE the memory term is host-wide — the backstop may be loose, because it+ * is not the thing standing between this host and a swap-thrash lockup.+ *+ * `mem === null` (darwin, or an unreadable /proc) keeps the historical 48. The count cap needs no+ * memory reading to work, so deriving it from `os.totalmem()` would quietly change reaping+ * behaviour on macOS — a cap of 12 on a 24 GB Mac — off a host figure whose meaning there this+ * module has already been burned by twice (see `hostMemReader`). A platform gets a new default+ * when it has been measured, not when a number happens to be available.*/-export function sessionBudgetConfig(env: NodeJS.ProcessEnv, totalMb: number): SessionBudgetConfig {+export function sessionBudgetConfig(+ env: NodeJS.ProcessEnv,+ mem: MemInfo | null,+ fallbackTotalMb: number+): SessionBudgetConfig {+ const totalMb = mem?.totalMb ?? fallbackTotalMb+ const derivedCap =+ mem === null+ ? MAX_DETACHED_CEILING+ : Math.min(+ MAX_DETACHED_CEILING,+ Math.max(MAX_DETACHED_FLOOR, Math.round((totalMb * HOST_SHARE) / NOMINAL_SESSION_MB))+ )return {disabled: env.NODETERM_SESSION_REAP_DISABLED === '1' || env.NODETERM_SESSION_REAP_DISABLED === 'true',minAvailableMb: envInt(env, 'NODETERM_SESSION_MIN_AVAILABLE_MB', Math.max(1024, Math.round(totalMb * 0.1))),- maxDetached: envInt(env, 'NODETERM_SESSION_MAX_DETACHED', 48),+ maxDetached: envInt(env, 'NODETERM_SESSION_MAX_DETACHED', derivedCap),graceSec: envHours(env, 'NODETERM_SESSION_GRACE_HOURS', 6),- batchMax: envInt(env, 'NODETERM_SESSION_REAP_BATCH', 8)+ batchMax: envInt(env, 'NODETERM_SESSION_REAP_BATCH', 8),+ // Percentages, so `envInt`'s `>= 1` floor is not the trap it is for a cap: 0 and junk both fall+ // back to the default, and an operator who wants the term OFF sets the ratio via a value the+ // clamp below turns into 0 — `NODETERM_SESSION_SWAP_FREE_PCT=100` can never be satisfied.+ swapFreeRatio: envInt(env, 'NODETERM_SESSION_SWAP_FREE_PCT', 20) / 100,+ swapAvailRatio: 0.25,+ psiFullAvg60: envInt(env, 'NODETERM_SESSION_PSI_FULL_AVG60', 10)+ }+}++/**+ * Is the HOST under memory pressure? Three OR'd terms, each of which independently means "there is+ * no headroom left". A term whose inputs are absent contributes NOTHING — absence of evidence is+ * never pressure, which is this module's standing rule and the reason darwin stays quiet.+ *+ * 1. **Available memory below the watermark.** The original term, unchanged.+ *+ * 2. **Swap spent AND available memory low.** `MemAvailable` alone is blind to a host that has+ * already burned its overflow reserve. MEASURED on the production host: 10.5 GB available+ * (16.7%) with 84% of swap consumed — comfortably above a 10%-of-RAM watermark, and the same+ * shape as the 2026-08-03 swap-thrash lockup. BOTH halves are required because either alone is+ * benign: a host can fill swap with cold pages and be perfectly healthy, and a host can run at+ * 20% available with swap untouched and be perfectly healthy. Together they mean the primary+ * pool is low and the reserve behind it is gone.+ *+ * 3. **PSI `full avg60`.** The kernel's own answer to "is this machine thrashing", and the only+ * term that measures a CONSEQUENCE rather than a level. `full` (every task stalled) rather than+ * `some` (at least one), because `some` is routinely non-zero on a busy, healthy host.+ *+ * Fail-open direction, stated per input: a missing `mem` is not pressure; a missing swap pair is+ * not pressure; a missing or unparsed PSI figure is not pressure; `swapTotalMb === 0` (no swap+ * configured) is not pressure. Every one of those makes the reaper do LESS, which is the safe+ * direction here — a reaper that kills a session someone is using is far worse than one that+ * misses a candidate.+ */+export function hostUnderMemoryPressure(mem: MemInfo | null, cfg: SessionBudgetConfig): boolean {+ if (mem === null) return false+ if (mem.availableMb < cfg.minAvailableMb) return true++ const { swapTotalMb, swapFreeMb, psiFullAvg60 } = mem+ if (+ cfg.swapFreeRatio > 0 &&+ swapTotalMb !== undefined &&+ swapFreeMb !== undefined &&+ swapTotalMb > 0 &&+ swapFreeMb / swapTotalMb <= cfg.swapFreeRatio &&+ mem.totalMb > 0 &&+ mem.availableMb / mem.totalMb <= cfg.swapAvailRatio+ ) {+ return true+ }++ if (cfg.psiFullAvg60 > 0 && psiFullAvg60 !== undefined && psiFullAvg60 >= cfg.psiFullAvg60) {+ return true}+ return false}/**- * Pure policy: which sessions to kill this sweep, least-recently-active first.+ * Pure policy: which sessions to kill this sweep, least-recently-ACTIVE first — where "active"+ * means the session's pane last PRODUCED OUTPUT (`outputSec`), not the moment nodeterm last+ * attached a client to it (`activitySec`). See `SessionInfo.activitySec` for the measurement that+ * forced the distinction; the short version is that on a live host the old clock never reads older+ * than about half an hour, so no grace window could ever elapse and this function returned an+ * empty plan on a host that was 84% into its swap.*- * Eligible = named `nt-*` AND detached AND idle past the grace window. Then:+ * Eligible = named `nt-*` AND detached AND silent past the grace window. Then:* - memory below the watermark → up to `batchMax` (a failed memory read — `mem === null` — is* NOT pressure: absence of evidence never triggers the primary path);* - `externalPressure` → the same allowance, for a resource this module cannot measure (today:@@ -142,29 +318,60 @@ export function planReap(const nt = sessions.filter((s) => s.name.startsWith('nt-'))const detached = nt.filter((s) => s.clients === 0)const eligible = detached- .filter((s) => nowSec - s.activitySec >= cfg.graceSec)- .sort((a, b) => a.activitySec - b.activitySec)+ .filter((s) => nowSec - s.outputSec >= cfg.graceSec)+ .sort((a, b) => a.outputSec - b.outputSec)- const lowMem = mem !== null && mem.availableMb < cfg.minAvailableMb+ const lowMem = hostUnderMemoryPressure(mem, cfg)const pressure = lowMem || externalPressure ? cfg.batchMax : 0const overCap = Math.max(0, detached.length - cfg.maxDetached)const take = Math.min(cfg.batchMax, Math.max(pressure, overCap))return eligible.slice(0, take).map((s) => s.name)}-/** Parse `list-sessions -F '#{session_name}|#{session_attached}|#{session_activity}'` output.- * Tolerant: malformed lines are skipped, never thrown on. */+/**+ * Parse `list-windows -a -F '<LIST_FMT>'` into one row PER SESSION.+ *+ * The listing is per WINDOW because `#{window_activity}` — the only stamp that tracks real pane+ * output — has no session-scope equivalent; `list-sessions` cannot answer the question this module+ * asks. Session-scope fields (`#{session_name}`, `#{session_attached}`, `#{session_activity}`)+ * resolve fine in window scope, verified against tmux on this host, so one listing still carries+ * everything.+ *+ * A session's windows are reduced with `Math.max` on `window_activity`: a session is silent only+ * when ALL of its windows are, and taking the first or the last would call a session with one busy+ * window and one idle one whatever its window ORDER happened to be. Verified against a two-window+ * session whose windows carried distinct stamps.+ *+ * Tolerant in the same direction as before — a malformed line is skipped, never thrown on — and+ * that tolerance is a safety property here: a session whose rows all fail to parse is absent from+ * the result entirely, so it can never become a kill candidate.+ */export function parseSessionList(stdout: string): SessionInfo[] {- const out: SessionInfo[] = []+ const bySession = new Map<string, SessionInfo>()for (const line of stdout.split('\n')) {const parts = line.trim().split('|')- if (parts.length !== 3) continue+ if (parts.length !== 4) continueconst attached = Number(parts[1])const activity = Number(parts[2])- if (!parts[0] || !Number.isFinite(attached) || !Number.isFinite(activity)) continue- out.push({ name: parts[0], clients: Math.max(0, attached), activitySec: activity })+ const output = Number(parts[3])+ if (!parts[0] || !Number.isFinite(attached) || !Number.isFinite(activity) || !Number.isFinite(output)) {+ continue+ }+ const prev = bySession.get(parts[0])+ if (prev) {+ // Most recent output across the session's windows wins; the session-scope fields are+ // identical on every row of the same session, so only this one needs reducing.+ if (output > prev.outputSec) prev.outputSec = output+ continue+ }+ bySession.set(parts[0], {+ name: parts[0],+ clients: Math.max(0, attached),+ activitySec: activity,+ outputSec: output+ })}- return out+ return [...bySession.values()]}/**@@ -277,13 +484,17 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {const env = opts.env ?? process.envconst nowSec = opts.nowSec ?? ((): number => Math.floor(Date.now() / 1000))const log = opts.log ?? ((m: string): void => console.log(m))- const cfg = sessionBudgetConfig(env, readMem()?.totalMb ?? Math.round(os.totalmem() / 1048576))+ // `mem`, not `mem.totalMb`: the detached cap is derived only where there is a real host reading,+ // so the null case (darwin) has to reach sessionBudgetConfig as null rather than as a number.+ const cfg = sessionBudgetConfig(env, readMem(), Math.round(os.totalmem() / 1048576))- const LIST_FMT = '#{session_name}|#{session_attached}|#{session_activity}'+ // `list-windows -a`, not `list-sessions`: `#{window_activity}` is the only stamp that tracks+ // real pane output, and it has no session-scope form. See parseSessionList.+ const LIST_FMT = '#{session_name}|#{session_attached}|#{session_activity}|#{window_activity}'const listSocket = async (bin: string, socket: string): Promise<SessionInfo[] | null> => {try {- const listed = parseSessionList(await exec(bin, ['-L', socket, 'list-sessions', '-F', LIST_FMT]))+ const listed = parseSessionList(await exec(bin, ['-L', socket, 'list-windows', '-a', '-F', LIST_FMT]))// Our own shadows are subtracted from tmux's client COUNT here, at the one place every// listing comes through, so the plan and the kill-time re-verify can never disagree about it// (a shadow attached between the two would otherwise resurrect the exemption). Re-read each@@ -317,8 +528,10 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {if (bySocket.size === 0) return 0const all = [...bySocket.entries()].flatMap(([, list]) => list)- const plan = new Set(planReap(all, readMem(), nowSec(), cfg, sweepOpts?.pressure !== undefined))+ const now = nowSec()+ const plan = new Set(planReap(all, readMem(), now, cfg, sweepOpts?.pressure !== undefined))if (plan.size === 0) return 0+ const silentH = new Map(all.map((s) => [s.name, ((now - s.outputSec) / 3600).toFixed(1)]))let killed = 0for (const [socket, listed] of bySocket) {@@ -334,7 +547,12 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {// `=` forces an exact target match — never tmux's prefix matching.await exec(bin, ['-L', socket, 'kill-session', '-t', `=${name}`])killed++- log(`[session-budget] reaped idle detached session ${name} (socket ${socket})`)+ // The silence is what justified the kill, so it is what the log has to name — an operator+ // reading "idle" against tmux's own `session_activity` would be reading the clock this+ // change exists to stop trusting.+ log(+ `[session-budget] reaped detached session ${name} — no pane output for ${silentH.get(name) ?? '?'}h (socket ${socket})`+ )} catch {// A vanished-in-between session or a kill failure changes nothing; next sweep re-plans.}diff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.tsindex 919a145a8..309462daf 100644--- a/src/core/session-memory.test.ts+++ b/src/core/session-memory.test.ts@@ -420,3 +420,103 @@ describe('collectSessionMemory on darwin', () => {}))})++import { parseMemInfoText, parsePsiMemory, readMemInfo } from './session-memory'++/** A verbatim excerpt of the production host's /proc/meminfo, 2026-08-15 (62.7 GB, swap 74% spent). */+const MEMINFO = `MemTotal: 65697400 kB+MemFree: 4154020 kB+MemAvailable: 13804628 kB+Buffers: 412300 kB+Cached: 9216440 kB+SwapCached: 501232 kB+SwapTotal: 8388604 kB+SwapFree: 2192260 kB+Dirty: 736 kB+`++const PSI = `some avg10=0.00 avg60=1.25 avg300=0.18 total=29288181130+full avg10=0.00 avg60=0.75 avg300=0.15 total=25621111809+`++describe('parseMemInfoText', () => {+ it('reads the required pair and the optional swap pair from ONE snapshot', () => {+ expect(parseMemInfoText(MEMINFO)).toEqual({+ availableMb: 13481,+ totalMb: 64158,+ swapTotalMb: 8192,+ swapFreeMb: 2141+ })+ })++ it('MemAvailable/MemTotal are required — a /proc we do not understand yields NO reading', () => {+ // Not a partial object: a reading missing its primary field would be a number the watermark+ // could still compare against, which is the "wrong number presented as a fact" failure.+ expect(parseMemInfoText(MEMINFO.replace(/MemAvailable:.*\n/, ''))).toBeNull()+ expect(parseMemInfoText(MEMINFO.replace(/MemTotal:.*\n/, ''))).toBeNull()+ expect(parseMemInfoText('garbage')).toBeNull()+ })++ it('swap is OMITTED, not zeroed, when the kernel does not report it', () => {+ // The distinction the swap term depends on: `undefined` means "did not measure" and disables+ // the term, whereas `0` would read as "swap totally exhausted" and could only ever reap MORE.+ const noSwap = parseMemInfoText(MEMINFO.replace(/SwapTotal:.*\n/, '').replace(/SwapFree:.*\n/, ''))+ expect(noSwap).toEqual({ availableMb: 13481, totalMb: 64158 })+ expect(noSwap).not.toHaveProperty('swapTotalMb')+ expect(noSwap).not.toHaveProperty('swapFreeMb')+ })++ it('half a swap reading is no swap reading (a free without a total cannot be a ratio)', () => {+ const half = parseMemInfoText(MEMINFO.replace(/SwapTotal:.*\n/, ''))+ expect(half).not.toHaveProperty('swapFreeMb')+ })++ it('a swapless host reports a real zero TOTAL, which every consumer guard turns off', () => {+ const off = parseMemInfoText(MEMINFO.replace(/SwapTotal:.*/, 'SwapTotal: 0 kB').replace(/SwapFree:.*/, 'SwapFree: 0 kB'))+ expect(off).toMatchObject({ swapTotalMb: 0, swapFreeMb: 0 })+ })+})++describe('parsePsiMemory', () => {+ it('reads avg60 from both lines', () => {+ expect(parsePsiMemory(PSI)).toEqual({ psiSomeAvg60: 1.25, psiFullAvg60: 0.75 })+ })++ it('takes avg60 specifically — not avg10 and not avg300', () => {+ // The cadence argument: the reaper sweeps every 10 minutes, so avg10 is noise and avg300 stays+ // elevated through a recovery. Distinct values in every column make a mix-up visible.+ const distinct = 'some avg10=11.00 avg60=22.00 avg300=33.00 total=1\nfull avg10=44.00 avg60=55.00 avg300=66.00 total=2\n'+ expect(parsePsiMemory(distinct)).toEqual({ psiSomeAvg60: 22, psiFullAvg60: 55 })+ })++ it('does not confuse the some line for the full line', () => {+ expect(parsePsiMemory('some avg10=0.00 avg60=9.00 avg300=0.00 total=1\n')).toEqual({ psiSomeAvg60: 9 })+ })++ it('an unreadable or absent PSI file yields NO figures, never zeros', () => {+ expect(parsePsiMemory('')).toEqual({})+ expect(parsePsiMemory('garbage')).toEqual({})+ expect(parsePsiMemory('some avg10=0.00 avg300=0.18 total=1\n')).toEqual({})+ })+})++describe('readMemInfo on this Linux host (integration)', () => {+ const onLinux = it.skipIf(process.platform !== 'linux')++ onLinux('carries swap alongside the available/total pair', () => {+ const m = readMemInfo()+ expect(m).not.toBeNull()+ expect(m!.totalMb).toBeGreaterThan(0)+ // Swap is not guaranteed configured, but if the kernel reports a total it must report a free.+ if (m!.swapTotalMb !== undefined) {+ expect(m!.swapFreeMb).toBeDefined()+ expect(m!.swapFreeMb!).toBeLessThanOrEqual(m!.swapTotalMb!)+ }+ })++ onLinux('PSI is optional and never breaks the reading', () => {+ const m = readMemInfo()+ expect(m).not.toBeNull()+ if (m!.psiFullAvg60 !== undefined) expect(m!.psiFullAvg60).toBeGreaterThanOrEqual(0)+ })+})diff --git a/src/core/session-memory.ts b/src/core/session-memory.tsindex 83cc68239..a3da96708 100644--- a/src/core/session-memory.ts+++ b/src/core/session-memory.ts@@ -220,15 +220,82 @@ export function parseVmStat(text: string, totalBytes: number): MemInfo | null {return { availableMb, totalMb }}+/**+ * Parse `/proc/meminfo`. `MemAvailable`/`MemTotal` are REQUIRED (without them there is no reading+ * at all); swap is optional and reported only when BOTH halves are present.+ *+ * Swap is read from the meminfo text already in hand rather than from a second file: the watermark+ * and the swap term must describe the same instant, and two reads a syscall apart can disagree+ * about a host that is actively swapping — which is precisely the host this term exists for.+ *+ * `SwapTotal: 0` is a real answer (a host with swap disabled) and is passed through as `0`, where+ * every consumer's `swapTotalMb > 0` guard turns the term off. A MISSING SwapTotal is a different+ * fact — a /proc we do not understand — and yields `undefined`, i.e. no signal.+ */+export function parseMemInfoText(text: string): MemInfo | null {+ const kb = (label: string): number | null => {+ const m = new RegExp(`^${label}:\\s+(\\d+)\\s*kB`, 'm').exec(text)+ return m ? Number(m[1]) : null+ }+ const avail = kb('MemAvailable')+ const total = kb('MemTotal')+ if (avail === null || total === null) return null+ const swapTotal = kb('SwapTotal')+ const swapFree = kb('SwapFree')+ const out: MemInfo = {+ availableMb: Math.round(avail / 1024),+ totalMb: Math.round(total / 1024)+ }+ // Both or neither: a SwapFree without a SwapTotal cannot be turned into a ratio, and half a+ // reading is worse than none — it would be a number a consumer could divide by zero with.+ if (swapTotal !== null && swapFree !== null) {+ out.swapTotalMb = Math.round(swapTotal / 1024)+ out.swapFreeMb = Math.round(swapFree / 1024)+ }+ return out+}++/**+ * Parse `/proc/pressure/memory` into the two `avg60` figures.+ *+ * Shape (Linux >= 4.20, PSI compiled in):+ * some avg10=0.00 avg60=0.00 avg300=0.18 total=29288181130+ * full avg10=0.00 avg60=0.00 avg300=0.15 total=25621111809+ *+ * `avg60` rather than `avg10` on purpose: the reaper sweeps every ten minutes, and a 10-second+ * window is noise at that cadence — a single compile spiking avg10 must not be read as a host in+ * trouble. `avg300` is the other direction: it stays elevated long after the host recovered, and+ * would keep reaping through the recovery.+ *+ * A line we cannot parse yields `undefined` for that figure, not 0 — a zero here means "measured,+ * no stall", which is the opposite of "did not measure".+ */+export function parsePsiMemory(text: string): { psiSomeAvg60?: number; psiFullAvg60?: number } {+ const avg60 = (kind: 'some' | 'full'): number | undefined => {+ const m = new RegExp(`^${kind}\\s[^\\n]*?\\bavg60=(\\d+(?:\\.\\d+)?)`, 'm').exec(text)+ if (!m) return undefined+ const n = Number(m[1])+ return Number.isFinite(n) ? n : undefined+ }+ const some = avg60('some')+ const full = avg60('full')+ return {+ ...(some !== undefined ? { psiSomeAvg60: some } : {}),+ ...(full !== undefined ? { psiFullAvg60: full } : {})+ }+}+export function readMemInfo(): MemInfo | null {try {- const text = fs.readFileSync('/proc/meminfo', 'utf8')- const avail = /MemAvailable:\s+(\d+)\s*kB/.exec(text)- const total = /MemTotal:\s+(\d+)\s*kB/.exec(text)- if (avail && total) {- return {- availableMb: Math.round(Number(avail[1]) / 1024),- totalMb: Math.round(Number(total[1]) / 1024)+ const base = parseMemInfoText(fs.readFileSync('/proc/meminfo', 'utf8'))+ if (base) {+ // PSI is a SEPARATE, OPTIONAL read: it is absent on pre-4.20 kernels, on kernels built+ // without CONFIG_PSI, and inside some containers. Its absence must cost the caller nothing —+ // the memory reading it decorates is already complete and correct without it.+ try {+ return { ...base, ...parsePsiMemory(fs.readFileSync('/proc/pressure/memory', 'utf8')) }+ } catch {+ return base}}} catch {diff --git a/src/shared/types.ts b/src/shared/types.tsindex c1ae09023..5db434d96 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1601,6 +1601,32 @@ export interface ProviderUsage {export interface MemInfo {availableMb: numbertotalMb: number+ /**+ * Swap, and the kernel's own stall accounting. **Optional on purpose, and their absence is the+ * darwin contract.**+ *+ * `availableMb` alone cannot see a host that has already spent its overflow reserve: a machine+ * with 10.5 GB "available" and 84% of its swap consumed reads as healthy under a 10%-of-RAM+ * watermark, which is exactly the state the 2026-08-03 swap-thrash lockup was in. These fields+ * carry the two host-wide facts that DO see it.+ *+ * Only the Linux reader populates them (`/proc/meminfo` for swap, `/proc/pressure/memory` for+ * PSI — both world-readable, measured on a `hidepid=invisible` host where a non-root uid can read+ * neither another user's processes nor their tmux socket). `parseVmStat` leaves every one of them+ * undefined, so no macOS reading can ever satisfy a swap or PSI term: darwin cannot start firing+ * on a signal that was never measured there.+ *+ * A consumer must treat `undefined` as NO SIGNAL, never as zero — a zero here reads as+ * "swap totally exhausted" / "no stall", and both are claims the reader has not earned.+ */+ /** Total swap in MB; `0` legitimately means "this host has no swap configured". */+ swapTotalMb?: number+ /** Free swap in MB. */+ swapFreeMb?: number+ /** `/proc/pressure/memory` `some avg60` — % of the last minute at least one task stalled on memory. */+ psiSomeAvg60?: number+ /** `/proc/pressure/memory` `full avg60` — % of the last minute EVERY task was stalled. Thrash. */+ psiFullAvg60?: number}/** One nt- session's memory, as the panel renders it. */