@agentguard-run/burn 0.6.1 → 0.7.0

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.
@@ -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
- swapUsedBytes = (0, platform_1.parseSwap)(result.stdout, platform);
294
+ swapText = result.stdout;
292
295
  }
293
296
  else if (alive() && platform === 'linux') {
294
297
  try {
295
- swapUsedBytes = (0, platform_1.parseSwap)(await metadata.readPrefix((0, node_path_1.join)(options.procRoot || '/proc', 'meminfo'), 16384), platform);
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)
@@ -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)}`);
@@ -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;