@agentguard-run/burn 0.7.2 → 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 +19 -0
- package/dist/src/cli.js +2 -1
- package/dist/src/idle/classify.js +13 -1
- package/dist/src/idle/growth-runner.d.ts +85 -0
- package/dist/src/idle/growth-runner.js +228 -0
- package/dist/src/idle/growth-sample.d.ts +48 -0
- package/dist/src/idle/growth-sample.js +101 -0
- package/dist/src/idle/growth.d.ts +157 -0
- package/dist/src/idle/growth.js +337 -0
- package/dist/src/idle/hook.js +7 -0
- package/dist/src/idle/memory.d.ts +38 -0
- package/dist/src/idle/memory.js +225 -0
- package/dist/src/idle/platform.d.ts +2 -1
- package/dist/src/idle/platform.js +1 -1
- package/dist/src/idle/render.js +1 -1
- package/dist/src/index.d.ts +5 -0
- package/dist/src/index.js +23 -1
- package/dist/src/insights/status-fields.d.ts +19 -0
- package/dist/src/insights/status-fields.js +46 -0
- package/dist/src/insights/status-machine.d.ts +21 -0
- package/dist/src/insights/status-machine.js +53 -0
- package/dist/src/insights/status-text.d.ts +30 -0
- package/dist/src/insights/status-text.js +9 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
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
|
+
|
|
13
|
+
## 0.7.3 (2026-12-04)
|
|
14
|
+
|
|
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.
|
|
16
|
+
- Available memory is the operating system's own figure (macOS `kern.memorystatus_level`, Linux `MemAvailable`), never `os.freemem()`, read at most once every five seconds across all open sessions through a small private cache file. A figure that cannot be read shows as `memory ?` or not at all, never as fine. Limits: the macOS figure can sit near 20% while the machine swaps hard, which is why swap and disk sit beside it; the Linux figure is the host's and ignores a container's memory ceiling; Windows shows no memory part.
|
|
17
|
+
- The package exports `readStatusMachine(home)`, `swapIsHeavy`, `readMemory` and `memoryLevel`, so the AgentGuard plugin can draw the same parts where the installed Burn has them (`typeof readStatusMachine === 'function'`).
|
|
18
|
+
- Display only: nothing here denies a launch, signals a process or deletes a file.
|
|
19
|
+
- The SessionStart advisory no longer reads "0 idle agent sessions holding 0.0 GB" when only an idle browser or an orphan workspace is past its threshold; it names what was found.
|
|
20
|
+
- `ps` no longer says swap is released only on reboot: swap shrinks when the processes holding memory stop.
|
|
21
|
+
|
|
3
22
|
## 0.7.2 (2026-11-13)
|
|
4
23
|
|
|
5
24
|
- Add `models [--days N] [--limit N] [--max-mb N] [json] [--lang en|es|pt]`: the top-level Claude Code and Codex sessions that started in the last N days (default 30, up to 365), each under its dominant model, models ordered by first session so the report reads as before, then after a switch. Per model: sessions, first and last session date, and per-session medians and totals of input tokens, output tokens, cache share, sub-agents launched, sub-agents that ended without finishing, and the API list-price equivalent. Every session's figures are the ones `compare` and `why` print for it, child transcripts included. Unpriced stays unpriced. How sub-agents ended is counted only where a sub-agent transcript records it; elsewhere it is unknown, left out of that row and counted, never 0. Measurement only: it never says which model did better.
|
package/dist/src/cli.js
CHANGED
|
@@ -94,6 +94,7 @@ const disk_1 = require("./idle/disk");
|
|
|
94
94
|
const telemetry_cli_1 = require("./telemetry-cli");
|
|
95
95
|
const status_fields_1 = require("./insights/status-fields");
|
|
96
96
|
const status_data_1 = require("./insights/status-data");
|
|
97
|
+
const status_machine_1 = require("./insights/status-machine");
|
|
97
98
|
const display_mode_1 = require("./display-mode");
|
|
98
99
|
const i18n_2 = require("./insights/i18n");
|
|
99
100
|
const simple_data_1 = require("./insights/simple-data");
|
|
@@ -664,7 +665,7 @@ async function main(argv) {
|
|
|
664
665
|
const burn = (0, status_data_1.readStatusBurn)(HOME, session);
|
|
665
666
|
if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(HOME, 'sessions')) && metrics.totalTokens !== undefined)
|
|
666
667
|
burn.tokens.used = metrics.totalTokens;
|
|
667
|
-
const formatted = (0, status_fields_1.formatStatusFields)({ ...metrics, burn, fields, windows: observation.snapshot?.windows,
|
|
668
|
+
const formatted = (0, status_fields_1.formatStatusFields)({ ...metrics, burn, fields, windows: observation.snapshot?.windows, machine: await (0, status_machine_1.readStatusMachine)(HOME),
|
|
668
669
|
width,
|
|
669
670
|
lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) });
|
|
670
671
|
const line = process.env.NO_COLOR !== undefined || noColor || formatted.clipped ? formatted.text : formatted.parts.map(part => {
|
|
@@ -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
|
-
|
|
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
|
+
}
|