@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.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,18 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.7.0 (2026-10-28)
4
+
5
+ - Add `install`: one command for every agent host on this computer. It finds Claude Code, Codex, Cursor and Hermes by their command on PATH and their config folder, reading files only, and prints the plan: each host, the exact commands and the files they change. `--yes` carries it out: the AgentGuard plugin through Claude Code's and Codex's own plugin commands (with `npm ci` in Codex's plugin folder, and in Claude Code's only when it left the dependencies out), Burn's hook merged into `~/.cursor/hooks.json`, and `agentguard-spend-hermes` installed with uv into the Python environment Hermes runs from, then enabled. It then reads each host again and prints one line per host (installed, already installed, skipped, or failed with the reason) with the mode AgentGuard runs in and the status command that confirms the effective mode. `--only` and `--skip` choose hosts; `--json` gives an agent the plan and the results. A second run changes nothing. A failed host does not stop the others, and the exit code is 1. It never runs a downloaded script, never uses sudo, never installs a host itself, never asks for a key and never writes `burn-policy.json`, so the plugin's enforce default still applies to a fresh install.
6
+ - `install` updates an installed AgentGuard plugin that is older than what is available (the newer of the host's local marketplace copy and plugin 0.5.0, as that copy can be stale) through the host's own plugin commands: `claude plugin marketplace update agentguard` and `claude plugin update agentguard@agentguard`, or `codex plugin marketplace upgrade agentguard` and `codex plugin add agentguard@agentguard --json`, adding the agentguard-run marketplace first when none is configured. A marketplace still added from MerchantGuard/agentguard-codex-plugin stays in place, since both hosts refuse the new source under the same name and GitHub forwards the old one.
7
+ - Where the plugin is installed and enabled, `install` removes a standalone Burn hook from `~/.codex/hooks.json` or `~/.claude/settings.json` after the plugin steps succeed, with a timestamped backup, taking out only the Burn gate entries and keeping every other byte of the file.
8
+ - The `agentguard-burn` wrapper passes `install` through unchanged. Its `^0.6.1` range does not reach 0.7.0, so `npx agentguard-burn install` needs a wrapper release on `^0.7.0`.
9
+
10
+ ## 0.6.2 (2026-10-22)
11
+
12
+ - `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`).
13
+ - `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`.
14
+ - `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.
15
+ - 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.
4
16
 
5
17
  ## 0.6.1 (2026-10-18)
6
18
 
package/README.md CHANGED
@@ -18,6 +18,32 @@ Press y if npm asks to install Burn. Plain `npx agentguard-burn` shows these thr
18
18
 
19
19
  Burn prints its installed version on the first line of every `why` and `calendar` text report, including the empty message. JSON reports include a `version` field. `npx agentguard-burn --version` (or `-v`) prints only the installed version.
20
20
 
21
+ ## Install AgentGuard on every agent host
22
+
23
+ ```sh
24
+ npx agentguard-burn install # the plan; nothing changes
25
+ npx agentguard-burn install --yes # carry it out
26
+ ```
27
+
28
+ `install` finds Claude Code, Codex, Cursor and Hermes on this computer by their command on PATH and their config folder. It decides by reading files and starts nothing to look. Without `--yes` it prints the plan: each host it found, the exact commands it would run and the files they change. With `--yes` it runs them, reads each host again, and prints one line per host: installed, already installed, skipped, or failed with the reason, with the mode AgentGuard runs in there.
29
+
30
+ | Host | What `--yes` does |
31
+ |---|---|
32
+ | Claude Code | `claude plugin marketplace add agentguard-run/agentguard-codex-plugin` (unless an agentguard marketplace is already added), `claude plugin install agentguard@agentguard`, and `npm ci` in the plugin folder only if the dependencies are missing. An older plugin: `claude plugin marketplace update agentguard`, then `claude plugin update agentguard@agentguard` |
33
+ | Codex | `codex plugin marketplace add agentguard-run/agentguard-codex-plugin` (unless already added), `codex plugin add agentguard@agentguard --json`, then `npm ci` in the plugin folder Codex reports if the dependencies are missing. An older plugin: `codex plugin marketplace upgrade agentguard`, then the same `plugin add` and `npm ci` |
34
+ | Cursor | merges the AgentGuard hook into `~/.cursor/hooks.json` after a timestamped backup: the same entry as `init cursor --write` |
35
+ | Hermes | `uv pip install --python <the Python environment Hermes runs from> agentguard-spend-hermes`, then `hermes plugins enable agentguard-spend` |
36
+
37
+ - `--only claude,codex` or `--skip hermes` chooses hosts (claude, codex, cursor, hermes).
38
+ - `--json` prints the plan, and after `--yes` each host's result, for an agent to read. An agent shows the plan to its person and runs `--yes` only after they agree.
39
+ - Run it again at any time. A host that already has AgentGuard is reported as already installed and nothing runs for it; a host that failed is tried again.
40
+ - An installed plugin older than what is available shows as "update available" and is updated through the host's own plugin commands; plugin files are never edited by hand. Available means the newer of what the host's local copy of the marketplace lists and plugin 0.5.0, since that local copy refreshes only when asked. A marketplace still added from the plugin's old repository (MerchantGuard/agentguard-codex-plugin, which GitHub forwards to agentguard-run/agentguard-codex-plugin) is left in place: Claude Code and Codex refuse to add the new source under the same name while it exists, and updates come through it.
41
+ - Where the plugin is installed (or being installed) and enabled, a standalone Burn hook in `~/.codex/hooks.json` or `~/.claude/settings.json` is removed after the plugin steps succeed: a timestamped backup first, then only the Burn gate entries go and every other hook and setting keeps its exact bytes. The plugin includes the same gate; in Codex it does not hand launch checks to a standalone hook, so both would check every launch. With the plugin turned off, or its install failed, the standalone hook stays.
42
+ - A failed host command does not stop the other hosts, and the exit code is 1. A host that is present but missing something it needs (its command on PATH, npm, uv, a readable `hooks.json`) shows in the plan with the reason and is reported as failed. A usage error exits 64.
43
+ - It never pipes a downloaded script to a shell, never uses sudo, never installs a host itself, never asks for or stores a key, and never writes `burn-policy.json`: the plugin writes enforce into a fresh one, and a file written first would keep a new install in shadow.
44
+ - Afterwards: start a new session in each host. In Codex, open `/hooks`, review the AgentGuard hooks and trust them yourself; an agent must never approve its own hooks. Restart Hermes. Then check the effective mode: `agentguard-status` in a Claude Code or Codex session, `agentguard-burn status` for Cursor, `/agentguard status` in Hermes. The mode `install` prints is read from local files; a paid license whose check fails falls back to shadow, which only `agentguard-status` can see.
45
+ - Run through `npx`, the Cursor hook points into the npx cache, which npm can clear. For a lasting hook, install Burn globally first (see "Optional global install and hooks" below), then run `agentguard-burn install`.
46
+
21
47
  ## Simple and detailed views
22
48
 
23
49
  `statusline`, `why` and `live` default to simple; `compact-replay` defaults to detailed so its table shows. Save a preference with `agentguard-burn mode simple` or `agentguard-burn mode detailed`. It lives in `AGENTGUARD_HOME/burn-config.json`, normally under `~/.agentguard`. `AGENTGUARD_BURN_MODE` overrides it. Per-command `simple` and `detailed` flags, prefixed by two hyphens, override both. Detailed output and JSON stay unchanged.
@@ -176,6 +202,23 @@ agentguard-burn reap
176
202
 
177
203
  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
204
 
205
+ The audit opens with free disk on the volume holding your home folder and swap use:
206
+
207
+ ```text
208
+ [WARN] Disk: 13.8 GB free of 994.7 GB (1.4%) on the volume holding /Users/you.
209
+ Under 10 GB or 10% free, the next large build or agent log can fill it.
210
+ [WARN] Swap: 14.1 GB of 15.0 GB in use (94.1%).
211
+ Over 80% used, memory is short and the machine slows down.
212
+ ```
213
+
214
+ 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.
215
+
216
+ 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:
217
+
218
+ ```text
219
+ 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.
220
+ ```
221
+
179
222
  `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
223
 
181
224
  Reap refuses:
package/dist/src/cli.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * replay what enforcement would have stopped, on your history
9
9
  * calibrate fit thresholds to your own usage, write shadow policy
10
10
  * status mode, shadow decisions, eligibility, every host's sessions
11
+ * install find every agent host here, print the plan, install with --yes
11
12
  * init [host] hook snippet for claude (default), cursor or codex
12
13
  * enforce promote shadow -> enforce, once eligible
13
14
  * shadow demote back to shadow
package/dist/src/cli.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * replay what enforcement would have stopped, on your history
10
10
  * calibrate fit thresholds to your own usage, write shadow policy
11
11
  * status mode, shadow decisions, eligibility, every host's sessions
12
+ * install find every agent host here, print the plan, install with --yes
12
13
  * init [host] hook snippet for claude (default), cursor or codex
13
14
  * enforce promote shadow -> enforce, once eligible
14
15
  * shadow demote back to shadow
@@ -89,6 +90,7 @@ const i18n_1 = require("./insights/i18n");
89
90
  const ttl_1 = require("./insights/ttl");
90
91
  const blocks_1 = require("./insights/blocks");
91
92
  const cli_1 = require("./idle/cli");
93
+ const disk_1 = require("./idle/disk");
92
94
  const telemetry_cli_1 = require("./telemetry-cli");
93
95
  const status_fields_1 = require("./insights/status-fields");
94
96
  const status_data_1 = require("./insights/status-data");
@@ -654,7 +656,7 @@ async function main(argv) {
654
656
  process.stdout.write(JSON.stringify(warning ? { continue: true, suppressOutput: false, systemMessage: warning } : { continue: true, suppressOutput: true }));
655
657
  return 0;
656
658
  }
657
- process.stdout.write(JSON.stringify((0, pre_tool_use_1.handlePreToolUse)(input, HOME)));
659
+ process.stdout.write(JSON.stringify((0, pre_tool_use_1.handlePreToolUse)(input, HOME, Date.now(), { volumeProbe: disk_1.statfsProbe })));
658
660
  return 0;
659
661
  }
660
662
  case 'replay': {
@@ -741,6 +743,28 @@ async function main(argv) {
741
743
  .replace(/\n\n\n/g, '\n\n') + '\n');
742
744
  return 0;
743
745
  }
746
+ case 'install': {
747
+ // Loaded only here, so hooks and reports never load it.
748
+ const { defaultRunner, installJson, parseInstallArgs, planInstall, renderPlan, renderReport, runInstall } = await Promise.resolve().then(() => __importStar(require('./install-all')));
749
+ const options = parseInstallArgs(rest);
750
+ if ('error' in options) {
751
+ process.stderr.write(`${options.error}\n`);
752
+ return 64;
753
+ }
754
+ const context = { home: (0, node_os_1.homedir)(), env: process.env, platform: process.platform, cliPath: (0, node_path_1.join)(__dirname, 'cli.js') };
755
+ const plan = planInstall(context, options);
756
+ if (!options.yes) {
757
+ const values = installJson(version_1.BURN_VERSION, plan, null);
758
+ show({ kind: 'command', command, values }, options.json ? `${JSON.stringify(values, null, 2)}\n` : renderPlan(plan, context), true);
759
+ return 0;
760
+ }
761
+ if (!options.json && plan.next)
762
+ process.stdout.write('Installing AgentGuard\n');
763
+ const report = runInstall(plan, context, defaultRunner(context), options.json ? undefined : (line) => process.stdout.write(` ${line}\n`));
764
+ const values = installJson(version_1.BURN_VERSION, plan, report);
765
+ show({ kind: 'command', command, values }, options.json ? `${JSON.stringify(values, null, 2)}\n` : `${plan.next ? '\n' : ''}${renderReport(report)}`, true);
766
+ return report.ok ? 0 : 1;
767
+ }
744
768
  case 'init': {
745
769
  const policy = (0, pre_tool_use_1.loadPolicy)(HOME);
746
770
  savePolicy(policy);
@@ -869,7 +893,7 @@ async function main(argv) {
869
893
  show({ kind: 'command', command: 'help', values: { commands: ['why', 'calendar', 'card'] } }, starter + '\nStart here: npx agentguard-burn why\nAll commands: npx agentguard-burn --help all\n', true);
870
894
  return !command || command === 'help' || command === '--help' || command === '-h' ? 0 : 64;
871
895
  }
872
- show({ kind: 'command', command: 'help', values: { commands: ['tree', 'tally', 'ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'week', 'why', 'compare', 'rewrites', 'compact-replay', 'ttl', 'pace', 'statusline', 'pricing', 'telemetry', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, starter + '\nAll commands\n' +
896
+ show({ kind: 'command', command: 'help', values: { commands: ['tree', 'tally', 'ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'week', 'why', 'compare', 'rewrites', 'compact-replay', 'ttl', 'pace', 'statusline', 'pricing', 'telemetry', 'replay', 'calibrate', 'status', 'install', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, starter + '\nAll commands\n' +
873
897
  ' ps [--json] local agent processes, held memory and workspace disk\n' +
874
898
  ' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
875
899
  ' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
@@ -901,6 +925,7 @@ async function main(argv) {
901
925
  ' replay <replay.json> --pricing <snapshot.json> [--json] replay a saved run with its original prices\n' +
902
926
  ' calibrate fit thresholds to your history (writes shadow policy)\n' +
903
927
  ' status mode, shadow observations, eligibility, hook health, every host\n' +
928
+ ' install [--yes] [--only <hosts>] [--skip <hosts>] [--json] find Claude Code, Codex, Cursor and Hermes here, print the plan; --yes installs AgentGuard on each\n' +
904
929
  ' init [claude|cursor|codex] [--write] print the hook snippet, or merge it into the config (with a backup)\n' +
905
930
  ' enforce [--force] shadow -> enforce\n' +
906
931
  ' shadow enforce -> shadow\n' +
@@ -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 declare function handlePreToolUse(input: HookInput, home: string, now?: number): HookOutput;
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
- if (!observation.messages.length)
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, ...observation.messages].filter(Boolean).join('\n') };
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 ?? '';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Removing AgentGuard's standalone Burn hook from a host's hooks file
3
+ * (~/.codex/hooks.json, ~/.claude/settings.json) once the AgentGuard plugin,
4
+ * which includes the same gate, is installed there.
5
+ *
6
+ * The file is the person's. Other hooks, other settings, their spacing and
7
+ * their key order stay exactly as written: instead of parsing and
8
+ * re-serializing, the file is parsed with byte positions and only the arrays
9
+ * and objects that lose an entry are rebuilt, from the original bytes of the
10
+ * entries they keep. A backup is taken first and the write is atomic.
11
+ */
12
+ export declare function isStandaloneBurnGate(command: unknown): boolean;
13
+ /**
14
+ * Removes the standalone Burn gate entries under "hooks". A matcher group
15
+ * holding only Burn entries goes with them, and an event left with no group
16
+ * goes too; a group that also holds other hooks keeps them.
17
+ */
18
+ export declare function removeStandaloneBurnHooks(text: string): {
19
+ text: string;
20
+ removed: number;
21
+ };
22
+ /** How many standalone Burn gate entries a hooks file holds (0 when it is missing or not valid JSON). */
23
+ export declare function countStandaloneBurnHooks(file: string): number;
24
+ /** Removes the Burn gate entries from a file: a timestamped backup first, then an atomic write that keeps the file's mode. */
25
+ export declare function removeStandaloneBurnHooksFromFile(file: string): {
26
+ removed: number;
27
+ backup: string | null;
28
+ };
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ /**
3
+ * Removing AgentGuard's standalone Burn hook from a host's hooks file
4
+ * (~/.codex/hooks.json, ~/.claude/settings.json) once the AgentGuard plugin,
5
+ * which includes the same gate, is installed there.
6
+ *
7
+ * The file is the person's. Other hooks, other settings, their spacing and
8
+ * their key order stay exactly as written: instead of parsing and
9
+ * re-serializing, the file is parsed with byte positions and only the arrays
10
+ * and objects that lose an entry are rebuilt, from the original bytes of the
11
+ * entries they keep. A backup is taken first and the write is atomic.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.isStandaloneBurnGate = isStandaloneBurnGate;
15
+ exports.removeStandaloneBurnHooks = removeStandaloneBurnHooks;
16
+ exports.countStandaloneBurnHooks = countStandaloneBurnHooks;
17
+ exports.removeStandaloneBurnHooksFromFile = removeStandaloneBurnHooksFromFile;
18
+ const node_fs_1 = require("node:fs");
19
+ /**
20
+ * A Burn gate command as `init claude|codex --write` writes it (or the npx and
21
+ * bare-command forms): Burn's CLI followed by `hook` or `codex-hook`. Other
22
+ * commands that mention Burn, such as `npx agentguard-burn why`, are not gates.
23
+ */
24
+ const BURN_GATE = /(?:agentguard-burn|agentguard-run\/burn)\S*\s+(?:hook|codex-hook)$/;
25
+ function isStandaloneBurnGate(command) {
26
+ return typeof command === 'string' && BURN_GATE.test(command.trim());
27
+ }
28
+ /** A JSON parser that keeps where every value starts and ends. Input is already known to be valid JSON. */
29
+ function parseWithPositions(text) {
30
+ let i = 0;
31
+ const ws = () => {
32
+ while (i < text.length && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r'))
33
+ i++;
34
+ };
35
+ const fail = (what) => {
36
+ throw new Error(`not valid JSON: ${what} at offset ${i}`);
37
+ };
38
+ const string = () => {
39
+ const start = i;
40
+ if (text[i] !== '"')
41
+ fail('string expected');
42
+ i++;
43
+ while (i < text.length && text[i] !== '"')
44
+ i += text[i] === '\\' ? 2 : 1;
45
+ if (text[i] !== '"')
46
+ fail('unterminated string');
47
+ i++;
48
+ return JSON.parse(text.slice(start, i));
49
+ };
50
+ const value = () => {
51
+ ws();
52
+ const start = i;
53
+ if (text[i] === '{') {
54
+ i++;
55
+ const members = [];
56
+ ws();
57
+ if (text[i] === '}')
58
+ return { kind: 'object', start, end: ++i, members };
59
+ for (;;) {
60
+ ws();
61
+ const keyStart = i;
62
+ const key = string();
63
+ ws();
64
+ if (text[i] !== ':')
65
+ fail("':' expected");
66
+ i++;
67
+ members.push({ key, keyStart, value: value() });
68
+ ws();
69
+ if (text[i] === ',') {
70
+ i++;
71
+ continue;
72
+ }
73
+ if (text[i] === '}') {
74
+ i++;
75
+ break;
76
+ }
77
+ fail("',' or '}' expected");
78
+ }
79
+ return { kind: 'object', start, end: i, members };
80
+ }
81
+ if (text[i] === '[') {
82
+ i++;
83
+ const items = [];
84
+ ws();
85
+ if (text[i] === ']')
86
+ return { kind: 'array', start, end: ++i, items };
87
+ for (;;) {
88
+ items.push(value());
89
+ ws();
90
+ if (text[i] === ',') {
91
+ i++;
92
+ continue;
93
+ }
94
+ if (text[i] === ']') {
95
+ i++;
96
+ break;
97
+ }
98
+ fail("',' or ']' expected");
99
+ }
100
+ return { kind: 'array', start, end: i, items };
101
+ }
102
+ if (text[i] === '"') {
103
+ const parsed = string();
104
+ return { kind: 'value', start, end: i, value: parsed };
105
+ }
106
+ const literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i, i + 64));
107
+ if (!literal)
108
+ fail('value expected');
109
+ i += literal[0].length;
110
+ return { kind: 'value', start, end: i, value: JSON.parse(literal[0]) };
111
+ };
112
+ const root = value();
113
+ ws();
114
+ if (i !== text.length)
115
+ fail('trailing text');
116
+ return root;
117
+ }
118
+ /** The original text with every node in `drop` removed; untouched parts keep their bytes. */
119
+ function render(text, node, drop) {
120
+ if (node.kind === 'value')
121
+ return text.slice(node.start, node.end);
122
+ const children = node.kind === 'array'
123
+ ? node.items.map((item) => ({ start: item.start, node: item }))
124
+ : node.members.map((member) => ({ start: member.keyStart, node: member.value }));
125
+ if (!children.length)
126
+ return text.slice(node.start, node.end);
127
+ const kept = children.filter((child) => !drop.has(child.node));
128
+ const [open, close] = node.kind === 'array' ? ['[', ']'] : ['{', '}'];
129
+ if (!kept.length)
130
+ return open + close;
131
+ if (kept.length === children.length) {
132
+ let out = '';
133
+ let at = node.start;
134
+ for (const child of children) {
135
+ out += text.slice(at, child.node.start) + render(text, child.node, drop);
136
+ at = child.node.end;
137
+ }
138
+ return out + text.slice(at, node.end);
139
+ }
140
+ const first = children[0];
141
+ const last = children[children.length - 1];
142
+ const separator = children.length > 1 ? text.slice(first.node.end, children[1].start) : ', ';
143
+ return open + text.slice(node.start + 1, first.start)
144
+ + kept.map((child) => text.slice(child.start, child.node.start) + render(text, child.node, drop)).join(separator)
145
+ + text.slice(last.node.end, node.end - 1) + close;
146
+ }
147
+ const commandOf = (node) => {
148
+ if (node.kind !== 'object')
149
+ return undefined;
150
+ const command = node.members.find((m) => m.key === 'command')?.value;
151
+ return command?.kind === 'value' ? command.value : undefined;
152
+ };
153
+ /**
154
+ * Removes the standalone Burn gate entries under "hooks". A matcher group
155
+ * holding only Burn entries goes with them, and an event left with no group
156
+ * goes too; a group that also holds other hooks keeps them.
157
+ */
158
+ function removeStandaloneBurnHooks(text) {
159
+ JSON.parse(text); // refuse anything that is not plain JSON before touching it
160
+ const root = parseWithPositions(text);
161
+ if (root.kind !== 'object')
162
+ return { text, removed: 0 };
163
+ const hooks = root.members.find((m) => m.key === 'hooks')?.value;
164
+ if (!hooks || hooks.kind !== 'object')
165
+ return { text, removed: 0 };
166
+ const drop = new Set();
167
+ let removed = 0;
168
+ for (const event of hooks.members) {
169
+ if (event.value.kind !== 'array')
170
+ continue;
171
+ let kept = 0;
172
+ let dropped = 0;
173
+ for (const group of event.value.items) {
174
+ if (commandOf(group) !== undefined) {
175
+ if (isStandaloneBurnGate(commandOf(group))) {
176
+ drop.add(group);
177
+ removed++;
178
+ dropped++;
179
+ }
180
+ else
181
+ kept++;
182
+ continue;
183
+ }
184
+ const inner = group.kind === 'object' ? group.members.find((m) => m.key === 'hooks')?.value : undefined;
185
+ const burn = inner?.kind === 'array' ? inner.items.filter((h) => isStandaloneBurnGate(commandOf(h))) : [];
186
+ if (!inner || inner.kind !== 'array' || !burn.length) {
187
+ kept++;
188
+ continue;
189
+ }
190
+ removed += burn.length;
191
+ if (burn.length === inner.items.length) {
192
+ drop.add(group);
193
+ dropped++;
194
+ }
195
+ else {
196
+ for (const entry of burn)
197
+ drop.add(entry);
198
+ kept++;
199
+ }
200
+ }
201
+ if (!kept && dropped)
202
+ drop.add(event.value);
203
+ }
204
+ // Whitespace around the top-level object (a final newline, say) stays as it was.
205
+ return removed ? { text: text.slice(0, root.start) + render(text, root, drop) + text.slice(root.end), removed } : { text, removed: 0 };
206
+ }
207
+ /** How many standalone Burn gate entries a hooks file holds (0 when it is missing or not valid JSON). */
208
+ function countStandaloneBurnHooks(file) {
209
+ try {
210
+ return removeStandaloneBurnHooks((0, node_fs_1.readFileSync)(file, 'utf8')).removed;
211
+ }
212
+ catch {
213
+ return 0;
214
+ }
215
+ }
216
+ /** Removes the Burn gate entries from a file: a timestamped backup first, then an atomic write that keeps the file's mode. */
217
+ function removeStandaloneBurnHooksFromFile(file) {
218
+ const original = (0, node_fs_1.readFileSync)(file, 'utf8');
219
+ const result = removeStandaloneBurnHooks(original);
220
+ if (!result.removed)
221
+ return { removed: 0, backup: null };
222
+ JSON.parse(result.text); // the rebuilt file must still be valid JSON before it replaces the original
223
+ const stamp = new Date().toISOString().replace(/[-:.]/g, '').slice(0, 15); // 20261028T163812
224
+ let backup = `${file}.bak-${stamp}`;
225
+ for (let n = 1; (0, node_fs_1.existsSync)(backup); n++)
226
+ backup = `${file}.bak-${stamp}-${n}`;
227
+ (0, node_fs_1.copyFileSync)(file, backup, node_fs_1.constants.COPYFILE_EXCL);
228
+ const temporary = `${file}.agentguard.tmp`;
229
+ (0, node_fs_1.writeFileSync)(temporary, result.text, { mode: (0, node_fs_1.statSync)(file).mode & 0o777 });
230
+ (0, node_fs_1.renameSync)(temporary, file);
231
+ return { removed: result.removed, backup };
232
+ }
@@ -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;