@agentguard-run/burn 0.6.0 → 0.6.2
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 +10 -1
- package/README.md +17 -0
- package/dist/src/cli.js +2 -1
- package/dist/src/frames.js +8 -0
- package/dist/src/hook/pre-tool-use.d.ts +8 -1
- package/dist/src/hook/pre-tool-use.js +7 -3
- package/dist/src/idle/collect.d.ts +8 -0
- package/dist/src/idle/collect.js +124 -4
- package/dist/src/idle/disk.d.ts +40 -0
- package/dist/src/idle/disk.js +152 -0
- package/dist/src/idle/platform.d.ts +5 -0
- package/dist/src/idle/platform.js +14 -0
- package/dist/src/idle/render.js +22 -1
- package/dist/src/idle/types.d.ts +30 -0
- package/dist/src/insights/status-fields.d.ts +5 -0
- package/dist/src/insights/status-fields.js +18 -1
- package/dist/src/insights/status-text.d.ts +18 -0
- package/dist/src/insights/status-text.js +6 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.6.2 (2026-10-22)
|
|
4
4
|
|
|
5
|
+
- `ps` opens with free disk on the volume holding your home folder and swap use. [WARN] under 10 GB or 10% free, [CRIT] under 5 GB, swap [WARN] above 80% used. Unknown readings say unknown. `ps --json` adds `disk` (`freeBytes`, `totalBytes`, `level`, `swapUsedBytes`, `swapTotalBytes`, `swapLevel`).
|
|
6
|
+
- `ps` adds an AGENT DATA section, information only: the size and file count of `~/.claude/projects` and Codex's sessions folders and history files, the five largest files ([WARN] over 1 GB), and sessions with more than 500 subagent transcripts. Sizes come from file metadata; transcript content is never opened. The scan has its own time and entry allowance and runs alongside the process scan; a stopped scan prints its totals as "at least". `ps --json` adds `agentData`.
|
|
7
|
+
- `ps` lists the linked git worktrees of the repositories behind live sessions as workspace rows, with size, dirty state and open handles. They are measured last and only while at least 30% of the audit's time is left. Information only, never deleted.
|
|
8
|
+
- The Claude Code PreToolUse hook warns once per session when the home volume has under 5 GB free: "AgentGuard WARN: 3.2 GB free on the disk holding /Users/you. Under 5 GB, builds, installs and agent logs start failing. Run agentguard-burn ps to see what agents are holding." It reads free space at most once a minute from a small file in the Burn home, stores session ids as digests, warns again after space recovers and drops, and never denies or asks.
|
|
9
|
+
|
|
10
|
+
## 0.6.1 (2026-10-18)
|
|
11
|
+
|
|
12
|
+
- `formatStatusFields` takes an optional `context` (`{tokens, threshold}`) and adds "28% to auto-compact" after the token figure (yellow at 30% of context left, red at 10%; the colour follows the number shown), plus the panel line "Context: 720,000 of 1,000,000 tokens, 28% left before Claude Code compacts the conversation.", in English, Spanish and Portuguese. Hidden without a threshold. The AgentGuard plugin's band supplies the figures; `statusline` has no compaction point to read and is unchanged.
|
|
13
|
+
- Past the session token limit the shared status text says "tokens 24B, past the 5B limit" (with "sub-agents wait for your yes" outside shadow mode) instead of the impossible "24B of 5B". The short forms for narrow widths say "past 5B".
|
|
5
14
|
## 0.6.0 (2026-10-10)
|
|
6
15
|
|
|
7
16
|
A simple view by default and a compaction replay, so the first screen answers "how much is left and what do I change".
|
package/README.md
CHANGED
|
@@ -176,6 +176,23 @@ agentguard-burn reap
|
|
|
176
176
|
|
|
177
177
|
Session idle time uses the controlling terminal's access time when readable, otherwise transcript file-write metadata. The table labels the method. A transcript fallback can warn but cannot prove that a terminal has been inactive for 24 hours. Workspace rows show size, last modification, dirty status and open-handle evidence. No transcript content or process arguments are printed or uploaded. Swap is reported only: swap is only released by the operating system on reboot. Burn does not touch it.
|
|
178
178
|
|
|
179
|
+
The audit opens with free disk on the volume holding your home folder and swap use:
|
|
180
|
+
|
|
181
|
+
```text
|
|
182
|
+
[WARN] Disk: 13.8 GB free of 994.7 GB (1.4%) on the volume holding /Users/you.
|
|
183
|
+
Under 10 GB or 10% free, the next large build or agent log can fill it.
|
|
184
|
+
[WARN] Swap: 14.1 GB of 15.0 GB in use (94.1%).
|
|
185
|
+
Over 80% used, memory is short and the machine slows down.
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Disk is [WARN] under 10 GB or 10% free and [CRIT] under 5 GB. An AGENT DATA section then shows how much `~/.claude/projects` and Codex's sessions folders and history files hold, the five largest files (marked [WARN] over 1 GB, which usually means a runaway loop or very large tool output), and any session with more than 500 subagent transcripts. Sizes and counts come from file metadata only. Linked git worktrees of the repositories behind live sessions appear as workspace rows. Like every workspace row, all of this is information only and never deleted.
|
|
189
|
+
|
|
190
|
+
The Claude Code PreToolUse hook adds one line per session when the home volume drops under 5 GB free. It reads free space at most once a minute and never denies or asks:
|
|
191
|
+
|
|
192
|
+
```text
|
|
193
|
+
AgentGuard WARN: 3.2 GB free on the disk holding /Users/you. Under 5 GB, builds, installs and agent logs start failing. Run agentguard-burn ps to see what agents are holding.
|
|
194
|
+
```
|
|
195
|
+
|
|
179
196
|
`reap` prints the same numbered audit, then requires an interactive terminal and numbers typed at the prompt. There is no `--yes` flag and piped confirmation is refused. It sends only SIGTERM to the selected eligible processes, waits, and reports whether they exited. It never sends SIGKILL and never deletes files or directories.
|
|
180
197
|
|
|
181
198
|
Reap refuses:
|
package/dist/src/cli.js
CHANGED
|
@@ -89,6 +89,7 @@ const i18n_1 = require("./insights/i18n");
|
|
|
89
89
|
const ttl_1 = require("./insights/ttl");
|
|
90
90
|
const blocks_1 = require("./insights/blocks");
|
|
91
91
|
const cli_1 = require("./idle/cli");
|
|
92
|
+
const disk_1 = require("./idle/disk");
|
|
92
93
|
const telemetry_cli_1 = require("./telemetry-cli");
|
|
93
94
|
const status_fields_1 = require("./insights/status-fields");
|
|
94
95
|
const status_data_1 = require("./insights/status-data");
|
|
@@ -654,7 +655,7 @@ async function main(argv) {
|
|
|
654
655
|
process.stdout.write(JSON.stringify(warning ? { continue: true, suppressOutput: false, systemMessage: warning } : { continue: true, suppressOutput: true }));
|
|
655
656
|
return 0;
|
|
656
657
|
}
|
|
657
|
-
process.stdout.write(JSON.stringify((0, pre_tool_use_1.handlePreToolUse)(input, HOME)));
|
|
658
|
+
process.stdout.write(JSON.stringify((0, pre_tool_use_1.handlePreToolUse)(input, HOME, Date.now(), { volumeProbe: disk_1.statfsProbe })));
|
|
658
659
|
return 0;
|
|
659
660
|
}
|
|
660
661
|
case 'replay': {
|
package/dist/src/frames.js
CHANGED
|
@@ -61,6 +61,14 @@ function renderFrame(data, options = {}) {
|
|
|
61
61
|
const report = data.report, slots = Math.max(1, Math.floor((h - 18) / 2));
|
|
62
62
|
canvas.put(2, 0, `${data.command.toUpperCase()} · LOCAL COST EXPOSURE · ${report.platform}`, 'mint');
|
|
63
63
|
canvas.put(3, 0, `Observed ${report.generatedAt} · memory first, then workspace disk`, 'slate');
|
|
64
|
+
const disk = report.disk;
|
|
65
|
+
if (disk) {
|
|
66
|
+
const free = disk.freeBytes === null ? 'Disk free ?' : `Disk free ${memory(disk.freeBytes)}${disk.level === 'crit' ? ' CRIT' : disk.level === 'warn' ? ' WARN' : ''}`;
|
|
67
|
+
const swap = disk.swapUsedBytes === null || disk.swapTotalBytes === null ? 'swap ?' : `swap ${memory(disk.swapUsedBytes)} of ${memory(disk.swapTotalBytes)}${disk.swapLevel === 'warn' ? ' WARN' : ''}`;
|
|
68
|
+
const files = report.agentData?.roots.filter(root => root.present) ?? [];
|
|
69
|
+
const data = files.length ? ` · agent data ${memory(files.reduce((sum, root) => sum + root.totalBytes, 0))}${report.agentData?.warn ? ' WARN' : ''}` : '';
|
|
70
|
+
canvas.put(4, 0, `${free} · ${swap}${data}`, disk.level === 'crit' ? 'red' : disk.level === 'warn' || disk.swapLevel === 'warn' || report.agentData?.warn ? 'amber' : 'slate');
|
|
71
|
+
}
|
|
64
72
|
const wide = w >= 100;
|
|
65
73
|
canvas.put(5, 0, wide ? '# HOST PID MEMORY UPTIME IDLE METHOD WIN WORKING DIRECTORY' : '# HOST PID MEMORY IDLE METHOD WIN', 'slate');
|
|
66
74
|
report.rows.slice(page * slots, (page + 1) * slots).forEach((row, i) => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type PersistedReaderCursor, type ReaderCursor } from '../history/claude-transcript';
|
|
2
2
|
import type { BurnReport, Policy, SessionState } from '../types';
|
|
3
|
+
import { type VolumeProbe } from '../idle/disk';
|
|
3
4
|
export interface HookInput {
|
|
4
5
|
hook_event_name?: string;
|
|
5
6
|
session_id?: string;
|
|
@@ -51,7 +52,13 @@ export declare function refreshSession(home: string, sessionId: string, transcri
|
|
|
51
52
|
newSpawns: number;
|
|
52
53
|
notified: string;
|
|
53
54
|
};
|
|
54
|
-
export
|
|
55
|
+
export interface PreToolUseOptions {
|
|
56
|
+
/** The CLI passes statfs. Without a probe the disk advisory is off, so library callers and tests never read a real volume. */
|
|
57
|
+
volumeProbe?: VolumeProbe;
|
|
58
|
+
/** The directory whose volume is measured; the home folder by default. */
|
|
59
|
+
volume?: string;
|
|
60
|
+
}
|
|
61
|
+
export declare function handlePreToolUse(input: HookInput, home: string, now?: number, options?: PreToolUseOptions): HookOutput;
|
|
55
62
|
/**
|
|
56
63
|
* Claude Code turns a hook's "ask" into a real permission prompt in these
|
|
57
64
|
* modes, and since v2.1.211 auto mode's classifier cannot approve it
|
|
@@ -43,6 +43,7 @@ const stop_text_1 = require("../stop-text");
|
|
|
43
43
|
const node_os_1 = require("node:os");
|
|
44
44
|
const live_1 = require("../insights/live");
|
|
45
45
|
const hook_1 = require("../idle/hook");
|
|
46
|
+
const disk_1 = require("../idle/disk");
|
|
46
47
|
const subagent_cost_1 = require("../subagent-cost");
|
|
47
48
|
const SPAWN_TOOLS = tool_names_1.LAUNCH_TOOLS;
|
|
48
49
|
function sessionFile(home, sessionId) {
|
|
@@ -155,7 +156,7 @@ function rememberNotified(home, sessionId, signature) {
|
|
|
155
156
|
/* best effort; the worst case is one repeated banner */
|
|
156
157
|
}
|
|
157
158
|
}
|
|
158
|
-
function handlePreToolUse(input, home, now = Date.now()) {
|
|
159
|
+
function handlePreToolUse(input, home, now = Date.now(), options = {}) {
|
|
159
160
|
if (input.hook_event_name === 'SessionStart') {
|
|
160
161
|
const warning = (0, hook_1.sessionStartWarning)(home, (0, policy_1.loadPolicy)(home), now);
|
|
161
162
|
return warning ? { continue: true, suppressOutput: false, systemMessage: warning } : { continue: true, suppressOutput: true };
|
|
@@ -171,9 +172,12 @@ function handlePreToolUse(input, home, now = Date.now()) {
|
|
|
171
172
|
}
|
|
172
173
|
const observation = (0, live_1.observeTool)(home, input, 'claude', (0, policy_1.loadPolicy)(home), now);
|
|
173
174
|
const output = handleSpawnPreToolUse(input, home, now);
|
|
174
|
-
|
|
175
|
+
// Advisory only: a full disk never changes the permission decision.
|
|
176
|
+
const disk = options.volumeProbe ? (0, disk_1.diskHookWarning)(home, input.session_id, now, options.volumeProbe, options.volume ?? (0, node_os_1.homedir)()) : null;
|
|
177
|
+
const messages = disk ? [...observation.messages, disk] : observation.messages;
|
|
178
|
+
if (!messages.length)
|
|
175
179
|
return output;
|
|
176
|
-
return { ...output, suppressOutput: false, systemMessage: [output.systemMessage, ...
|
|
180
|
+
return { ...output, suppressOutput: false, systemMessage: [output.systemMessage, ...messages].filter(Boolean).join('\n') };
|
|
177
181
|
}
|
|
178
182
|
function handleSpawnPreToolUse(input, home, now) {
|
|
179
183
|
const toolName = input.tool_name ?? '';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Stats } from 'node:fs';
|
|
2
2
|
import { type CommandRunner } from './platform';
|
|
3
|
+
import { type VolumeProbe } from './disk';
|
|
3
4
|
import { type AuditReport, type AuditThresholds } from './types';
|
|
4
5
|
export type { CommandRunner } from './platform';
|
|
5
6
|
export interface MetadataAccess {
|
|
@@ -18,7 +19,14 @@ export interface CollectAuditOptions {
|
|
|
18
19
|
workspaceRoots?: string[];
|
|
19
20
|
claudeProjectsRoot?: string;
|
|
20
21
|
codexSessionsRoot?: string;
|
|
22
|
+
/** Codex home for the agent-data totals: its sessions folders and top-level history files. */
|
|
23
|
+
codexHome?: string;
|
|
21
24
|
procRoot?: string;
|
|
25
|
+
volumeProbe?: VolumeProbe;
|
|
26
|
+
/** Linked git worktrees of the repositories behind live sessions join the workspace rows. */
|
|
27
|
+
sessionWorktrees?: boolean;
|
|
28
|
+
maxAgentDataEntries?: number;
|
|
29
|
+
agentDataBudgetMs?: number;
|
|
22
30
|
runner?: CommandRunner;
|
|
23
31
|
metadata?: MetadataAccess;
|
|
24
32
|
maxProcesses?: number;
|
package/dist/src/idle/collect.js
CHANGED
|
@@ -8,6 +8,7 @@ const node_os_1 = require("node:os");
|
|
|
8
8
|
const node_path_1 = require("node:path");
|
|
9
9
|
const classify_1 = require("./classify");
|
|
10
10
|
const platform_1 = require("./platform");
|
|
11
|
+
const disk_1 = require("./disk");
|
|
11
12
|
const types_1 = require("./types");
|
|
12
13
|
const localMetadata = {
|
|
13
14
|
lstat: path => node_fs_1.promises.lstat(path), readdir: path => node_fs_1.promises.readdir(path), realpath: path => node_fs_1.promises.realpath(path),
|
|
@@ -186,6 +187,8 @@ async function collectAudit(options = {}) {
|
|
|
186
187
|
}
|
|
187
188
|
return { size, newest: modified };
|
|
188
189
|
}
|
|
190
|
+
// Metadata-only and independent of the process table, so it runs while ps, lsof and git do.
|
|
191
|
+
const agentDataPending = collectAgentData();
|
|
189
192
|
const ps = await run('ps', ['-axo', 'pid=,ppid=,rss=,tty=,lstart=,etime=,command='], { maxBuffer: 8 * 1024 * 1024 });
|
|
190
193
|
let processes = ps.code === 0 ? (0, platform_1.parsePs)(ps.stdout) : [];
|
|
191
194
|
if (!processes.length && platform === 'linux' && alive())
|
|
@@ -284,20 +287,98 @@ async function collectAudit(options = {}) {
|
|
|
284
287
|
return false;
|
|
285
288
|
return null;
|
|
286
289
|
}
|
|
287
|
-
let swapUsedBytes = null;
|
|
290
|
+
let swapUsedBytes = null, swapText = null;
|
|
288
291
|
if (alive() && platform === 'darwin') {
|
|
289
292
|
const result = await run('sysctl', ['vm.swapusage']);
|
|
290
293
|
if (result.code === 0)
|
|
291
|
-
|
|
294
|
+
swapText = result.stdout;
|
|
292
295
|
}
|
|
293
296
|
else if (alive() && platform === 'linux') {
|
|
294
297
|
try {
|
|
295
|
-
|
|
298
|
+
swapText = await metadata.readPrefix((0, node_path_1.join)(options.procRoot || '/proc', 'meminfo'), 16384);
|
|
296
299
|
}
|
|
297
300
|
catch { /* Explicit unknown below. */ }
|
|
298
301
|
}
|
|
302
|
+
if (swapText !== null)
|
|
303
|
+
swapUsedBytes = (0, platform_1.parseSwap)(swapText, platform);
|
|
299
304
|
if (swapUsedBytes === null)
|
|
300
305
|
skipped.push('Swap usage is unavailable.');
|
|
306
|
+
const disk = (0, disk_1.diskPressure)(home, alive() ? (options.volumeProbe || disk_1.statfsProbe)(home) : null, swapText === null ? null : (0, platform_1.parseSwapUsage)(swapText, platform));
|
|
307
|
+
if (disk.freeBytes === null)
|
|
308
|
+
skipped.push('Free disk space is unavailable.');
|
|
309
|
+
/** Sizes and counts from directory metadata. A file is never opened. */
|
|
310
|
+
async function collectAgentData() {
|
|
311
|
+
const largest = [], subagents = new Map();
|
|
312
|
+
const deadline = performance.now() + (options.agentDataBudgetMs ?? 5000), cap = options.maxAgentDataEntries ?? 200_000;
|
|
313
|
+
let seen = 0;
|
|
314
|
+
const within = () => alive() && performance.now() < deadline && seen < cap;
|
|
315
|
+
async function walk(root, path, depth, only) {
|
|
316
|
+
if (!within()) {
|
|
317
|
+
root.complete = false;
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
let names;
|
|
321
|
+
try {
|
|
322
|
+
names = (await metadata.readdir(path)).sort();
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
root.complete = false;
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
seen += names.length;
|
|
329
|
+
const infos = await Promise.all(names.map(name => stat((0, node_path_1.join)(path, name))));
|
|
330
|
+
for (const [index, name] of names.entries()) {
|
|
331
|
+
if (!within()) {
|
|
332
|
+
root.complete = false;
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const location = (0, node_path_1.join)(path, name), info = infos[index];
|
|
336
|
+
if (!info || info.isSymbolicLink())
|
|
337
|
+
continue;
|
|
338
|
+
if (info.isDirectory()) {
|
|
339
|
+
if (only && !only.includes(name))
|
|
340
|
+
continue;
|
|
341
|
+
if (depth >= 8) {
|
|
342
|
+
root.complete = false;
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
await walk(root, location, depth + 1);
|
|
346
|
+
}
|
|
347
|
+
else if (info.isFile()) {
|
|
348
|
+
root.totalBytes += info.size;
|
|
349
|
+
root.files++;
|
|
350
|
+
if (largest.length < 5 || info.size > largest[largest.length - 1].sizeBytes) {
|
|
351
|
+
largest.push({ path: location, sizeBytes: info.size, modifiedAt: new Date(info.mtimeMs).toISOString(), warn: info.size > 1e9 });
|
|
352
|
+
largest.sort((a, b) => b.sizeBytes - a.sizeBytes || a.path.localeCompare(b.path));
|
|
353
|
+
largest.length = Math.min(largest.length, 5);
|
|
354
|
+
}
|
|
355
|
+
if (name.endsWith('.jsonl') && (0, node_path_1.basename)(path) === 'subagents')
|
|
356
|
+
subagents.set((0, node_path_1.dirname)(path), (subagents.get((0, node_path_1.dirname)(path)) || 0) + 1);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
const sources = [
|
|
361
|
+
{ label: 'Claude Code transcripts', path: options.claudeProjectsRoot || (0, node_path_1.join)(home, '.claude', 'projects') },
|
|
362
|
+
{ label: 'Codex sessions and history', path: options.codexHome || (0, node_path_1.join)(home, '.codex'), only: ['sessions', 'archived_sessions'] },
|
|
363
|
+
];
|
|
364
|
+
const roots = [];
|
|
365
|
+
for (const source of sources) {
|
|
366
|
+
const root = { label: source.label, path: source.path, present: false, totalBytes: 0, files: 0, complete: true };
|
|
367
|
+
const info = await stat(source.path);
|
|
368
|
+
if (info?.isDirectory()) {
|
|
369
|
+
root.present = true;
|
|
370
|
+
await walk(root, source.path, 0, source.only);
|
|
371
|
+
}
|
|
372
|
+
else if (info === null && await existence(source.path) === null)
|
|
373
|
+
root.complete = false;
|
|
374
|
+
roots.push(root);
|
|
375
|
+
}
|
|
376
|
+
if (roots.some(root => !root.complete))
|
|
377
|
+
skipped.push('Agent data scan stopped early; its totals are lower bounds.');
|
|
378
|
+
const subagentHeavy = [...subagents].filter(([, count]) => count > 500).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 10)
|
|
379
|
+
.map(([path, count]) => ({ path, subagentFiles: count, warn: true }));
|
|
380
|
+
return { roots, largest, subagentHeavy, warn: largest.some(file => file.warn) || subagentHeavy.length > 0 };
|
|
381
|
+
}
|
|
301
382
|
const workspacePaths = new Set(), roots = options.workspaceRoots || ['/private/tmp', '/tmp', (0, node_path_1.join)(home, '.claude', 'scratchpads')];
|
|
302
383
|
async function findWorkspaces(path, depth = 0) {
|
|
303
384
|
if (!alive())
|
|
@@ -494,7 +575,41 @@ async function collectAudit(options = {}) {
|
|
|
494
575
|
row.reasons.push('Activity is unknown; elapsed process lifetime is not evidence of idleness.');
|
|
495
576
|
rows.push(row);
|
|
496
577
|
}
|
|
578
|
+
const sessionWorktreePaths = new Set(), sessionRepos = new Set();
|
|
579
|
+
if (options.sessionWorktrees !== false)
|
|
580
|
+
for (const row of rows) {
|
|
581
|
+
if (row.kind !== 'session' || !row.cwd || !alive())
|
|
582
|
+
continue;
|
|
583
|
+
const result = await run('git', ['-C', row.cwd, 'worktree', 'list', '--porcelain']);
|
|
584
|
+
if (result.code !== 0)
|
|
585
|
+
continue;
|
|
586
|
+
const [main, ...linked] = (0, platform_1.parseWorktrees)(result.stdout);
|
|
587
|
+
if (!main || sessionRepos.has(main))
|
|
588
|
+
continue;
|
|
589
|
+
sessionRepos.add(main);
|
|
590
|
+
for (const path of linked) {
|
|
591
|
+
if (!alive())
|
|
592
|
+
break;
|
|
593
|
+
if (workspacePaths.size >= (options.maxWorkspaces ?? 1000)) {
|
|
594
|
+
skipped.push('Workspace count limit reached; additional candidates were skipped.');
|
|
595
|
+
break;
|
|
596
|
+
}
|
|
597
|
+
// A prunable registration whose folder is gone holds no disk.
|
|
598
|
+
if (await existence(path) !== true)
|
|
599
|
+
continue;
|
|
600
|
+
const location = await canonical(path);
|
|
601
|
+
workspacePaths.add(location);
|
|
602
|
+
sessionWorktreePaths.add(location);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
let unmeasuredWorktrees = 0;
|
|
497
606
|
for (const workspace of workspacePaths) {
|
|
607
|
+
// Session worktrees come last and only use spare time, so they never cut the evidence above short.
|
|
608
|
+
// The skipped note avoids the words that mark orphan totals as lower bounds; these rows are never orphans.
|
|
609
|
+
if (sessionWorktreePaths.has(workspace) && performance.now() - started > (options.maxDurationMs ?? 30000) * 0.7) {
|
|
610
|
+
unmeasuredWorktrees++;
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
498
613
|
if (!alive()) {
|
|
499
614
|
const row = blankRow('workspace', `workspace:${workspace}`, (0, node_path_1.basename)(workspace));
|
|
500
615
|
row.cwd = workspace;
|
|
@@ -527,17 +642,22 @@ async function collectAudit(options = {}) {
|
|
|
527
642
|
row.openHandles = await openHandles(workspace);
|
|
528
643
|
const registration = await registered(workspace), liveOwner = processes.some(process => process.cwd && (0, classify_1.inside)(process.cwd, workspace));
|
|
529
644
|
row.orphan = registration === false && !liveOwner && row.openHandles === false;
|
|
645
|
+
if (sessionWorktreePaths.has(workspace))
|
|
646
|
+
row.reasons.push('Linked git worktree of a repository behind a live agent session.');
|
|
530
647
|
row.reasons.push(registration === true ? 'Workspace is present in git worktree registrations.' : registration === false ? 'Workspace is absent from git worktree registrations.' : 'Git worktree registration could not be verified.');
|
|
531
648
|
if (row.openHandles === null)
|
|
532
649
|
row.reasons.push('Open handles could not be verified.');
|
|
533
650
|
row.warn = row.orphan && row.idleSeconds !== null && row.idleSeconds >= thresholds.orphan_workspace_warn_days * 86400;
|
|
534
651
|
rows.push(row);
|
|
535
652
|
}
|
|
653
|
+
if (unmeasuredWorktrees)
|
|
654
|
+
skipped.push(`${unmeasuredWorktrees} linked worktrees of live sessions were not measured, to keep the audit inside its time allowance.`);
|
|
655
|
+
const agentData = await agentDataPending;
|
|
536
656
|
if (roots.length && (rows.some(row => row.kind === 'workspace' && (row.sizeBytes === null || row.openHandles === null || row.reasons.some(reason => reason.includes('could not be verified'))))
|
|
537
657
|
|| skipped.some(reason => /limit|budget|canceled|discovery is incomplete/.test(reason)))) {
|
|
538
658
|
skipped.push('Workspace totals are lower bounds over measured, proven orphans; incomplete or inaccessible directories are not counted as zero-sized.');
|
|
539
659
|
}
|
|
540
|
-
return { version: 1, generatedAt: new Date(now).toISOString(), platform, rows, processes, swapUsedBytes, skipped: [...new Set(skipped)], thresholds,
|
|
660
|
+
return { version: 1, generatedAt: new Date(now).toISOString(), platform, rows, processes, swapUsedBytes, disk, agentData, skipped: [...new Set(skipped)], thresholds,
|
|
541
661
|
totals: { idleAgentMemoryBytes: rows.filter(row => row.kind === 'session' && row.warn).reduce((sum, row) => sum + row.rssBytes, 0),
|
|
542
662
|
orphanWorkspaceBytes: rows.filter(row => row.kind === 'workspace' && row.orphan).reduce((sum, row) => sum + (row.sizeBytes || 0), 0) } };
|
|
543
663
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const DISK_WARN_BYTES = 10000000000;
|
|
2
|
+
export declare const DISK_WARN_FRACTION = 0.1;
|
|
3
|
+
export declare const DISK_CRIT_BYTES = 5000000000;
|
|
4
|
+
export declare const SWAP_WARN_FRACTION = 0.8;
|
|
5
|
+
export type PressureLevel = 'ok' | 'warn' | 'crit' | 'unknown';
|
|
6
|
+
export interface VolumeSpace {
|
|
7
|
+
freeBytes: number;
|
|
8
|
+
totalBytes: number;
|
|
9
|
+
}
|
|
10
|
+
/** Returns null when the volume cannot be read. Unknown is never reported as free. */
|
|
11
|
+
export type VolumeProbe = (path: string) => VolumeSpace | null;
|
|
12
|
+
export interface DiskPressure {
|
|
13
|
+
/** The directory whose volume was measured, normally the home folder. */
|
|
14
|
+
path: string;
|
|
15
|
+
freeBytes: number | null;
|
|
16
|
+
totalBytes: number | null;
|
|
17
|
+
level: PressureLevel;
|
|
18
|
+
swapUsedBytes: number | null;
|
|
19
|
+
swapTotalBytes: number | null;
|
|
20
|
+
swapLevel: PressureLevel;
|
|
21
|
+
}
|
|
22
|
+
export declare const statfsProbe: VolumeProbe;
|
|
23
|
+
export declare function diskLevel(space: VolumeSpace | null): PressureLevel;
|
|
24
|
+
export declare function swapLevel(used: number | null, total: number | null): PressureLevel;
|
|
25
|
+
export declare function diskPressure(path: string, space: VolumeSpace | null, swap: {
|
|
26
|
+
usedBytes: number;
|
|
27
|
+
totalBytes: number;
|
|
28
|
+
} | null): DiskPressure;
|
|
29
|
+
/** A status line, then advice only when a threshold is crossed. */
|
|
30
|
+
export declare function diskLines(disk: DiskPressure | null | undefined): string[];
|
|
31
|
+
export declare function swapLines(disk: DiskPressure | null | undefined): string[];
|
|
32
|
+
export declare const DISK_CHECK_TTL_MS = 60000;
|
|
33
|
+
export declare const diskCheckPath: (home: string) => string;
|
|
34
|
+
/**
|
|
35
|
+
* The hook's disk advisory. One statfs at most every 60 seconds, read from a
|
|
36
|
+
* small cache file in the Burn home. Under 5 GB free, each session hears it
|
|
37
|
+
* once; the list resets when space recovers, so a second drop warns again.
|
|
38
|
+
* Session ids are stored as short digests, never raw. Never denies.
|
|
39
|
+
*/
|
|
40
|
+
export declare function diskHookWarning(home: string, sessionId: string | undefined, now: number, probe: VolumeProbe, volume: string): string | null;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.diskCheckPath = exports.DISK_CHECK_TTL_MS = exports.statfsProbe = exports.SWAP_WARN_FRACTION = exports.DISK_CRIT_BYTES = exports.DISK_WARN_FRACTION = exports.DISK_WARN_BYTES = void 0;
|
|
4
|
+
exports.diskLevel = diskLevel;
|
|
5
|
+
exports.swapLevel = swapLevel;
|
|
6
|
+
exports.diskPressure = diskPressure;
|
|
7
|
+
exports.diskLines = diskLines;
|
|
8
|
+
exports.swapLines = swapLines;
|
|
9
|
+
exports.diskHookWarning = diskHookWarning;
|
|
10
|
+
/**
|
|
11
|
+
* Free disk and swap pressure.
|
|
12
|
+
*
|
|
13
|
+
* Agent sessions write transcripts, worktrees and build caches until the disk
|
|
14
|
+
* fills, and a full disk then fills swap. Both are local metadata reads: one
|
|
15
|
+
* statfs call and the swap figures `ps` already collects. Nothing is deleted
|
|
16
|
+
* or sent.
|
|
17
|
+
*
|
|
18
|
+
* WARN-only by design, the same reasoning as the local-compute detector: we
|
|
19
|
+
* cannot know what the person needs the space for, so a disk STOP would be a
|
|
20
|
+
* guess, and a guessed STOP is what gets a safety tool uninstalled.
|
|
21
|
+
*/
|
|
22
|
+
const node_crypto_1 = require("node:crypto");
|
|
23
|
+
const node_fs_1 = require("node:fs");
|
|
24
|
+
const node_path_1 = require("node:path");
|
|
25
|
+
exports.DISK_WARN_BYTES = 10e9;
|
|
26
|
+
exports.DISK_WARN_FRACTION = 0.1;
|
|
27
|
+
exports.DISK_CRIT_BYTES = 5e9;
|
|
28
|
+
exports.SWAP_WARN_FRACTION = 0.8;
|
|
29
|
+
const statfsProbe = path => {
|
|
30
|
+
try {
|
|
31
|
+
const stats = (0, node_fs_1.statfsSync)(path);
|
|
32
|
+
const free = stats.bavail * stats.bsize, total = stats.blocks * stats.bsize;
|
|
33
|
+
return Number.isFinite(free) && Number.isFinite(total) && free >= 0 && total > 0 ? { freeBytes: free, totalBytes: total } : null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
exports.statfsProbe = statfsProbe;
|
|
40
|
+
function diskLevel(space) {
|
|
41
|
+
if (!space)
|
|
42
|
+
return 'unknown';
|
|
43
|
+
if (space.freeBytes < exports.DISK_CRIT_BYTES)
|
|
44
|
+
return 'crit';
|
|
45
|
+
return space.freeBytes < exports.DISK_WARN_BYTES || space.freeBytes < space.totalBytes * exports.DISK_WARN_FRACTION ? 'warn' : 'ok';
|
|
46
|
+
}
|
|
47
|
+
function swapLevel(used, total) {
|
|
48
|
+
if (used === null || total === null)
|
|
49
|
+
return 'unknown';
|
|
50
|
+
// No swap file yet is not pressure; macOS creates swap files on demand.
|
|
51
|
+
return total > 0 && used / total > exports.SWAP_WARN_FRACTION ? 'warn' : 'ok';
|
|
52
|
+
}
|
|
53
|
+
function diskPressure(path, space, swap) {
|
|
54
|
+
return { path, freeBytes: space?.freeBytes ?? null, totalBytes: space?.totalBytes ?? null, level: diskLevel(space),
|
|
55
|
+
swapUsedBytes: swap?.usedBytes ?? null, swapTotalBytes: swap?.totalBytes ?? null, swapLevel: swapLevel(swap?.usedBytes ?? null, swap?.totalBytes ?? null) };
|
|
56
|
+
}
|
|
57
|
+
const size = (bytes) => bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.round(bytes / 1e6)} MB`;
|
|
58
|
+
const percent = (part, whole) => `${(part / whole * 100).toFixed(1)}%`;
|
|
59
|
+
/** A status line, then advice only when a threshold is crossed. */
|
|
60
|
+
function diskLines(disk) {
|
|
61
|
+
if (!disk || disk.freeBytes === null || disk.totalBytes === null)
|
|
62
|
+
return ['Disk: free space is unknown.'];
|
|
63
|
+
const base = `Disk: ${size(disk.freeBytes)} free of ${size(disk.totalBytes)} (${percent(disk.freeBytes, disk.totalBytes)}) on the volume holding ${disk.path}.`;
|
|
64
|
+
if (disk.level === 'crit')
|
|
65
|
+
return [`[CRIT] ${base}`, 'Under 5 GB, builds, installs and agent logs start failing.'];
|
|
66
|
+
if (disk.level === 'warn')
|
|
67
|
+
return [`[WARN] ${base}`, 'Under 10 GB or 10% free, the next large build or agent log can fill it.'];
|
|
68
|
+
return [base];
|
|
69
|
+
}
|
|
70
|
+
function swapLines(disk) {
|
|
71
|
+
if (!disk || disk.swapUsedBytes === null || disk.swapTotalBytes === null)
|
|
72
|
+
return ['Swap: usage is unknown.'];
|
|
73
|
+
if (disk.swapTotalBytes === 0)
|
|
74
|
+
return ['Swap: none in use.'];
|
|
75
|
+
const base = `Swap: ${size(disk.swapUsedBytes)} of ${size(disk.swapTotalBytes)} in use (${percent(disk.swapUsedBytes, disk.swapTotalBytes)}).`;
|
|
76
|
+
return disk.swapLevel === 'warn' ? [`[WARN] ${base}`, 'Over 80% used, memory is short and the machine slows down.'] : [base];
|
|
77
|
+
}
|
|
78
|
+
exports.DISK_CHECK_TTL_MS = 60_000;
|
|
79
|
+
const DISK_CHECK_MAX_BYTES = 64 * 1024, WARNED_SESSIONS_KEPT = 50;
|
|
80
|
+
const diskCheckPath = (home) => (0, node_path_1.join)(home, 'disk-check.json');
|
|
81
|
+
exports.diskCheckPath = diskCheckPath;
|
|
82
|
+
function readDiskCheck(home) {
|
|
83
|
+
try {
|
|
84
|
+
const file = (0, exports.diskCheckPath)(home), stat = (0, node_fs_1.lstatSync)(file);
|
|
85
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > DISK_CHECK_MAX_BYTES)
|
|
86
|
+
return null;
|
|
87
|
+
const value = JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
|
|
88
|
+
return value && value.version === 1 && Number.isFinite(value.checkedAt) && Array.isArray(value.warned)
|
|
89
|
+
&& value.warned.every(item => typeof item === 'string') ? value : null;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function writeDiskCheck(home, check) {
|
|
96
|
+
(0, node_fs_1.mkdirSync)(home, { recursive: true, mode: 0o700 });
|
|
97
|
+
const file = (0, exports.diskCheckPath)(home), temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomUUID)()}`;
|
|
98
|
+
try {
|
|
99
|
+
(0, node_fs_1.writeFileSync)(temporary, JSON.stringify(check) + '\n', { mode: 0o600, flag: 'wx' });
|
|
100
|
+
(0, node_fs_1.renameSync)(temporary, file);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
try {
|
|
104
|
+
(0, node_fs_1.unlinkSync)(temporary);
|
|
105
|
+
}
|
|
106
|
+
catch { }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The hook's disk advisory. One statfs at most every 60 seconds, read from a
|
|
111
|
+
* small cache file in the Burn home. Under 5 GB free, each session hears it
|
|
112
|
+
* once; the list resets when space recovers, so a second drop warns again.
|
|
113
|
+
* Session ids are stored as short digests, never raw. Never denies.
|
|
114
|
+
*/
|
|
115
|
+
function diskHookWarning(home, sessionId, now, probe, volume) {
|
|
116
|
+
try {
|
|
117
|
+
let check = readDiskCheck(home), changed = false;
|
|
118
|
+
if (!check || check.path !== volume || now < check.checkedAt || now - check.checkedAt >= exports.DISK_CHECK_TTL_MS) {
|
|
119
|
+
const space = probe(volume);
|
|
120
|
+
check = { version: 1, checkedAt: now, path: volume, freeBytes: space?.freeBytes ?? null, totalBytes: space?.totalBytes ?? null, warned: check?.warned ?? [] };
|
|
121
|
+
changed = true;
|
|
122
|
+
}
|
|
123
|
+
const space = check.freeBytes !== null && check.totalBytes !== null ? { freeBytes: check.freeBytes, totalBytes: check.totalBytes } : null;
|
|
124
|
+
let warning = null;
|
|
125
|
+
if (diskLevel(space) !== 'crit') {
|
|
126
|
+
if (check.warned.length) {
|
|
127
|
+
check.warned = [];
|
|
128
|
+
changed = true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
const key = (0, node_crypto_1.createHash)('sha256').update(sessionId || 'unknown-session').digest('hex').slice(0, 16);
|
|
133
|
+
if (!check.warned.includes(key)) {
|
|
134
|
+
check.warned = [...check.warned.slice(-(WARNED_SESSIONS_KEPT - 1)), key];
|
|
135
|
+
changed = true;
|
|
136
|
+
warning = `AgentGuard WARN: ${size(space.freeBytes)} free on the disk holding ${volume}. Under 5 GB, builds, installs and agent logs start failing. Run agentguard-burn ps to see what agents are holding.`;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// A disk too full for this small write is the case that most needs the
|
|
140
|
+
// warning, so a failed write still warns. It may then repeat on later calls.
|
|
141
|
+
if (changed) {
|
|
142
|
+
try {
|
|
143
|
+
writeDiskCheck(home, check);
|
|
144
|
+
}
|
|
145
|
+
catch { /* best effort */ }
|
|
146
|
+
}
|
|
147
|
+
return warning;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -18,6 +18,11 @@ export declare function parsePs(text: string): ProcessSnapshot[];
|
|
|
18
18
|
export declare function parseLsofCwds(text: string): Map<number, string>;
|
|
19
19
|
export declare function parseWorktrees(text: string): string[];
|
|
20
20
|
export declare function parseSwap(text: string, platform: string): number | null;
|
|
21
|
+
/** Used and total swap. Either figure missing means the whole reading is unknown. */
|
|
22
|
+
export declare function parseSwapUsage(text: string, platform: string): {
|
|
23
|
+
usedBytes: number;
|
|
24
|
+
totalBytes: number;
|
|
25
|
+
} | null;
|
|
21
26
|
export declare function parseProcStat(text: string, command: string, bootId: string, ticks: number, now: number, uptime: number): ProcessSnapshot | null;
|
|
22
27
|
/** Linux fallback reads proc metadata only. cmdline is process identity, never transcript content. */
|
|
23
28
|
export declare function procProcesses(root: string, runner: CommandRunner, signal: AbortSignal | undefined, limit: number, skipped: string[]): Promise<ProcessSnapshot[]>;
|
|
@@ -6,6 +6,7 @@ exports.parsePs = parsePs;
|
|
|
6
6
|
exports.parseLsofCwds = parseLsofCwds;
|
|
7
7
|
exports.parseWorktrees = parseWorktrees;
|
|
8
8
|
exports.parseSwap = parseSwap;
|
|
9
|
+
exports.parseSwapUsage = parseSwapUsage;
|
|
9
10
|
exports.parseProcStat = parseProcStat;
|
|
10
11
|
exports.procProcesses = procProcesses;
|
|
11
12
|
exports.browserWindows = browserWindows;
|
|
@@ -68,6 +69,19 @@ function parseSwap(text, platform) {
|
|
|
68
69
|
const total = /^SwapTotal:\s+(\d+)\s+kB$/m.exec(text), free = /^SwapFree:\s+(\d+)\s+kB$/m.exec(text);
|
|
69
70
|
return total && free ? Math.max(0, Number(total[1]) - Number(free[1])) * 1024 : null;
|
|
70
71
|
}
|
|
72
|
+
/** Used and total swap. Either figure missing means the whole reading is unknown. */
|
|
73
|
+
function parseSwapUsage(text, platform) {
|
|
74
|
+
if (platform === 'darwin') {
|
|
75
|
+
const bytes = (field) => {
|
|
76
|
+
const match = new RegExp(`${field}\\s*=\\s*([\\d.]+)([KMG])\\b`).exec(text);
|
|
77
|
+
return match ? Math.round(Number(match[1]) * ({ K: 1024, M: 1024 ** 2, G: 1024 ** 3 }[match[2]])) : null;
|
|
78
|
+
};
|
|
79
|
+
const used = bytes('used'), total = bytes('total');
|
|
80
|
+
return used !== null && total !== null ? { usedBytes: used, totalBytes: total } : null;
|
|
81
|
+
}
|
|
82
|
+
const total = /^SwapTotal:\s+(\d+)\s+kB$/m.exec(text), free = /^SwapFree:\s+(\d+)\s+kB$/m.exec(text);
|
|
83
|
+
return total && free ? { usedBytes: Math.max(0, Number(total[1]) - Number(free[1])) * 1024, totalBytes: Number(total[1]) * 1024 } : null;
|
|
84
|
+
}
|
|
71
85
|
function parseProcStat(text, command, bootId, ticks, now, uptime) {
|
|
72
86
|
const match = /^(\d+) \((.*)\) (.*)$/.exec(text.trim());
|
|
73
87
|
if (!match)
|
package/dist/src/idle/render.js
CHANGED
|
@@ -7,6 +7,7 @@ exports.auditForJson = auditForJson;
|
|
|
7
7
|
exports.renderAudit = renderAudit;
|
|
8
8
|
/** Local resource tables use Burn's existing light frame and WARN vocabulary. */
|
|
9
9
|
const frames_1 = require("../frames");
|
|
10
|
+
const disk_1 = require("./disk");
|
|
10
11
|
const plain = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
|
|
11
12
|
const shorten = (value, width) => {
|
|
12
13
|
const chars = Array.from(plain(value));
|
|
@@ -54,7 +55,7 @@ function renderAudit(report, options = {}) {
|
|
|
54
55
|
const line = (value = '') => {
|
|
55
56
|
let content = pad(value, inner);
|
|
56
57
|
if (options.colour)
|
|
57
|
-
content = content.replace(/\[WARN\]/g, '\x1b[33m[WARN]\x1b[0m');
|
|
58
|
+
content = content.replace(/\[WARN\]/g, '\x1b[33m[WARN]\x1b[0m').replace(/\[CRIT\]/g, '\x1b[31m[CRIT]\x1b[0m');
|
|
58
59
|
lines.push(`│ ${content} │`);
|
|
59
60
|
};
|
|
60
61
|
const wrap = (value, prefix = '') => {
|
|
@@ -66,6 +67,8 @@ function renderAudit(report, options = {}) {
|
|
|
66
67
|
border('╭', '─', '╮');
|
|
67
68
|
line('AGENTGUARD BURN | LOCAL COST EXPOSURE');
|
|
68
69
|
line(`Observed ${report.generatedAt} | ${report.platform} | memory first, then workspace disk`);
|
|
70
|
+
(0, disk_1.diskLines)(report.disk).forEach((text, index) => wrap(text, index ? ' ' : ''));
|
|
71
|
+
(0, disk_1.swapLines)(report.disk).forEach((text, index) => wrap(text, index ? ' ' : ''));
|
|
69
72
|
border('├', '─', '┤');
|
|
70
73
|
const pathWidth = inner - 79;
|
|
71
74
|
const columns = (values) => values.map((value, index) => pad(value, [4, 9, 8, pathWidth, 10, 7, 7, 11, 8, 6][index])).join(' ');
|
|
@@ -94,6 +97,24 @@ function renderAudit(report, options = {}) {
|
|
|
94
97
|
});
|
|
95
98
|
if (!report.rows.length)
|
|
96
99
|
line('No agent-owned resources found in the readable scope.');
|
|
100
|
+
if (report.agentData) {
|
|
101
|
+
const data = report.agentData;
|
|
102
|
+
border('├', '─', '┤');
|
|
103
|
+
line('AGENT DATA | transcripts and history, information only, never deleted');
|
|
104
|
+
for (const root of data.roots)
|
|
105
|
+
wrap(!root.present ? `${root.label}: none at ${root.path}`
|
|
106
|
+
: `${root.label}: ${root.complete ? '' : 'at least '}${memory(root.totalBytes)} in ${root.files.toLocaleString('en-US')} files at ${root.path}`);
|
|
107
|
+
if (data.largest.length)
|
|
108
|
+
line('Largest files:');
|
|
109
|
+
for (const file of data.largest)
|
|
110
|
+
wrap(`${file.warn ? '[WARN] ' : ''}${memory(file.sizeBytes)} | modified ${file.modifiedAt} | ${file.path}`, ' ');
|
|
111
|
+
if (data.largest.some(file => file.warn))
|
|
112
|
+
wrap('A single transcript over 1 GB usually means a runaway loop or very large tool output.', ' ');
|
|
113
|
+
if (data.subagentHeavy.length)
|
|
114
|
+
line('Sessions with more than 500 subagent transcripts:');
|
|
115
|
+
for (const directory of data.subagentHeavy)
|
|
116
|
+
wrap(`[WARN] ${directory.subagentFiles.toLocaleString('en-US')} subagent files | ${directory.path}`, ' ');
|
|
117
|
+
}
|
|
97
118
|
border('├', '─', '┤');
|
|
98
119
|
line(`Idle agent held memory: ${memory(report.totals.idleAgentMemoryBytes)}`);
|
|
99
120
|
line(`Orphan workspace disk: ${memory(report.totals.orphanWorkspaceBytes)}`);
|
package/dist/src/idle/types.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Local metadata only. Unknown evidence is explicit and never authorizes reaping. */
|
|
2
|
+
import type { DiskPressure } from './disk';
|
|
2
3
|
export interface AuditThresholds {
|
|
3
4
|
idle_session_warn_hours: number;
|
|
4
5
|
idle_browser_warn_minutes: number;
|
|
@@ -39,6 +40,32 @@ export interface AuditRow {
|
|
|
39
40
|
warn: boolean;
|
|
40
41
|
reasons: string[];
|
|
41
42
|
}
|
|
43
|
+
/** File sizes and counts only. Transcript content is never opened. */
|
|
44
|
+
export interface AgentDataRoot {
|
|
45
|
+
label: string;
|
|
46
|
+
path: string;
|
|
47
|
+
present: boolean;
|
|
48
|
+
totalBytes: number;
|
|
49
|
+
files: number;
|
|
50
|
+
complete: boolean;
|
|
51
|
+
}
|
|
52
|
+
export interface AgentDataFile {
|
|
53
|
+
path: string;
|
|
54
|
+
sizeBytes: number;
|
|
55
|
+
modifiedAt: string;
|
|
56
|
+
warn: boolean;
|
|
57
|
+
}
|
|
58
|
+
export interface SubagentDirectory {
|
|
59
|
+
path: string;
|
|
60
|
+
subagentFiles: number;
|
|
61
|
+
warn: boolean;
|
|
62
|
+
}
|
|
63
|
+
export interface AgentDataReport {
|
|
64
|
+
roots: AgentDataRoot[];
|
|
65
|
+
largest: AgentDataFile[];
|
|
66
|
+
subagentHeavy: SubagentDirectory[];
|
|
67
|
+
warn: boolean;
|
|
68
|
+
}
|
|
42
69
|
export interface AuditReport {
|
|
43
70
|
version: 1;
|
|
44
71
|
generatedAt: string;
|
|
@@ -52,5 +79,8 @@ export interface AuditReport {
|
|
|
52
79
|
orphanWorkspaceBytes: number;
|
|
53
80
|
};
|
|
54
81
|
thresholds: AuditThresholds;
|
|
82
|
+
/** Absent in audits cached by Burn 0.6.1 and earlier. */
|
|
83
|
+
disk?: DiskPressure | null;
|
|
84
|
+
agentData?: AgentDataReport | null;
|
|
55
85
|
}
|
|
56
86
|
export declare const DEFAULT_AUDIT_THRESHOLDS: AuditThresholds;
|
|
@@ -49,6 +49,11 @@ export interface StatusInput extends StatusMetrics {
|
|
|
49
49
|
share?: number | null;
|
|
50
50
|
windows?: UsageWindow[];
|
|
51
51
|
fields?: string;
|
|
52
|
+
/** The live main-conversation context and the token count where Claude Code auto-compacts. */
|
|
53
|
+
context?: {
|
|
54
|
+
tokens: number;
|
|
55
|
+
threshold: number;
|
|
56
|
+
} | null;
|
|
52
57
|
width?: number;
|
|
53
58
|
lang?: keyof typeof STATUS_TEXT;
|
|
54
59
|
now?: number;
|
|
@@ -67,6 +67,9 @@ function formatStatusFields(input) {
|
|
|
67
67
|
const elapsed = (input.now ?? Date.now()) - window.observedAt;
|
|
68
68
|
return elapsed > 60000 ? words.ago.replace('{minutes}', String(Math.floor(elapsed / 60000))) : '';
|
|
69
69
|
};
|
|
70
|
+
const ctx = input.context && Number.isFinite(input.context.tokens) && input.context.tokens >= 0 &&
|
|
71
|
+
Number.isFinite(input.context.threshold) && input.context.threshold > 0 ? input.context : null;
|
|
72
|
+
const left = ctx ? Math.max(0, Math.round(100 - (100 * ctx.tokens) / ctx.threshold)) : null;
|
|
70
73
|
const optional = new Map();
|
|
71
74
|
if (pace !== null)
|
|
72
75
|
optional.set('pace', { text: `${words.limit} ${duration(pace)}`, color: pace < 30 ? 'yellow' : null });
|
|
@@ -92,7 +95,19 @@ function formatStatusFields(input) {
|
|
|
92
95
|
const color = statusColor(win.count, win.limit);
|
|
93
96
|
out.push({ text: ` ${short > 1 ? 'a' : words.agents} ${win.count}${short ? '/' : ` ${words.of} `}${win.limit}`, color, dim: !color });
|
|
94
97
|
const add = (text, extra = {}) => out.push({ text: ` · ${text}`, dim: !extra.color, ...extra });
|
|
95
|
-
|
|
98
|
+
const label = short > 1 ? 't' : words.tokens, limit = statusCount(burn.tokens.limit);
|
|
99
|
+
// A session past its ceiling keeps counting. "24B of 5B" reads as broken, so say what the state is.
|
|
100
|
+
if (burn.tokens.limit > 0 && burn.tokens.used >= burn.tokens.limit) {
|
|
101
|
+
const past = (short ? words.pastShort : words.pastLimit).replace('{limit}', limit);
|
|
102
|
+
add(`${label} ${statusCount(burn.tokens.used)}, ${past}${!short && burn.mode !== 'shadow' ? `: ${words.waits}` : ''}`, { color: 'red' });
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
add(`${label} ${statusCount(burn.tokens.used)}${short ? '/' : ` ${words.of} `}${limit}`, { color: statusColor(burn.tokens.used, burn.tokens.limit) });
|
|
106
|
+
if (ctx && left !== null) {
|
|
107
|
+
// The colour follows the number shown, so "30%" is always yellow and "10%" always red.
|
|
108
|
+
const color = left <= 10 ? 'red' : left <= 30 ? 'yellow' : null;
|
|
109
|
+
add(short > 1 ? `ac ${left}%` : `${left}% ${short ? words.compactShort : words.compact}`, color ? { color } : {});
|
|
110
|
+
}
|
|
96
111
|
if (typeof input.share === 'number' && Number.isFinite(input.share))
|
|
97
112
|
add(`${Math.round(input.share)}% ${short ? words.sub : words.share}`);
|
|
98
113
|
if (plan)
|
|
@@ -123,6 +138,8 @@ function formatStatusFields(input) {
|
|
|
123
138
|
const fullText = output.map(part => part.text).join('');
|
|
124
139
|
const text = [...fullText].slice(0, width).join('');
|
|
125
140
|
const panel = [
|
|
141
|
+
...(ctx && left !== null ? [words.contextLine.replace('{used}', Math.round(ctx.tokens).toLocaleString('en-US'))
|
|
142
|
+
.replace('{threshold}', Math.round(ctx.threshold).toLocaleString('en-US')).replace('{left}', String(left))] : []),
|
|
126
143
|
...plans.map(window => `${words.plan} ${Math.round(window.usedPercent)}% (${planName(window)}). ${words.reset} ${Number.isFinite(window.resetsAt) ? new Date(window.resetsAt).toISOString() : words.none}.${age(window) ? ` ${words.lastRead} ${age(window)}.` : ''}`),
|
|
127
144
|
pace !== null ? `${words.limit} ${duration(pace)}.` : words.paceEmpty,
|
|
128
145
|
input.cost ? `${words.costLead} ≈ ${money(input.cost, words.range)} ${words.costFull}.` : words.costEmpty,
|
|
@@ -10,6 +10,12 @@ export declare const STATUS_TEXT: {
|
|
|
10
10
|
share: string;
|
|
11
11
|
sub: string;
|
|
12
12
|
weekly: string;
|
|
13
|
+
pastLimit: string;
|
|
14
|
+
pastShort: string;
|
|
15
|
+
waits: string;
|
|
16
|
+
compact: string;
|
|
17
|
+
compactShort: string;
|
|
18
|
+
contextLine: string;
|
|
13
19
|
limit: string;
|
|
14
20
|
cache: string;
|
|
15
21
|
spend: string;
|
|
@@ -45,6 +51,12 @@ export declare const STATUS_TEXT: {
|
|
|
45
51
|
share: string;
|
|
46
52
|
sub: string;
|
|
47
53
|
weekly: string;
|
|
54
|
+
pastLimit: string;
|
|
55
|
+
pastShort: string;
|
|
56
|
+
waits: string;
|
|
57
|
+
compact: string;
|
|
58
|
+
compactShort: string;
|
|
59
|
+
contextLine: string;
|
|
48
60
|
limit: string;
|
|
49
61
|
cache: string;
|
|
50
62
|
spend: string;
|
|
@@ -80,6 +92,12 @@ export declare const STATUS_TEXT: {
|
|
|
80
92
|
share: string;
|
|
81
93
|
sub: string;
|
|
82
94
|
weekly: string;
|
|
95
|
+
pastLimit: string;
|
|
96
|
+
pastShort: string;
|
|
97
|
+
waits: string;
|
|
98
|
+
compact: string;
|
|
99
|
+
compactShort: string;
|
|
100
|
+
contextLine: string;
|
|
83
101
|
limit: string;
|
|
84
102
|
cache: string;
|
|
85
103
|
spend: string;
|
|
@@ -4,6 +4,8 @@ exports.STATUS_TEXT = void 0;
|
|
|
4
4
|
// Display-only words shared with the Claude mod. No environment or I/O here.
|
|
5
5
|
exports.STATUS_TEXT = {
|
|
6
6
|
en: { ago: '{minutes}m ago', lastRead: 'Last read', range: 'to', fiveHour: '5-hour', agents: 'sub-agents', tokens: 'tokens', of: 'of', share: 'to sub-agents', sub: 'sub', weekly: 'weekly',
|
|
7
|
+
pastLimit: 'past the {limit} limit', pastShort: 'past {limit}', waits: 'sub-agents wait for your yes', compact: 'to auto-compact', compactShort: 'to compact',
|
|
8
|
+
contextLine: 'Context: {used} of {threshold} tokens, {left}% left before Claude Code compacts the conversation.',
|
|
7
9
|
limit: 'limit in', cache: 'cache waste', spend: 'spend', today: 'today', list: 'list', watching: 'watching only',
|
|
8
10
|
unavailable: 'status unavailable', starting: 'starting', costFull: 'at API list price, not a bill',
|
|
9
11
|
paceEmpty: 'Pace needs two rising plan usage samples and a limit reached before reset.',
|
|
@@ -14,6 +16,8 @@ exports.STATUS_TEXT = {
|
|
|
14
16
|
enabled: 'Optional status fields on:', none: 'none', change: 'Change status_fields in the AgentGuard plugin settings, or pass the fields flag to Burn statusline.',
|
|
15
17
|
unknown: 'Ignored unknown status fields:', reset: 'Resets at', plan: 'Plan usage:', hidden: 'Fields hidden to fit this width:' },
|
|
16
18
|
es: { ago: 'hace {minutes}min', lastRead: 'Última lectura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'a subagentes', sub: 'sub', weekly: 'semanal',
|
|
19
|
+
pastLimit: 'pasó el límite de {limit}', pastShort: 'pasó {limit}', waits: 'los subagentes esperan tu sí', compact: 'para autocompactar', compactShort: 'hasta compactar',
|
|
20
|
+
contextLine: 'Contexto: {used} de {threshold} tokens, queda {left}% antes de que Claude Code compacte la conversación.',
|
|
17
21
|
limit: 'límite en', cache: 'caché reescrita', spend: 'gasto', today: 'hoy', list: 'lista', watching: 'solo observando',
|
|
18
22
|
unavailable: 'estado no disponible', starting: 'iniciando', costFull: 'a precio de lista de la API, no es una factura',
|
|
19
23
|
paceEmpty: 'El ritmo necesita dos muestras crecientes del plan y alcanzar el límite antes del reinicio.',
|
|
@@ -24,6 +28,8 @@ exports.STATUS_TEXT = {
|
|
|
24
28
|
enabled: 'Campos opcionales activos:', none: 'ninguno', change: 'Cambia status_fields en los ajustes del plugin AgentGuard o pasa la opción fields a Burn statusline.',
|
|
25
29
|
unknown: 'Campos de estado desconocidos ignorados:', reset: 'Se reinicia a las', plan: 'Uso del plan:', hidden: 'Campos ocultos para caber en este ancho:' },
|
|
26
30
|
pt: { ago: 'há {minutes}min', lastRead: 'Última leitura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'para subagentes', sub: 'sub', weekly: 'semanal',
|
|
31
|
+
pastLimit: 'passou do limite de {limit}', pastShort: 'passou {limit}', waits: 'subagentes esperam seu sim', compact: 'até autocompactar', compactShort: 'até compactar',
|
|
32
|
+
contextLine: 'Contexto: {used} de {threshold} tokens, resta {left}% antes de o Claude Code compactar a conversa.',
|
|
27
33
|
limit: 'limite em', cache: 'cache regravado', spend: 'gasto', today: 'hoje', list: 'lista', watching: 'só observando',
|
|
28
34
|
unavailable: 'status indisponível', starting: 'iniciando', costFull: 'a preço de lista da API, não é uma fatura',
|
|
29
35
|
paceEmpty: 'O ritmo precisa de duas amostras crescentes do plano e atingir o limite antes da renovação.',
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentguard-run/burn",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
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",
|
|
7
7
|
"bugs": {
|
|
8
|
-
"url": "https://github.com/
|
|
8
|
+
"url": "https://github.com/agentguard-run/agentguard-codex-plugin/issues"
|
|
9
9
|
},
|
|
10
10
|
"type": "commonjs",
|
|
11
11
|
"main": "dist/src/index.js",
|