@agentguard-run/burn 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.4 (2026-12-04)
4
+
5
+ - New: a growth watch for a long-lived host (`GrowthRunner`, `GrowthWatch`, `stepGrowth`, `stopNamed`). Fed one process sample every 15 seconds, it names a process under an agent session whose memory climbed for two minutes without a break: at least 512 MB over the window, growth in every third of it, at most a quarter handed back, and a size of 1 GB or more while the machine is short of memory (a quarter of RAM while it is not). A process that held at least 2 GB and a tenth of RAM for the whole window is listed without an announcement while memory is short, and leaves the list two minutes after it recovers.
6
+ - Size is the footprint (resident plus compressed and swapped): on macOS from one streaming `top`, on Linux `VmRSS` plus `VmSwap`. Under pressure the resident size alone can read 11 MB for a 5 GB process. From 10 GB up macOS prints whole gigabytes, so those readings are judged over four minutes by the same rule.
7
+ - Identity is the process number and the OS start identity, read in UTC. A program that renames itself keeps its history; a reused number starts a new one.
8
+ - `stopNamed` is the only signal site and acts only when called for one listed process: it reads the process again and refuses if it is gone, has another start identity or command, is not what the caller says the person was shown, is an agent session, or is this process or one of its ancestors (or the ancestry cannot be read whole). One SIGTERM, never anything stronger, at most once per listing. Nothing in the watch acts on its own.
9
+ - A deterministic simulator (`tests/helpers/growth-sim.ts`) replays the Dec 3 2026 incident, ordinary builds, collector sawtooths, single loads, process-number reuse, exec swaps, self-renaming and processes that ignore the stop, with the real reader's coarse sizes, late samples and missing footprints, across 2,000 random machines. 46 planted defects in the watch are each caught by the tests.
10
+ - `agentHost` recognises a session started as `node -r preload.js <script>`: the values of node options that take one are skipped when finding the script.
11
+ - Limits: a process never seen under a session; many small workers; two loads a minute apart; a leak stepping less often than every 45 seconds; up to six minutes to name a slow leak above 10 GB on macOS; the instant between the identity re-read and the signal.
12
+
3
13
  ## 0.7.3 (2026-12-04)
4
14
 
5
15
  - The status line shows this machine: `N% memory free` always (macOS and Linux), `swap N GB` when swap is heavy (half of physical memory or more, or 4 GB beside a low disk), and `disk N GB free` first when free disk is low. Memory turns yellow at 15% available (or 20% while the macOS kernel reports a warning) and red at 10% or a kernel critical level. These parts are never dropped before the optional fields on a narrow terminal.
@@ -57,7 +57,19 @@ function agentHost(command) {
57
57
  if (['claude', 'codex'].includes(executable))
58
58
  return executable;
59
59
  if (/^node(?:js)?$/.test(executable)) {
60
- const script = words.slice(1).find(word => !word.startsWith('-')) || '';
60
+ // The script is the first word that is neither an option nor the value of an option that takes one.
61
+ let script = '';
62
+ for (let index = 1; index < words.length; index++) {
63
+ const word = words[index];
64
+ if (/^(?:-r|--require|--import|--loader|--experimental-loader|--env-file|-C|--conditions|--title|--inspect-port|--max-http-header-size|--stack-trace-limit)$/.test(word)) {
65
+ index++;
66
+ continue;
67
+ }
68
+ if (word.startsWith('-'))
69
+ continue;
70
+ script = word;
71
+ break;
72
+ }
61
73
  if (/(?:^|\/)codex(?:\.js)?$/.test(script) || /\/@openai\/codex\/bin\/codex\.js$/.test(script))
62
74
  return 'codex';
63
75
  if (/(?:^|\/)claude(?:\.js)?$/.test(script) || /\/@anthropic-ai\/claude-code\/cli\.js$/.test(script))
@@ -0,0 +1,85 @@
1
+ import type { PressureLevel } from './disk';
2
+ import { type GrowthConfig, type GrowthFinding, type GrowthStep, type StopOutcome } from './growth';
3
+ import { type FootprintSample } from './growth-sample';
4
+ import { type CommandRunner } from './platform';
5
+ import type { ProcessSnapshot } from './types';
6
+ export declare const GROWTH_INTERVAL_MS = 15000;
7
+ export interface SourceSample {
8
+ tableComplete: boolean;
9
+ processes: ProcessSnapshot[];
10
+ footprint: FootprintSample | null;
11
+ }
12
+ /** Where samples come from. One implementation per OS; tests supply a scripted one. */
13
+ export interface GrowthSource {
14
+ /** Calls back once per sample. Never calls back while the previous callback's work is still running. */
15
+ start(onSample: (sample: SourceSample) => void): void;
16
+ stop(): void;
17
+ /** A fresh, complete process table, or null when it could not be read whole. */
18
+ table(): Promise<ProcessSnapshot[] | null>;
19
+ /** One fresh read of one process, in the same format as the table. Null when it is gone. */
20
+ readOne(pid: number): Promise<ProcessSnapshot | null>;
21
+ }
22
+ export interface TopChild {
23
+ stdout: {
24
+ setEncoding(encoding: 'utf8'): void;
25
+ on(event: 'data', listener: (chunk: string) => void): void;
26
+ };
27
+ on(event: 'exit' | 'error', listener: () => void): void;
28
+ kill(signal: 'SIGTERM'): void;
29
+ }
30
+ export interface DarwinSourceOptions {
31
+ spawnTop?: () => TopChild;
32
+ runner?: CommandRunner;
33
+ restartMs?: number;
34
+ /** Consecutive starts that produced no sample before the source gives up. */
35
+ maxFailures?: number;
36
+ setTimer?: (work: () => void, ms: number) => {
37
+ unref?(): void;
38
+ };
39
+ clearTimer?: (timer: unknown) => void;
40
+ }
41
+ export declare function darwinSource(options?: DarwinSourceOptions): GrowthSource;
42
+ export interface LinuxSourceOptions {
43
+ procRoot?: string;
44
+ runner?: CommandRunner;
45
+ intervalMs?: number;
46
+ maxProcesses?: number;
47
+ }
48
+ export declare function linuxSource(options?: LinuxSourceOptions): GrowthSource;
49
+ export interface GrowthRunnerOptions {
50
+ source?: GrowthSource | null;
51
+ platform?: string;
52
+ /** This process: it and its ancestors are never stopped. */
53
+ pid?: number;
54
+ now?: () => number;
55
+ totalRamBytes?: () => number | null;
56
+ level?: () => Promise<PressureLevel>;
57
+ /** Sends the signal. Must not wait on anything before the system call. */
58
+ kill?: (pid: number, signal: 'SIGTERM') => void;
59
+ onStep?: (step: GrowthStep) => void;
60
+ /** The rule's numbers. Left alone outside tests and rehearsals. */
61
+ config?: GrowthConfig;
62
+ }
63
+ export interface GrowthView {
64
+ /** When the last complete sample was taken. Null before the first. */
65
+ sampledAt: number | null;
66
+ findings: GrowthFinding[];
67
+ }
68
+ export declare class GrowthRunner {
69
+ private readonly options;
70
+ private readonly source;
71
+ private readonly watch;
72
+ private readonly now;
73
+ private sampledAt;
74
+ private started;
75
+ constructor(options?: GrowthRunnerOptions);
76
+ /** False when this OS has no reader. Safe to call twice. */
77
+ start(): boolean;
78
+ stop(): void;
79
+ view(): GrowthView;
80
+ /** The person chose "Stop it" for one listed process. */
81
+ stopFinding(key: string, shown?: (command: string) => boolean): Promise<{
82
+ outcome: StopOutcome;
83
+ reason: string;
84
+ }>;
85
+ }
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GrowthRunner = exports.GROWTH_INTERVAL_MS = void 0;
4
+ exports.darwinSource = darwinSource;
5
+ exports.linuxSource = linuxSource;
6
+ /**
7
+ * Runs the growth watch against the real machine for a long-lived worker.
8
+ * Everything here is asynchronous and bounded: a sample that is not ready is
9
+ * skipped, never queued, so the worker's replies are never held up.
10
+ */
11
+ const node_child_process_1 = require("node:child_process");
12
+ const node_fs_1 = require("node:fs");
13
+ const node_os_1 = require("node:os");
14
+ const node_path_1 = require("node:path");
15
+ const growth_1 = require("./growth");
16
+ const growth_sample_1 = require("./growth-sample");
17
+ const memory_1 = require("./memory");
18
+ const platform_1 = require("./platform");
19
+ /** Start identities are printed in UTC so a time zone or daylight change never renames a running process. */
20
+ const UTC = { TZ: 'UTC' };
21
+ const PS_COLUMNS = 'pid=,ppid=,rss=,tty=,lstart=,etime=,command=';
22
+ exports.GROWTH_INTERVAL_MS = 15_000;
23
+ function darwinSource(options = {}) {
24
+ const runner = options.runner ?? platform_1.runLocal;
25
+ const spawnTop = options.spawnTop ?? (() => (0, node_child_process_1.spawn)('top', [...growth_sample_1.TOP_FOOTPRINT_ARGS], { stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, LC_ALL: 'C' } }));
26
+ const setTimer = options.setTimer ?? ((work, ms) => setTimeout(work, ms)), clearTimer = options.clearTimer ?? (timer => clearTimeout(timer));
27
+ let child = null, running = false, busy = false, failures = 0, timer = null;
28
+ const table = async () => {
29
+ const result = await runner('ps', ['-axo', PS_COLUMNS], { timeoutMs: 2000, maxBuffer: 16 * 1024 * 1024, env: UTC });
30
+ if (result.code !== 0)
31
+ return null;
32
+ const rows = (0, platform_1.parsePs)(result.stdout);
33
+ return rows.length > 0 ? rows : null;
34
+ };
35
+ const launch = (onSample) => {
36
+ if (!running)
37
+ return;
38
+ const stream = new growth_sample_1.TopFootprintStream();
39
+ let mine;
40
+ try {
41
+ mine = spawnTop();
42
+ }
43
+ catch {
44
+ ended(onSample, null);
45
+ return;
46
+ }
47
+ child = mine;
48
+ mine.stdout.setEncoding('utf8');
49
+ mine.stdout.on('data', chunk => {
50
+ if (!running || child !== mine)
51
+ return;
52
+ let samples;
53
+ try {
54
+ samples = stream.push(chunk);
55
+ }
56
+ catch {
57
+ return;
58
+ }
59
+ for (const footprint of samples) {
60
+ failures = 0;
61
+ // The process table is read after the footprints, so every process with a footprint has a row unless it just exited.
62
+ if (busy)
63
+ continue;
64
+ busy = true;
65
+ void table().then(processes => { if (running)
66
+ onSample({ tableComplete: processes !== null, processes: processes ?? [], footprint }); })
67
+ .catch(() => { }).finally(() => { busy = false; });
68
+ }
69
+ });
70
+ mine.on('exit', () => ended(onSample, mine));
71
+ mine.on('error', () => ended(onSample, mine));
72
+ };
73
+ const ended = (onSample, which) => {
74
+ if (!running || (which !== null && child !== which))
75
+ return;
76
+ child = null;
77
+ if (++failures > (options.maxFailures ?? 5)) {
78
+ running = false;
79
+ return;
80
+ }
81
+ timer = setTimer(() => launch(onSample), options.restartMs ?? 30_000);
82
+ timer.unref?.();
83
+ };
84
+ return {
85
+ start(onSample) { if (running)
86
+ return; running = true; failures = 0; launch(onSample); },
87
+ stop() { running = false; if (timer)
88
+ clearTimer(timer); timer = null; const mine = child; child = null; try {
89
+ mine?.kill('SIGTERM');
90
+ }
91
+ catch { /* Already gone. */ } },
92
+ table,
93
+ async readOne(pid) {
94
+ if (!Number.isSafeInteger(pid) || pid < 1)
95
+ return null;
96
+ const result = await runner('ps', ['-o', PS_COLUMNS, '-p', String(pid)], { timeoutMs: 1500, env: UTC });
97
+ const rows = (0, platform_1.parsePs)(result.stdout);
98
+ return rows.length === 1 && rows[0].pid === pid ? rows[0] : null;
99
+ },
100
+ };
101
+ }
102
+ function linuxSource(options = {}) {
103
+ const root = options.procRoot ?? '/proc', runner = options.runner ?? platform_1.runLocal;
104
+ let timer = null, busy = false;
105
+ const table = async () => {
106
+ const skipped = [];
107
+ const rows = await (0, platform_1.procProcesses)(root, runner, undefined, options.maxProcesses ?? 10_000, skipped);
108
+ return rows.length > 0 && skipped.length === 0 ? rows : null;
109
+ };
110
+ const footprints = async (rows) => {
111
+ const result = new Map();
112
+ for (let index = 0; index < rows.length; index += 64) {
113
+ await Promise.all(rows.slice(index, index + 64).map(async (row) => {
114
+ try {
115
+ const bytes = (0, growth_sample_1.parseProcStatusFootprint)(await node_fs_1.promises.readFile((0, node_path_1.join)(root, String(row.pid), 'status'), 'utf8'));
116
+ if (bytes !== null)
117
+ result.set(row.pid, bytes);
118
+ }
119
+ catch { /* Exited or not readable: its footprint is unknown, never zero. */ }
120
+ }));
121
+ }
122
+ return result;
123
+ };
124
+ return {
125
+ start(onSample) {
126
+ if (timer)
127
+ return;
128
+ const tick = () => {
129
+ if (busy)
130
+ return;
131
+ busy = true;
132
+ void (async () => {
133
+ const rows = await table();
134
+ onSample({ tableComplete: rows !== null, processes: rows ?? [], footprint: rows ? { complete: true, footprints: await footprints(rows) } : null });
135
+ })().catch(() => { }).finally(() => { busy = false; });
136
+ };
137
+ timer = setInterval(tick, options.intervalMs ?? exports.GROWTH_INTERVAL_MS);
138
+ timer.unref?.();
139
+ tick();
140
+ },
141
+ stop() { if (timer)
142
+ clearInterval(timer); timer = null; },
143
+ table,
144
+ async readOne(pid) { return (await table())?.find(row => row.pid === pid) ?? null; },
145
+ };
146
+ }
147
+ class GrowthRunner {
148
+ options;
149
+ source;
150
+ watch;
151
+ now;
152
+ sampledAt = null;
153
+ started = false;
154
+ constructor(options = {}) {
155
+ this.options = options;
156
+ const platform = options.platform ?? process.platform;
157
+ this.source = options.source !== undefined ? options.source : platform === 'darwin' ? darwinSource() : platform === 'linux' ? linuxSource() : null;
158
+ this.now = options.now ?? Date.now;
159
+ const source = this.source, self = options.pid ?? process.pid, kill = options.kill ?? ((pid, signal) => { process.kill(pid, signal); });
160
+ const dependencies = {
161
+ now: this.now,
162
+ readOne: async (pid) => { const row = source ? await source.readOne(pid) : null; return row ? asGrowth(row) : null; },
163
+ protectedPids: async () => {
164
+ const rows = source ? await source.table() : null;
165
+ if (!rows)
166
+ return null;
167
+ const parent = new Map(rows.map(row => [row.pid, row.ppid]));
168
+ const guarded = new Set([1]);
169
+ let pid = self;
170
+ // Any break in the chain from this process up to pid 1 means the ancestry is not known.
171
+ while (pid > 1) {
172
+ if (guarded.has(pid))
173
+ return null;
174
+ guarded.add(pid);
175
+ const next = parent.get(pid);
176
+ if (next === undefined || !Number.isSafeInteger(next) || next < 0)
177
+ return null;
178
+ pid = next;
179
+ }
180
+ return guarded;
181
+ },
182
+ // No await before the system call: the identity was read in the step just before this one.
183
+ signal: async (pid, signal) => { kill(pid, signal); },
184
+ };
185
+ this.watch = new growth_1.GrowthWatch(dependencies, options.config);
186
+ }
187
+ /** False when this OS has no reader. Safe to call twice. */
188
+ start() {
189
+ if (!this.source)
190
+ return false;
191
+ if (this.started)
192
+ return true;
193
+ this.started = true;
194
+ const level = this.options.level ?? (async () => (await (0, memory_1.systemMemoryProbe)()()).level);
195
+ const ram = this.options.totalRamBytes ?? (() => (0, node_os_1.totalmem)());
196
+ this.source.start(sample => {
197
+ void (async () => {
198
+ let pressure = 'unknown';
199
+ try {
200
+ pressure = await level();
201
+ }
202
+ catch { /* Unknown is never guessed. */ }
203
+ if (!this.started)
204
+ return;
205
+ const step = this.watch.step((0, growth_sample_1.growthSample)({ ...sample, at: this.now(), level: pressure, totalRamBytes: ram() }));
206
+ if (step.state.lastAt !== null)
207
+ this.sampledAt = step.state.lastAt;
208
+ try {
209
+ this.options.onStep?.(step);
210
+ }
211
+ catch { /* A display problem never stops the watch. */ }
212
+ })().catch(() => { });
213
+ });
214
+ return true;
215
+ }
216
+ stop() { this.started = false; this.source?.stop(); }
217
+ view() {
218
+ return { sampledAt: this.sampledAt, findings: Object.values(this.watch.state.findings).sort((a, b) => b.sizeBytes - a.sizeBytes || a.pid - b.pid) };
219
+ }
220
+ /** The person chose "Stop it" for one listed process. */
221
+ stopFinding(key, shown) {
222
+ if (!this.started)
223
+ return Promise.resolve({ outcome: 'refused', reason: 'The watch is not running.' });
224
+ return this.watch.stop(key, shown);
225
+ }
226
+ }
227
+ exports.GrowthRunner = GrowthRunner;
228
+ const asGrowth = (row) => ({ pid: row.pid, ppid: row.ppid, startedAt: row.startedAt, command: row.command, footprintBytes: null });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Turns what the OS prints into the samples the growth watch reads. Parsing
3
+ * only: the worker owns the child process and the timer.
4
+ *
5
+ * macOS: one long-running `top -l 0 -s 15 -stats pid,mem`. Its MEM column is
6
+ * the footprint (resident plus compressed and swapped), which `ps` cannot
7
+ * give: under pressure a 5 GB process can show 11 MB resident.
8
+ * Linux: VmRSS plus VmSwap from /proc/<pid>/status.
9
+ */
10
+ import type { PressureLevel } from './disk';
11
+ import type { GrowthSample } from './growth';
12
+ import type { ProcessSnapshot } from './types';
13
+ export declare const TOP_FOOTPRINT_ARGS: readonly ["-l", "0", "-s", "15", "-stats", "pid,mem"];
14
+ /** "4958M", "18M-", "630M+", "12G", "0B". Anything else is unknown, never zero. */
15
+ export declare function parseFootprint(text: string): number | null;
16
+ export interface FootprintSample {
17
+ /** True only when every process the header counted has a row. */
18
+ complete: boolean;
19
+ footprints: Map<number, number>;
20
+ }
21
+ /**
22
+ * Splits the stream into samples. A sample is handed over the moment its last
23
+ * row arrives; one that is cut off by the next header is handed over as not
24
+ * complete, so the watch ignores it.
25
+ */
26
+ export declare class TopFootprintStream {
27
+ private pending;
28
+ private expected;
29
+ private rows;
30
+ private inTable;
31
+ private current;
32
+ private doubled;
33
+ private open;
34
+ push(chunk: string): FootprintSample[];
35
+ }
36
+ /** Linux: resident plus swapped, from one /proc/<pid>/status. Kernel threads have neither line. */
37
+ export declare function parseProcStatusFootprint(text: string): number | null;
38
+ export interface SampleParts {
39
+ at: number;
40
+ /** False when the process table was cut short or timed out. */
41
+ tableComplete: boolean;
42
+ processes: ProcessSnapshot[];
43
+ footprint: FootprintSample | null;
44
+ level: PressureLevel;
45
+ totalRamBytes: number | null;
46
+ }
47
+ /** A process in the table with no footprint row keeps its place with an unknown size. */
48
+ export declare function growthSample(parts: SampleParts): GrowthSample;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TopFootprintStream = exports.TOP_FOOTPRINT_ARGS = void 0;
4
+ exports.parseFootprint = parseFootprint;
5
+ exports.parseProcStatusFootprint = parseProcStatusFootprint;
6
+ exports.growthSample = growthSample;
7
+ exports.TOP_FOOTPRINT_ARGS = ['-l', '0', '-s', '15', '-stats', 'pid,mem'];
8
+ const UNIT = { B: 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
9
+ /** "4958M", "18M-", "630M+", "12G", "0B". Anything else is unknown, never zero. */
10
+ function parseFootprint(text) {
11
+ const match = /^(\d{1,7})([BKMGT])[+-]?$/.exec(text);
12
+ return match ? Number(match[1]) * UNIT[match[2]] : null;
13
+ }
14
+ /**
15
+ * Splits the stream into samples. A sample is handed over the moment its last
16
+ * row arrives; one that is cut off by the next header is handed over as not
17
+ * complete, so the watch ignores it.
18
+ */
19
+ class TopFootprintStream {
20
+ pending = '';
21
+ expected = null;
22
+ rows = 0;
23
+ inTable = false;
24
+ current = new Map();
25
+ doubled = new Set();
26
+ open = false;
27
+ push(chunk) {
28
+ const done = [];
29
+ this.pending += chunk;
30
+ // A line is only read once its newline has arrived. A runaway line is dropped with its sample.
31
+ if (this.pending.length > 1_000_000 && !this.pending.includes('\n')) {
32
+ this.pending = '';
33
+ this.expected = null;
34
+ this.open = false;
35
+ return done;
36
+ }
37
+ let end;
38
+ while ((end = this.pending.indexOf('\n')) >= 0) {
39
+ const line = this.pending.slice(0, end).trimEnd();
40
+ this.pending = this.pending.slice(end + 1);
41
+ const header = /^Processes:\s+(\d{1,6})\s+total\b/.exec(line);
42
+ if (header) {
43
+ if (this.open)
44
+ done.push({ complete: false, footprints: this.current });
45
+ this.expected = Number(header[1]);
46
+ this.rows = 0;
47
+ this.inTable = false;
48
+ this.current = new Map();
49
+ this.doubled = new Set();
50
+ this.open = true;
51
+ continue;
52
+ }
53
+ if (!this.open)
54
+ continue;
55
+ if (/^PID\s+MEM\s*$/.test(line)) {
56
+ this.inTable = true;
57
+ continue;
58
+ }
59
+ if (!this.inTable)
60
+ continue;
61
+ const row = /^(\d{1,10})\s+(\S+)$/.exec(line);
62
+ if (!row)
63
+ continue;
64
+ this.rows++;
65
+ const pid = Number(row[1]), bytes = parseFootprint(row[2]);
66
+ // A pid printed more than once is ambiguous: it gets no footprint in this sample.
67
+ if (this.current.has(pid) || this.doubled.has(pid)) {
68
+ this.current.delete(pid);
69
+ this.doubled.add(pid);
70
+ }
71
+ else if (bytes !== null)
72
+ this.current.set(pid, bytes);
73
+ if (this.rows === this.expected) {
74
+ done.push({ complete: true, footprints: this.current });
75
+ this.open = false;
76
+ this.current = new Map();
77
+ this.doubled = new Set();
78
+ }
79
+ }
80
+ return done;
81
+ }
82
+ }
83
+ exports.TopFootprintStream = TopFootprintStream;
84
+ /** Linux: resident plus swapped, from one /proc/<pid>/status. Kernel threads have neither line. */
85
+ function parseProcStatusFootprint(text) {
86
+ const resident = /^VmRSS:\s+(\d{1,12})\s+kB$/m.exec(text), swapped = /^VmSwap:\s+(\d{1,12})\s+kB$/m.exec(text);
87
+ return resident ? (Number(resident[1]) + (swapped ? Number(swapped[1]) : 0)) * 1024 : null;
88
+ }
89
+ /** A process in the table with no footprint row keeps its place with an unknown size. */
90
+ function growthSample(parts) {
91
+ const footprints = parts.footprint?.footprints ?? new Map();
92
+ const processes = parts.processes.map(item => ({
93
+ pid: item.pid, ppid: item.ppid, startedAt: item.startedAt, command: item.command,
94
+ footprintBytes: footprints.get(item.pid) ?? null,
95
+ }));
96
+ return {
97
+ at: parts.at, complete: parts.tableComplete === true && parts.footprint?.complete === true && processes.length > 0,
98
+ totalRamBytes: typeof parts.totalRamBytes === 'number' && Number.isFinite(parts.totalRamBytes) && parts.totalRamBytes > 0 ? parts.totalRamBytes : null,
99
+ level: parts.level, processes,
100
+ };
101
+ }
@@ -0,0 +1,157 @@
1
+ import type { PressureLevel } from './disk';
2
+ export declare const GIB: number;
3
+ export declare const MIB: number;
4
+ export interface GrowthConfig {
5
+ /** The sustained-growth window. */
6
+ windowMs: number;
7
+ /** Tolerance on the window edge, one sample interval: samples run late on a machine that is swapping. */
8
+ slackMs: number;
9
+ /** Readings in the window must span at least this long. */
10
+ minSpanMs: number;
11
+ /** Judged by time, not by count: missed samples, slow samples and missing footprints are all tolerated down to this many readings. */
12
+ minReadings: number;
13
+ minGrowthBytes: number;
14
+ /** Each third of the window must carry at least this share of the growth: one load followed by drift, or a climb shorter than the window, is not a leak. */
15
+ minThirdShare: number;
16
+ /** Readings at or above this size are whole gigabytes on macOS. They are judged over the longer window below, by the same rule. */
17
+ coarseFromBytes: number;
18
+ coarseWindowMs: number;
19
+ coarseMinSpanMs: number;
20
+ /** Memory handed back inside the window may be at most this share of the growth: a collector's sawtooth is not a leak. */
21
+ maxGiveBackShare: number;
22
+ /** A process this large under a session is listed, without a notice, while the machine is short of memory. */
23
+ largeMinBytes: number;
24
+ largeShare: number;
25
+ /** Size floor while the machine is short of memory. */
26
+ pressuredFloorBytes: number;
27
+ /** Size floor as a share of RAM while memory is fine or unknown. */
28
+ calmFloorShare: number;
29
+ calmFloorMinBytes: number;
30
+ /** A named process with no growth for this long reads "holding". */
31
+ holdingAfterMs: number;
32
+ maxTracks: number;
33
+ }
34
+ export declare const DEFAULT_GROWTH: GrowthConfig;
35
+ export interface GrowthProcess {
36
+ pid: number;
37
+ ppid: number;
38
+ /** Stable OS start identity. A process without one is never tracked. */
39
+ startedAt: string | null;
40
+ command: string;
41
+ /** Null when this sample has no footprint for the process. */
42
+ footprintBytes: number | null;
43
+ }
44
+ export interface GrowthSample {
45
+ at: number;
46
+ /** False when the process table or the footprint read was cut short. Ignored whole. */
47
+ complete: boolean;
48
+ totalRamBytes: number | null;
49
+ level: PressureLevel;
50
+ processes: GrowthProcess[];
51
+ }
52
+ interface Track {
53
+ pid: number;
54
+ startedAt: string;
55
+ /** The latest command line. Not part of the identity: a program may rename itself in place. */
56
+ command: string;
57
+ /** Seen under an agent session at least once. Kept after a reparent. */
58
+ underSession: boolean;
59
+ readings: Array<[at: number, bytes: number]>;
60
+ }
61
+ export interface GrowthFinding {
62
+ key: string;
63
+ pid: number;
64
+ startedAt: string;
65
+ command: string;
66
+ namedAt: number;
67
+ /** 'grew': sustained growth was seen. 'large': listed for its size alone while memory is short; never announced. */
68
+ origin: 'grew' | 'large';
69
+ /** Size when it was first listed. Falling under half of it drops the finding. */
70
+ namedBytes: number;
71
+ sizeBytes: number;
72
+ peakBytes: number;
73
+ /** Growth over the window the last time sustained growth was seen. Zero for a process listed for size alone. */
74
+ grewBytes: number;
75
+ /** The span that growth was measured over: about two minutes, about four where sizes are whole gigabytes. */
76
+ grewOverMs: number;
77
+ lastGrewAt: number | null;
78
+ status: 'growing' | 'holding' | 'stop_sent';
79
+ stopSentAt: number | null;
80
+ }
81
+ export interface GrowthState {
82
+ version: 1;
83
+ lastAt: number | null;
84
+ /** When machine memory was last warn or crit. A process listed for size alone leaves the list two minutes after. */
85
+ pressuredAt: number | null;
86
+ tracks: Record<string, Track>;
87
+ findings: Record<string, GrowthFinding>;
88
+ }
89
+ export declare const emptyGrowthState: () => GrowthState;
90
+ export declare const growthKey: (pid: number, startedAt: string) => string;
91
+ /** Pids with an agent session process somewhere above them in this sample. */
92
+ export declare function underAgentSession(processes: GrowthProcess[]): Set<number>;
93
+ export declare function sizeFloor(level: PressureLevel, totalRamBytes: number | null, config?: GrowthConfig): number;
94
+ /** How much, and over how long: the words shown to the person must name the real span. */
95
+ export interface MeasuredGrowth {
96
+ grewBytes: number;
97
+ overMs: number;
98
+ }
99
+ /**
100
+ * Growth over the window, or null when the readings do not show sustained
101
+ * growth. Judged on time and totals, never on sample-to-sample steps. Where
102
+ * the reader only prints whole gigabytes (macOS, from 10 GB up) a two-minute
103
+ * window holds too few steps to tell a leak from one load, so those readings
104
+ * are judged by the same rule over four minutes.
105
+ */
106
+ export declare function sustainedGrowth(readings: Array<[number, number]>, now: number, config?: GrowthConfig): number | null;
107
+ export declare function measureGrowth(readings: Array<[number, number]>, now: number, config?: GrowthConfig): MeasuredGrowth | null;
108
+ /** Size at which a process under a session is listed for its size alone. Only while the machine is short of memory. */
109
+ export declare function largeFloor(level: PressureLevel, totalRamBytes: number | null, config?: GrowthConfig): number;
110
+ export interface GrowthStep {
111
+ state: GrowthState;
112
+ /** Everything named right now, largest first. */
113
+ findings: GrowthFinding[];
114
+ /** Sustained growth seen for the first time in this step: the only moment a notice is due. Never a process listed for size alone. */
115
+ fresh: GrowthFinding[];
116
+ }
117
+ export declare function stepGrowth(previous: GrowthState, sample: GrowthSample, config?: GrowthConfig): GrowthStep;
118
+ export interface StopDependencies {
119
+ /** One fresh single-process read, made by the same process that signals. Null when the pid is gone. */
120
+ readOne(pid: number): Promise<GrowthProcess | null>;
121
+ /** Pid 1, this process and its ancestors. Null when the ancestry could not be verified. */
122
+ protectedPids(): Promise<Set<number> | null>;
123
+ signal(pid: number, signal: 'SIGTERM'): Promise<void>;
124
+ now(): number;
125
+ }
126
+ export type StopOutcome = 'sent' | 'refused' | 'signal_failed';
127
+ export interface StopResult {
128
+ state: GrowthState;
129
+ outcome: StopOutcome;
130
+ reason: string;
131
+ }
132
+ /**
133
+ * The person chose "Stop it" for one named process. Sends SIGTERM at most once
134
+ * per listing, only to the same program that was named, never anything
135
+ * stronger. Any doubt is a refusal. `shown` answers whether a command line is
136
+ * what the person saw when they chose.
137
+ */
138
+ export declare function stopNamed(state: GrowthState, key: string, dependencies: StopDependencies, shown?: (command: string) => boolean): Promise<StopResult>;
139
+ /**
140
+ * The one authoritative state for a worker: samples and stop requests go
141
+ * through here, so two taps on the same finding send one signal and a sample
142
+ * that lands while a stop is in flight does not lose its record.
143
+ */
144
+ export declare class GrowthWatch {
145
+ private readonly dependencies;
146
+ private readonly config;
147
+ private current;
148
+ private readonly stopping;
149
+ constructor(dependencies: StopDependencies, config?: GrowthConfig, state?: GrowthState);
150
+ get state(): GrowthState;
151
+ step(sample: GrowthSample): GrowthStep;
152
+ stop(key: string, shown?: (command: string) => boolean): Promise<{
153
+ outcome: StopOutcome;
154
+ reason: string;
155
+ }>;
156
+ }
157
+ export {};
@@ -0,0 +1,337 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GrowthWatch = exports.growthKey = exports.emptyGrowthState = exports.DEFAULT_GROWTH = exports.MIB = exports.GIB = void 0;
4
+ exports.underAgentSession = underAgentSession;
5
+ exports.sizeFloor = sizeFloor;
6
+ exports.sustainedGrowth = sustainedGrowth;
7
+ exports.measureGrowth = measureGrowth;
8
+ exports.largeFloor = largeFloor;
9
+ exports.stepGrowth = stepGrowth;
10
+ exports.stopNamed = stopNamed;
11
+ /**
12
+ * Growth watch: names a process under an agent session whose memory keeps
13
+ * climbing, and stops it only when the person chooses to. Pure state machine:
14
+ * the worker feeds it one sample every 15 seconds and no clock, file or OS
15
+ * call lives here. Nothing in this file acts on its own.
16
+ *
17
+ * Size is the process footprint (resident plus compressed and swapped). On a
18
+ * pressured Mac the resident size alone can read 11 MB for a 5 GB process.
19
+ */
20
+ const classify_1 = require("./classify");
21
+ exports.GIB = 1024 ** 3;
22
+ exports.MIB = 1024 ** 2;
23
+ exports.DEFAULT_GROWTH = {
24
+ windowMs: 120_000, slackMs: 15_000, minSpanMs: 105_000, minReadings: 5,
25
+ minGrowthBytes: 512 * exports.MIB, minThirdShare: 0.2, coarseFromBytes: 10 * exports.GIB, coarseWindowMs: 240_000, coarseMinSpanMs: 225_000, maxGiveBackShare: 0.25,
26
+ largeMinBytes: 2 * exports.GIB, largeShare: 0.1, pressuredFloorBytes: exports.GIB, calmFloorShare: 0.25, calmFloorMinBytes: 2 * exports.GIB,
27
+ holdingAfterMs: 120_000, maxTracks: 600,
28
+ };
29
+ const emptyGrowthState = () => ({ version: 1, lastAt: null, pressuredAt: null, tracks: {}, findings: {} });
30
+ exports.emptyGrowthState = emptyGrowthState;
31
+ const growthKey = (pid, startedAt) => `${pid}|${startedAt}`;
32
+ exports.growthKey = growthKey;
33
+ const whole = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
34
+ /** One closed-shape read of an untrusted process row. */
35
+ function cleanProcess(input) {
36
+ if (!input || typeof input !== 'object')
37
+ return null;
38
+ const { pid, ppid, startedAt, command, footprintBytes } = input;
39
+ if (!whole(pid) || pid < 1 || !whole(ppid) || typeof command !== 'string' || command.length === 0)
40
+ return null;
41
+ return {
42
+ pid, ppid, command, startedAt: typeof startedAt === 'string' && startedAt.length > 0 ? startedAt : null,
43
+ footprintBytes: typeof footprintBytes === 'number' && Number.isFinite(footprintBytes) && footprintBytes >= 0 ? footprintBytes : null,
44
+ };
45
+ }
46
+ /** Pids with an agent session process somewhere above them in this sample. */
47
+ function underAgentSession(processes) {
48
+ const parent = new Map(), hosts = new Set(), result = new Set();
49
+ for (const item of processes) {
50
+ parent.set(item.pid, item.ppid);
51
+ if ((0, classify_1.agentHost)(item.command))
52
+ hosts.add(item.pid);
53
+ }
54
+ for (const item of processes) {
55
+ const seen = new Set([item.pid]);
56
+ let current = item.ppid;
57
+ while (current > 0 && !seen.has(current)) {
58
+ if (hosts.has(current)) {
59
+ result.add(item.pid);
60
+ break;
61
+ }
62
+ seen.add(current);
63
+ const next = parent.get(current);
64
+ if (next === undefined)
65
+ break;
66
+ current = next;
67
+ }
68
+ }
69
+ return result;
70
+ }
71
+ function sizeFloor(level, totalRamBytes, config = exports.DEFAULT_GROWTH) {
72
+ if (level === 'warn' || level === 'crit')
73
+ return config.pressuredFloorBytes;
74
+ // With memory fine or unreadable, only a process holding a large share of the machine is worth a word.
75
+ if (totalRamBytes === null || !Number.isFinite(totalRamBytes) || totalRamBytes <= 0)
76
+ return Number.POSITIVE_INFINITY;
77
+ return Math.max(config.calmFloorMinBytes, totalRamBytes * config.calmFloorShare);
78
+ }
79
+ /** The size at one instant, on the straight line between the readings either side of it. */
80
+ function sizeAt(readings, at) {
81
+ for (let index = 1; index < readings.length; index++) {
82
+ const [t0, v0] = readings[index - 1], [t1, v1] = readings[index];
83
+ if (at <= t1)
84
+ return t1 === t0 ? v1 : v0 + (v1 - v0) * (at - t0) / (t1 - t0);
85
+ }
86
+ return readings[readings.length - 1][1];
87
+ }
88
+ function grewThroughout(inside, now, minSpanMs, minReadings, config) {
89
+ if (inside.length < minReadings)
90
+ return null;
91
+ const first = inside[0], last = inside[inside.length - 1];
92
+ if (last[0] !== now || last[0] - first[0] < minSpanMs)
93
+ return null;
94
+ const grew = last[1] - first[1];
95
+ if (grew < config.minGrowthBytes)
96
+ return null;
97
+ let givenBack = 0;
98
+ for (let index = 1; index < inside.length; index++) {
99
+ const change = inside[index][1] - inside[index - 1][1];
100
+ if (change < 0)
101
+ givenBack -= change;
102
+ }
103
+ if (givenBack > grew * config.maxGiveBackShare)
104
+ return null;
105
+ // Growth in every third of the span, measured at the exact third marks so a late or missing sample does not move them.
106
+ const span = last[0] - first[0];
107
+ const edges = [first[1], sizeAt(inside, first[0] + span / 3), sizeAt(inside, first[0] + span * 2 / 3), last[1]];
108
+ for (let part = 0; part < 3; part++)
109
+ if (edges[part + 1] - edges[part] < grew * config.minThirdShare)
110
+ return null;
111
+ return { grewBytes: grew, overMs: span };
112
+ }
113
+ /**
114
+ * Growth over the window, or null when the readings do not show sustained
115
+ * growth. Judged on time and totals, never on sample-to-sample steps. Where
116
+ * the reader only prints whole gigabytes (macOS, from 10 GB up) a two-minute
117
+ * window holds too few steps to tell a leak from one load, so those readings
118
+ * are judged by the same rule over four minutes.
119
+ */
120
+ function sustainedGrowth(readings, now, config = exports.DEFAULT_GROWTH) {
121
+ return measureGrowth(readings, now, config)?.grewBytes ?? null;
122
+ }
123
+ function measureGrowth(readings, now, config = exports.DEFAULT_GROWTH) {
124
+ const within = (windowMs) => readings.filter(([at]) => at > now - windowMs - config.slackMs && at <= now);
125
+ const inside = within(config.windowMs);
126
+ if (inside.length === 0)
127
+ return null;
128
+ const coarse = inside.every(([, bytes]) => bytes >= config.coarseFromBytes && bytes % exports.GIB === 0);
129
+ return coarse
130
+ ? grewThroughout(within(config.coarseWindowMs), now, config.coarseMinSpanMs, config.minReadings * 2, config)
131
+ : grewThroughout(inside, now, config.minSpanMs, config.minReadings, config);
132
+ }
133
+ /** At or over the size for the whole two-minute window, not for one sample. */
134
+ function largeThroughout(readings, now, large, config) {
135
+ const inside = readings.filter(([at]) => at > now - config.windowMs - config.slackMs && at <= now);
136
+ return inside.length >= config.minReadings && inside[inside.length - 1][0] === now && now - inside[0][0] >= config.minSpanMs && inside.every(([, bytes]) => bytes >= large);
137
+ }
138
+ /** Size at which a process under a session is listed for its size alone. Only while the machine is short of memory. */
139
+ function largeFloor(level, totalRamBytes, config = exports.DEFAULT_GROWTH) {
140
+ if (level !== 'warn' && level !== 'crit')
141
+ return Number.POSITIVE_INFINITY;
142
+ const share = totalRamBytes !== null && Number.isFinite(totalRamBytes) && totalRamBytes > 0 ? totalRamBytes * config.largeShare : 0;
143
+ return Math.max(config.largeMinBytes, share);
144
+ }
145
+ const listed = (state) => Object.values(state.findings).sort((a, b) => b.sizeBytes - a.sizeBytes || a.pid - b.pid);
146
+ function stepGrowth(previous, sample, config = exports.DEFAULT_GROWTH) {
147
+ const at = sample?.at;
148
+ // A cut-short sample or a clock that did not move forward proves nothing: absence in it is not an exit.
149
+ if (!sample || sample.complete !== true || typeof at !== 'number' || !Number.isFinite(at) || !Array.isArray(sample.processes)
150
+ || (previous.lastAt !== null && at <= previous.lastAt)) {
151
+ return { state: previous, findings: listed(previous), fresh: [] };
152
+ }
153
+ const level = sample.level === 'warn' || sample.level === 'crit' || sample.level === 'ok' ? sample.level : 'unknown';
154
+ const ram = typeof sample.totalRamBytes === 'number' ? sample.totalRamBytes : null;
155
+ const rows = [], seenPids = new Set();
156
+ for (const raw of sample.processes) {
157
+ const item = cleanProcess(raw);
158
+ // A pid listed twice makes the table ambiguous for that pid: neither row is used.
159
+ if (!item)
160
+ continue;
161
+ if (seenPids.has(item.pid)) {
162
+ const index = rows.findIndex(row => row.pid === item.pid);
163
+ if (index >= 0)
164
+ rows.splice(index, 1);
165
+ continue;
166
+ }
167
+ seenPids.add(item.pid);
168
+ rows.push(item);
169
+ }
170
+ const sessionPids = underAgentSession(rows);
171
+ const tracks = {}, findings = {}, fresh = [];
172
+ const floor = sizeFloor(level, ram, config), large = largeFloor(level, ram, config);
173
+ const edge = at - Math.max(config.windowMs, config.coarseWindowMs) - config.slackMs;
174
+ const pressuredAt = level === 'warn' || level === 'crit' ? at : previous.pressuredAt ?? null;
175
+ const calmTooLong = pressuredAt === null || at - pressuredAt >= config.holdingAfterMs;
176
+ for (const item of rows) {
177
+ if (item.startedAt === null || (0, classify_1.agentHost)(item.command))
178
+ continue;
179
+ // Identity is the process number and its OS start time. The command line is not: a program may rename itself in place.
180
+ const key = (0, exports.growthKey)(item.pid, item.startedAt);
181
+ const before = Object.prototype.hasOwnProperty.call(previous.tracks, key) ? previous.tracks[key] : undefined;
182
+ const underSession = sessionPids.has(item.pid) || before?.underSession === true;
183
+ if (!underSession)
184
+ continue;
185
+ const readings = before ? before.readings.filter(([time]) => time > edge) : [];
186
+ if (item.footprintBytes !== null)
187
+ readings.push([at, item.footprintBytes]);
188
+ tracks[key] = { pid: item.pid, startedAt: item.startedAt, command: item.command, underSession, readings };
189
+ const measured = item.footprintBytes === null ? null : measureGrowth(readings, at, config);
190
+ const named = before && Object.prototype.hasOwnProperty.call(previous.findings, key) ? previous.findings[key] : undefined;
191
+ if (named) {
192
+ const size = item.footprintBytes ?? named.sizeBytes;
193
+ // It gave the memory back, or an exec replaced the program: no longer a finding. A stop already sent stays on record.
194
+ if (size < named.namedBytes / 2 && named.status !== 'stop_sent')
195
+ continue;
196
+ // Listed for size alone, and the machine has had memory to spare for two minutes: off the list.
197
+ if (named.origin === 'large' && calmTooLong && named.status !== 'stop_sent')
198
+ continue;
199
+ // A process listed for size alone counts as growing on the same terms as any other: only at or over the size floor.
200
+ const grew = measured !== null && (named.origin === 'grew' || size >= floor) ? measured : null;
201
+ const lastGrewAt = grew !== null ? at : named.lastGrewAt;
202
+ const announce = grew !== null && named.origin === 'large';
203
+ const next = {
204
+ ...named, command: item.command, sizeBytes: size, peakBytes: Math.max(named.peakBytes, size), lastGrewAt,
205
+ origin: announce ? 'grew' : named.origin, grewBytes: grew?.grewBytes ?? named.grewBytes, grewOverMs: grew?.overMs ?? named.grewOverMs,
206
+ status: named.status === 'stop_sent' ? 'stop_sent' : lastGrewAt !== null && at - lastGrewAt < config.holdingAfterMs ? 'growing' : 'holding',
207
+ };
208
+ findings[key] = next;
209
+ if (announce && named.status !== 'stop_sent')
210
+ fresh.push(next);
211
+ continue;
212
+ }
213
+ if (item.footprintBytes === null)
214
+ continue;
215
+ if (measured !== null && item.footprintBytes >= floor) {
216
+ const finding = {
217
+ key, pid: item.pid, startedAt: item.startedAt, command: item.command, namedAt: at, origin: 'grew', namedBytes: item.footprintBytes,
218
+ sizeBytes: item.footprintBytes, peakBytes: item.footprintBytes, grewBytes: measured.grewBytes, grewOverMs: measured.overMs, lastGrewAt: at, status: 'growing', stopSentAt: null,
219
+ };
220
+ findings[key] = finding;
221
+ fresh.push(finding);
222
+ }
223
+ else if (largeThroughout(readings, at, large, config)) {
224
+ // Watched for two minutes, large, and the machine is short of memory: listed quietly so the person can see what holds it.
225
+ findings[key] = {
226
+ key, pid: item.pid, startedAt: item.startedAt, command: item.command, namedAt: at, origin: 'large', namedBytes: item.footprintBytes,
227
+ sizeBytes: item.footprintBytes, peakBytes: item.footprintBytes, grewBytes: 0, grewOverMs: 0, lastGrewAt: null, status: 'holding', stopSentAt: null,
228
+ };
229
+ }
230
+ }
231
+ // Bound the state: keep the tracks with the most to say.
232
+ const keys = Object.keys(tracks);
233
+ if (keys.length > config.maxTracks) {
234
+ const size = (key) => { const list = tracks[key].readings; return list.length ? list[list.length - 1][1] : 0; };
235
+ for (const key of keys.sort((a, b) => Number(Boolean(findings[b])) - Number(Boolean(findings[a])) || size(b) - size(a)).slice(config.maxTracks)) {
236
+ if (!findings[key])
237
+ delete tracks[key];
238
+ }
239
+ }
240
+ const state = { version: 1, lastAt: at, pressuredAt, tracks, findings };
241
+ return { state, findings: listed(state), fresh };
242
+ }
243
+ /**
244
+ * The person chose "Stop it" for one named process. Sends SIGTERM at most once
245
+ * per listing, only to the same program that was named, never anything
246
+ * stronger. Any doubt is a refusal. `shown` answers whether a command line is
247
+ * what the person saw when they chose.
248
+ */
249
+ async function stopNamed(state, key, dependencies, shown) {
250
+ const refuse = (reason) => ({ state, outcome: 'refused', reason });
251
+ const finding = Object.prototype.hasOwnProperty.call(state.findings, key) ? state.findings[key] : undefined;
252
+ if (!finding)
253
+ return refuse('That process is no longer listed.');
254
+ if (finding.status === 'stop_sent')
255
+ return refuse('It was already asked to stop. Nothing stronger is sent.');
256
+ // What the person was shown when they chose. If the process has become something else since, they have not chosen that.
257
+ if (shown && !shown(finding.command))
258
+ return refuse('That process changed since the list was shown. Look at the list again.');
259
+ let guarded;
260
+ try {
261
+ guarded = await dependencies.protectedPids();
262
+ }
263
+ catch {
264
+ guarded = null;
265
+ }
266
+ if (!guarded)
267
+ return refuse('This process ancestry could not be verified.');
268
+ if (finding.pid <= 1 || guarded.has(finding.pid))
269
+ return refuse('That process is part of what runs this session.');
270
+ let current;
271
+ try {
272
+ const read = await dependencies.readOne(finding.pid);
273
+ current = read ? cleanProcess(read) : null;
274
+ }
275
+ catch {
276
+ return refuse('The process could not be read again.');
277
+ }
278
+ if (!current)
279
+ return refuse('The process already exited.');
280
+ if (current.pid !== finding.pid || current.startedAt === null || current.startedAt !== finding.startedAt || current.command !== finding.command) {
281
+ return refuse('A different program now has that process number. Nothing was sent.');
282
+ }
283
+ if ((0, classify_1.agentHost)(current.command))
284
+ return refuse('That process is an agent session.');
285
+ // The only signal site. No await sits between the identity check and this call.
286
+ try {
287
+ await dependencies.signal(finding.pid, 'SIGTERM');
288
+ }
289
+ catch {
290
+ return { state, outcome: 'signal_failed', reason: 'The stop request could not be sent. Nothing stronger was tried.' };
291
+ }
292
+ const sent = { ...finding, status: 'stop_sent', stopSentAt: dependencies.now() };
293
+ return { state: { ...state, findings: { ...state.findings, [key]: sent } }, outcome: 'sent', reason: 'Asked it to stop.' };
294
+ }
295
+ /**
296
+ * The one authoritative state for a worker: samples and stop requests go
297
+ * through here, so two taps on the same finding send one signal and a sample
298
+ * that lands while a stop is in flight does not lose its record.
299
+ */
300
+ class GrowthWatch {
301
+ dependencies;
302
+ config;
303
+ current;
304
+ stopping = new Set();
305
+ constructor(dependencies, config = exports.DEFAULT_GROWTH, state = (0, exports.emptyGrowthState)()) {
306
+ this.dependencies = dependencies;
307
+ this.config = config;
308
+ this.current = state;
309
+ }
310
+ get state() { return this.current; }
311
+ step(sample) {
312
+ const result = stepGrowth(this.current, sample, this.config);
313
+ this.current = result.state;
314
+ return result;
315
+ }
316
+ async stop(key, shown) {
317
+ // Claimed before the first await: a second request for the same finding never reaches the signal.
318
+ if (this.stopping.has(key))
319
+ return { outcome: 'refused', reason: 'It is already being asked to stop.' };
320
+ this.stopping.add(key);
321
+ try {
322
+ const result = await stopNamed(this.current, key, this.dependencies, shown);
323
+ if (result.outcome === 'sent') {
324
+ const sent = result.state.findings[key];
325
+ // Samples may have advanced the state meanwhile. A process that already left the list is not put back on it.
326
+ if (Object.prototype.hasOwnProperty.call(this.current.findings, key)) {
327
+ this.current = { ...this.current, findings: { ...this.current.findings, [key]: { ...this.current.findings[key], status: 'stop_sent', stopSentAt: sent.stopSentAt } } };
328
+ }
329
+ }
330
+ return { outcome: result.outcome, reason: result.reason };
331
+ }
332
+ finally {
333
+ this.stopping.delete(key);
334
+ }
335
+ }
336
+ }
337
+ exports.GrowthWatch = GrowthWatch;
@@ -8,7 +8,8 @@ export interface CommandOptions {
8
8
  cwd?: string;
9
9
  timeoutMs?: number;
10
10
  signal?: AbortSignal;
11
- maxBuffer?: number;
11
+ maxBuffer?: number; /** Added to the environment, after the fixed locale. */
12
+ env?: Record<string, string>;
12
13
  }
13
14
  export type CommandRunner = (command: string, args: string[], options?: CommandOptions) => Promise<CommandResult>;
14
15
  export declare const runLocal: CommandRunner;
@@ -20,7 +20,7 @@ const runLocal = (command, args, options = {}) => new Promise(resolve => {
20
20
  }
21
21
  (0, node_child_process_1.execFile)(command, args, { cwd: options.cwd, timeout: options.timeoutMs ?? 1500,
22
22
  signal: options.signal, killSignal: 'SIGTERM', maxBuffer: options.maxBuffer ?? 4 * 1024 * 1024,
23
- encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', GIT_OPTIONAL_LOCKS: '0' } }, (error, stdout, stderr) => {
23
+ encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', GIT_OPTIONAL_LOCKS: '0', ...options.env } }, (error, stdout, stderr) => {
24
24
  resolve({ stdout, stderr: stderr || (error && typeof error.code !== 'number' ? error.message : ''), code: error ? typeof error.code === 'number' ? error.code : -1 : 0 });
25
25
  });
26
26
  });
@@ -34,6 +34,9 @@ export { formatStatusFields, parseStatusFields, statusPace, statusColor, type St
34
34
  export { readStatusBurn, readStatusMetrics } from './insights/status-data';
35
35
  export { readStatusMachine, swapIsHeavy, type MachineSources } from './insights/status-machine';
36
36
  export { readMemory, memoryLevel, type MemoryReading } from './idle/memory';
37
+ export { stepGrowth, stopNamed, emptyGrowthState, sizeFloor, DEFAULT_GROWTH, GrowthWatch, type GrowthState, type GrowthSample, type GrowthFinding, type GrowthProcess, type StopDependencies, type StopResult } from './idle/growth';
38
+ export { GrowthRunner, darwinSource, linuxSource, type GrowthSource, type GrowthView, type GrowthRunnerOptions } from './idle/growth-runner';
39
+ export { TopFootprintStream, growthSample, parseProcStatusFootprint, TOP_FOOTPRINT_ARGS, type FootprintSample } from './idle/growth-sample';
37
40
  export { collectWeek, saveWeek, weekFigures, weekStartOf, lastCompletedWeekStart, isMonday, WEEK_SCHEMA, SMALLER_MODEL, type WeekFigures, type WeekReport, type WeekAmount, type WeekCause, type WeekTopCause, type BurnWeekFile, type CollectWeekOptions, type SaveWeekResult } from './insights/week';
38
41
  export { renderWeek } from './insights/week-render';
39
42
  export { modelsReport, renderModels, modelGroups, subagentsUnfinished, sessionBytes, MODELS_DEFAULT_DAYS, MODELS_MAX_DAYS, MODELS_DEFAULT_LIMIT, MODELS_MAX_LIMIT, MODELS_DEFAULT_MAX_SESSION_BYTES, MODELS_MAX_SESSION_MEGABYTES, type ModelsReport, type ModelsGroup, type ModelsSession, type ModelsSessionInput, type ModelsSkipped, type ModelsSkippedSession, type ModelsOptions } from './insights/models';
package/dist/src/index.js CHANGED
@@ -16,7 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
18
  exports.parseStatusFields = exports.formatStatusFields = exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
19
- exports.MODELS_MAX_SESSION_MEGABYTES = exports.MODELS_DEFAULT_MAX_SESSION_BYTES = exports.MODELS_MAX_LIMIT = exports.MODELS_DEFAULT_LIMIT = exports.MODELS_MAX_DAYS = exports.MODELS_DEFAULT_DAYS = exports.sessionBytes = exports.subagentsUnfinished = exports.modelGroups = exports.renderModels = exports.modelsReport = exports.renderWeek = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = exports.isMonday = exports.lastCompletedWeekStart = exports.weekStartOf = exports.weekFigures = exports.saveWeek = exports.collectWeek = exports.memoryLevel = exports.readMemory = exports.swapIsHeavy = exports.readStatusMachine = exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
19
+ exports.MODELS_MAX_SESSION_MEGABYTES = exports.MODELS_DEFAULT_MAX_SESSION_BYTES = exports.MODELS_MAX_LIMIT = exports.MODELS_DEFAULT_LIMIT = exports.MODELS_MAX_DAYS = exports.MODELS_DEFAULT_DAYS = exports.sessionBytes = exports.subagentsUnfinished = exports.modelGroups = exports.renderModels = exports.modelsReport = exports.renderWeek = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = exports.isMonday = exports.lastCompletedWeekStart = exports.weekStartOf = exports.weekFigures = exports.saveWeek = exports.collectWeek = exports.TOP_FOOTPRINT_ARGS = exports.parseProcStatusFootprint = exports.growthSample = exports.TopFootprintStream = exports.linuxSource = exports.darwinSource = exports.GrowthRunner = exports.GrowthWatch = exports.DEFAULT_GROWTH = exports.sizeFloor = exports.emptyGrowthState = exports.stopNamed = exports.stepGrowth = exports.memoryLevel = exports.readMemory = exports.swapIsHeavy = exports.readStatusMachine = exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
20
20
  __exportStar(require("./types"), exports);
21
21
  var defaults_1 = require("./defaults");
22
22
  Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
@@ -165,6 +165,22 @@ Object.defineProperty(exports, "swapIsHeavy", { enumerable: true, get: function
165
165
  var memory_1 = require("./idle/memory");
166
166
  Object.defineProperty(exports, "readMemory", { enumerable: true, get: function () { return memory_1.readMemory; } });
167
167
  Object.defineProperty(exports, "memoryLevel", { enumerable: true, get: function () { return memory_1.memoryLevel; } });
168
+ var growth_1 = require("./idle/growth");
169
+ Object.defineProperty(exports, "stepGrowth", { enumerable: true, get: function () { return growth_1.stepGrowth; } });
170
+ Object.defineProperty(exports, "stopNamed", { enumerable: true, get: function () { return growth_1.stopNamed; } });
171
+ Object.defineProperty(exports, "emptyGrowthState", { enumerable: true, get: function () { return growth_1.emptyGrowthState; } });
172
+ Object.defineProperty(exports, "sizeFloor", { enumerable: true, get: function () { return growth_1.sizeFloor; } });
173
+ Object.defineProperty(exports, "DEFAULT_GROWTH", { enumerable: true, get: function () { return growth_1.DEFAULT_GROWTH; } });
174
+ Object.defineProperty(exports, "GrowthWatch", { enumerable: true, get: function () { return growth_1.GrowthWatch; } });
175
+ var growth_runner_1 = require("./idle/growth-runner");
176
+ Object.defineProperty(exports, "GrowthRunner", { enumerable: true, get: function () { return growth_runner_1.GrowthRunner; } });
177
+ Object.defineProperty(exports, "darwinSource", { enumerable: true, get: function () { return growth_runner_1.darwinSource; } });
178
+ Object.defineProperty(exports, "linuxSource", { enumerable: true, get: function () { return growth_runner_1.linuxSource; } });
179
+ var growth_sample_1 = require("./idle/growth-sample");
180
+ Object.defineProperty(exports, "TopFootprintStream", { enumerable: true, get: function () { return growth_sample_1.TopFootprintStream; } });
181
+ Object.defineProperty(exports, "growthSample", { enumerable: true, get: function () { return growth_sample_1.growthSample; } });
182
+ Object.defineProperty(exports, "parseProcStatusFootprint", { enumerable: true, get: function () { return growth_sample_1.parseProcStatusFootprint; } });
183
+ Object.defineProperty(exports, "TOP_FOOTPRINT_ARGS", { enumerable: true, get: function () { return growth_sample_1.TOP_FOOTPRINT_ARGS; } });
168
184
  var week_1 = require("./insights/week");
169
185
  Object.defineProperty(exports, "collectWeek", { enumerable: true, get: function () { return week_1.collectWeek; } });
170
186
  Object.defineProperty(exports, "saveWeek", { enumerable: true, get: function () { return week_1.saveWeek; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.7.3",
3
+ "version": "0.7.4",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://agentguard.run/burn",