burnoff 1.0.0 → 1.2.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.
Files changed (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -0,0 +1,75 @@
1
+ name: Burnoff PR Cost & CI Budget Gate
2
+
3
+ on:
4
+ pull_request:
5
+ types: [opened, synchronize, reopened]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ pr-cost-gate:
12
+ runs-on: ubuntu-latest
13
+ outputs:
14
+ summary_path: ${{ steps.gate.outputs.summary_path }}
15
+ steps:
16
+ - name: Checkout repository
17
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
18
+ with:
19
+ fetch-depth: 0
20
+
21
+ - name: Setup Node.js
22
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
23
+ with:
24
+ node-version: '22'
25
+
26
+ - name: Compute PR Cost Attribution
27
+ run: |
28
+ mkdir -p .burnoff-ci
29
+ USAGE_FLAG=""
30
+ if [ -s .burnoff-ci/provider-usage.json ]; then
31
+ USAGE_FLAG="--provider-usage .burnoff-ci/provider-usage.json"
32
+ fi
33
+ npx -y burnoff@1.2.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --json --out .burnoff-ci/pr-cost.json
34
+ npx -y burnoff@1.2.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --markdown --out .burnoff-ci/pr-cost.md
35
+
36
+ - name: Enforce CI Token-Budget Gate
37
+ id: gate
38
+ run: |
39
+ npx -y burnoff@1.2.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations --out .burnoff-ci/ci-gate.md
40
+ cat .burnoff-ci/pr-cost.md >> "$GITHUB_STEP_SUMMARY"
41
+ cat .burnoff-ci/ci-gate.md >> "$GITHUB_STEP_SUMMARY"
42
+ echo "summary_path=.burnoff-ci/pr-cost.md" >> "$GITHUB_OUTPUT"
43
+
44
+ - name: Upload PR attribution artifact
45
+ if: always()
46
+ uses: actions/upload-artifact@ea165f8d65b6e75b5fd2b08d0cbd28a89f188154
47
+ with:
48
+ name: burnoff-pr-cost
49
+ path: .burnoff-ci/
50
+ if-no-files-found: ignore
51
+
52
+ pr-comment:
53
+ needs: pr-cost-gate
54
+ if: always() && github.event.pull_request.head.repo.fork == false
55
+ runs-on: ubuntu-latest
56
+ permissions:
57
+ contents: read
58
+ pull-requests: write
59
+ steps:
60
+ - name: Download PR attribution artifact
61
+ uses: actions/download-artifact@d3f86a106a0bac45b975a62879b590290c2497ec
62
+ with:
63
+ name: burnoff-pr-cost
64
+ path: .burnoff-ci
65
+
66
+ - name: Post PR Cost Summary Comment
67
+ env:
68
+ GH_TOKEN: ${{ github.token }}
69
+ PR_NUMBER: ${{ github.event.pull_request.number }}
70
+ REPO: ${{ github.repository }}
71
+ run: |
72
+ if [ -s .burnoff-ci/pr-cost.md ]; then
73
+ { cat .burnoff-ci/pr-cost.md; echo ""; [ -s .burnoff-ci/ci-gate.md ] && cat .burnoff-ci/ci-gate.md; } > .burnoff-ci/comment.md
74
+ gh pr comment "$PR_NUMBER" --repo "$REPO" --body-file .burnoff-ci/comment.md
75
+ fi
package/README.md CHANGED
@@ -1,54 +1,118 @@
1
1
  # Burnoff
2
2
 
3
- **Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code.**
3
+ **Burnoff** — Deterministic circuit breakers, bounded file-read guards, and Turn-0 config linting for Claude Code (with experimental Google Antigravity CLI support).
4
4
 
5
- Burnoff stops runaway agent failure loops, protects repositories from destructive shell commands and credential reads, bounds oversized file reads before they blow up context windows, and enforces per-PR AI spend budgets in GitHub Actions. Designed as a zero-dependency, zero-proxy companion to `rtk` and `ccusage`.
5
+ Burnoff runs locally via `PreToolUse` and `PostToolUse` hooks to bound oversized file reads (`updatedInput`), stop runaway command failure loops, block destructive shell/git operations and credential reads, and statically lint Turn-0 repository config bloat (`CLAUDE.md`/`AGENTS.md`, `.mcp.json`, volatile prompt-prefix instructions `BO-CFG-11`). Zero runtime dependencies, MIT licensed, 100% local, and no proxy or daemon required.
6
6
 
7
7
  ## Why Burnoff?
8
8
 
9
- - **Runaway Loop Circuit Breaker (`DET-04`):** Trips after 3 consecutive identical tool/command failures with atomic cross-process state locking (`O_EXCL`), resetting cleanly on success or `git stash`.
10
- - **Destructive Command & Secret Guards (`DET-01`, `DET-02`, `DET-03`):** Blocks `git push --force`, `--no-verify`, `HUSKY=0`, `rm -rf`, and credential/env reads (allowing safe templates like `.env.example`), while downgrading reversible `git checkout --` / `git restore` calls to an interactive `ask` prompt.
11
- - **Bounded File-Read Clamp (`updatedInput`):** Caps unbounded doc/log reads (`250 lines / 16 KB`), fast-clamps multi-megabyte sparse files via an `8 MB` head probe (`<50 ms`), trims overlapping re-reads, and leaves active source code unclamped (`neverClampCodeOffCliff: true`).
12
- - **FTS5 CLI Output Archival (`node:sqlite`):** Archives noisy test/build stdout into `~/.burnoff/cache/tool_logs_fts5.db` while keeping `100%` of critical error lines and returning a `npx burnoff search <turnId> "<keyword>"` handle.
13
- - **Infracost-Style PR Spend Gates (`pr-cost`, `ci-gate`, `team-digest`):** Attributes branch commits to Claude Code session spend, reconciles against `--provider-usage <export.json>`, and enforces `.burnoff.yaml` thresholds in CI without touching `.claude/settings.json`.
9
+ - **Bounded File-Read Guards (`DET-06`):** Clamps oversized non-code reads (`250 lines / 16 KB`) via `updatedInput`, skips overlapping re-reads, and leaves active source files unclamped.
10
+ - **Deterministic Runaway Loop Breaker (`DET-04`):** Halts repeating tool or command failure loops after 3 consecutive failures using cross-process state locking, exempting read-only recovery steps and resetting cleanly on success or `git stash`.
11
+ - **Destructive Shell & Credential Guards (`DET-01` / `DET-02` / `DET-03`):** Blocks high-risk shell/git commands (`git push --force`, `--no-verify`, `rm -rf`) and sensitive credential/env paths (allowing `.env.example`/`.env.sample` templates), while routing reversible git resets and lockfile/workflow edits through interactive confirmation.
12
+ - **Turn-0 Startup Config Linter (`audit --startup`):** Audits `.mcp.json`, Claude Code settings, `.agents/mcp_config.json`, `GEMINI.md`/`AGENTS.md`/`.agents/rules/*.md`, volatile prompt-prefix instructions (`BO-CFG-11`), and tool bloat before a session starts.
13
+ - **Repo Policy & Local FinOps (`pr-cost` / `ci-gate`):** Correlates branch commits with local Claude Code and Google Antigravity CLI session transcripts, optionally reconciles against `.burnoff-ci/provider-usage.json`, and evaluates `.burnoff.yaml` thresholds via `ci-gate`.
14
14
 
15
- ## Requirements
15
+ ## Requirements & Scope
16
16
 
17
- - **Node.js `>=20.19.0`** (`Node.js >=22.13.0` recommended for native built-in `node:sqlite` FTS5 indexing; older supported versions automatically run in JSONL fallback mode).
18
- - **Zero runtime npm dependencies.**
17
+ - **Supported Agents:** **Claude Code** and **Google Antigravity CLI (experimental)**.
18
+ - **Runtime:** **Node.js `>=20.19.0`** (`Node.js >=22.13.0` recommended for built-in `node:sqlite` FTS5 indexing; older supported Node.js versions automatically run in local JSON fallback mode).
19
+ - **Dependencies:** **Zero runtime npm dependencies.**
20
+
21
+ ### Client Capability Matrix
22
+
23
+ | Capability | Claude Code | Google Antigravity CLI (experimental) |
24
+ | :--- | :---: | :---: |
25
+ | **DET-01 / 02 / 03** (Shell, secret & protected-file guards) | Yes | Yes (`decision: deny \| ask`) |
26
+ | **DET-04** (Runaway loop breaker) | Yes (`PostToolUse` / `PostToolUseFailure`) | Yes (`PostToolUse.error`) |
27
+ | **DET-05** (Subagent fan-out & prompt-bloat guard) | Yes (`Task` / `Agent`, advisory by default) | Yes (`invoke_subagent`, advisory by default) |
28
+ | **DET-06** (Bounded file-read clamp & overlap trim) | Yes (`updatedInput`) | Yes (`overwrite: { StartLine, EndLine }`) |
29
+ | **`PostToolUse` FTS5 log archive & MCP output replacement** | MCP replacement + local FTS5 archive (built-in tool output is not replaced in `auto` mode) | **No** (`PostToolUse` returns `{}`) |
30
+ | **Turn-0 startup audit (`burnoff audit --startup`)** | Yes | Yes (`GEMINI.md`, `AGENTS.md`, `.agents/`) |
31
+ | **Local FinOps (`audit`, `pr-cost`, `ci-gate`)** | Yes | Yes (Gemini rate cards & `transcript.jsonl`) |
19
32
 
20
33
  ## Quickstart
21
34
 
22
- Install hooks into your repository's local Claude Code settings (`.claude/settings.local.json`) and protect `git status` via `.git/info/exclude`:
35
+ Install Burnoff in your project, preview changes, wire hooks, and run your Turn-0 health & startup audit:
23
36
 
24
37
  ```bash
25
- npx burnoff init
38
+ npm i -D burnoff
39
+ npx burnoff init --dry-run
40
+ npx burnoff init # Claude Code (.claude/settings.local.json)
41
+ npx burnoff init --client antigravity # Google Antigravity CLI (.agents/hooks.json)
42
+ npx burnoff init --client antigravity --global # Global (~/.gemini/config/hooks.json)
43
+ npx burnoff init --client both # Wire both clients
44
+ npx burnoff audit --startup
26
45
  npx burnoff doctor
46
+ npx burnoff doctor --gc # Prune >14d caches & rotate prior-month ledger
27
47
  ```
28
48
 
29
49
  Remove hooks cleanly at any time:
30
50
 
31
51
  ```bash
32
52
  npx burnoff uninstall
53
+ npx burnoff uninstall --client antigravity [--global]
54
+ ```
55
+
56
+ ## Smoke Test (`PreToolUse` exit `2`)
57
+
58
+ Verify that the `PreToolUse` guard blocks secret reads before execution:
59
+
60
+ ```bash
61
+ echo '{"session_id":"smoke-1","tool_name":"Bash","tool_input":{"command":"cat .env;echo ok"}}' | node node_modules/burnoff/hooks/pre-tool-use.mjs; echo "exit=$?"
62
+ ```
63
+
64
+ Expected output:
65
+
66
+ ```text
67
+ [Burnoff DET-02 Secret & Credential Boundary] Access to sensitive credential path ".env" is blocked. (.env.example / .env.sample are permitted.)
68
+ exit=2
33
69
  ```
34
70
 
71
+ ## Measured Hook Latency & `Read`-Clamp Savings
72
+
73
+ Measured directly on **Windows (`win32`, Node `v25.6.0`)** (reproduce locally with `npm run test:bench`):
74
+
75
+ | Hook / Path | Mode | Median (`p50`) | Notes |
76
+ | :--- | :--- | :---: | :--- |
77
+ | `hooks/pre-tool-use.mjs` | Cold CLI spawn (`n=5`) | `102.4 ms` | Synchronous named-pipe bailout on cold start (`112.0 ms` p50 over 10 runs in `test:bench`) |
78
+ | `hooks/pre-tool-use.mjs` | Warm daemon CLI / RPC (`n=10`) | `97.2 ms` CLI / `1.34 ms` RPC | Over warm IPC (`burnoff daemon start`) |
79
+ | `hooks/post-tool-use.mjs` | Cold CLI spawn (`n=5`) | `136.4 ms` | `POST_TOOL_MATCHER` excludes `Grep\|Glob` |
80
+
81
+ Example measured `Read`-clamp (`DET-06`) run on an 800-line, `72,000`-byte (`~18,000` est. tokens) log file (`APP_SERVER.log`):
82
+
83
+ - **Before clamp:** `800` lines / `72,000` bytes (`~18,000` est. tokens).
84
+ - **After `PreToolUse` `updatedInput` (`offset: 1, limit: 182`):** `182` lines / `16,379` bytes (`~4,095` est. tokens) — **`~13,906` est. tokens (`77.3%`) saved** in a single intercepted `Read` while respecting the `16 KB` (`16,384` B) ceiling.
85
+
86
+ ## Local-Only Trust & Privacy
87
+
88
+ Burnoff runs 100% locally via hook subprocesses and local CLI commands:
89
+
90
+ - **Zero outbound network calls & zero proxy/MITM:** Your prompts, source code, and credentials never leave your machine.
91
+ - **Exact paths touched:**
92
+ - `~/.burnoff/` (or `$BURNOFF_HOME`): savings ledger, FTS5/JSON CLI log archive, and optional local warm daemon socket/pipe.
93
+ - `.claude/settings.local.json`: repo-local Claude Code hook wiring only (never modifies shared `.claude/settings.json`).
94
+ - `.claude/cache/` and `.claude/locks/`: session loop-breaker state, read-interval snapshots, lockfiles, and offloaded `>=4k`-token tool output artifacts (`.claude/cache/artifacts/burnoff_<sha256>.txt`, pruned via `npx burnoff doctor --gc`).
95
+ - `.agents/hooks.json` (project) or `~/.gemini/config/hooks.json` (global): written only when `--client antigravity` or `--client both` is passed.
96
+ - `.git/info/exclude`: privately ignores Burnoff's local files so `git status` stays spotless without touching `.gitignore`.
97
+
35
98
  ## CLI Commands
36
99
 
37
100
  | Command | Purpose |
38
101
  | :--- | :--- |
39
- | `burnoff init [--dry-run]` | Wire `PreToolUse` and `PostToolUse` hooks in `.claude/settings.local.json` and update `.git/info/exclude`. |
102
+ | `burnoff init [--dry-run]` | Wire `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` hooks and update `.git/info/exclude`. |
40
103
  | `burnoff uninstall [--dry-run]` | Remove Burnoff hooks and `.git/info/exclude` block. |
41
104
  | `burnoff doctor [--gc] [--json]` | Inspect Node/SQLite FTS5, `.burnoff.yaml`, hook wiring, warm daemon, ledger, and prune >14d caches with `--gc`. |
42
- | `burnoff audit [--session <file>] [--json]` | Parse Claude Code JSONL transcripts (`~/.claude/projects/`) and report per-session cost, cache hit %, and 200k-cliff turns. |
105
+ | `burnoff audit --startup [--json]` | Run the Turn-0 startup config linter across `.mcp.json`, Claude Code settings, and rule files. |
106
+ | `burnoff audit [--session <file>] [--json]` | Parse local JSONL transcripts (`~/.claude/projects/`) and report per-session cost, cache hit %, and >200k-cliff turns. |
43
107
  | `burnoff pr-cost [--base main] [--provider-usage file.json]` | Correlate `git log <base>..HEAD` commits with session spend and output Markdown or `burnoff-pr-attribution/v1` JSON. |
44
- | `burnoff ci-gate [--strict] [--github-annotations]` | Enforce `.burnoff.yaml` `ciBudgetGate` thresholds (`MAX_PR_COST_USD`, `MAX_PR_TOKENS`, `MIN_CACHE_HIT_PCT`, `MAX_WASTE_RATIO_PCT`, `MAX_RING0_VIOLATIONS`). |
45
- | `burnoff team-digest [--days 7]` | Output a 5-line weekly Engineering Manager summary of spend, cache efficiency, top cost driver, and guard savings. |
108
+ | `burnoff ci-gate --input pr-cost.json [--strict] [--github-annotations]` | Enforce `.burnoff.yaml` `ciBudgetGate` thresholds (`MAX_PR_COST_USD`, `MAX_PR_TOKENS`, `MIN_CACHE_HIT_PCT`, `MAX_WASTE_RATIO_PCT`, `MAX_RING0_VIOLATIONS`). |
109
+ | `burnoff team-digest [--days 7]` | Output a 5-line weekly summary of local spend, cache efficiency, top cost driver, and guard savings. |
46
110
  | `burnoff search <turnId> [keyword]` | Search archived FTS5 CLI output without re-running expensive test or build commands. |
47
111
  | `burnoff daemon <start\|stop\|status>` | Manage the workspace-scoped warm IPC daemon (`~/.burnoff/run/` or Windows named pipe). |
48
112
 
49
- ## Team Policy (`.burnoff.yaml`)
113
+ ## For Teams: Repo Policy & GitHub Actions
50
114
 
51
- Create an optional `.burnoff.yaml` in your repository root to customize guardrails and CI spend gates:
115
+ Commit an optional `.burnoff.yaml` in your repository root so every developer shares the same deterministic guardrails, read bounds, and CI gate thresholds:
52
116
 
53
117
  ```yaml
54
118
  guards:
@@ -56,6 +120,11 @@ guards:
56
120
  det04Threshold: 3
57
121
  strictTestIntegrity: false
58
122
  scopeLockEnabled: true
123
+ subagentFanoutEnabled: true
124
+ subagentFanoutAction: advisory
125
+ subagentMaxBurstCount: 4
126
+ subagentBurstWindowSec: 60
127
+ subagentMaxPromptChars: 8000
59
128
 
60
129
  readClamp:
61
130
  enabled: true
@@ -75,11 +144,16 @@ ciBudgetGate:
75
144
  maxWasteRatioPct: 35
76
145
  maxRing0Violations: 0
77
146
  mode: enforce
147
+ failOnMissingTranscripts: false
78
148
  ```
79
149
 
80
- ## GitHub Actions PR Gate
150
+ See [`.github/workflows/burnoff-pr-gate.yml`](.github/workflows/burnoff-pr-gate.yml) for a SHA-pinned, least-privilege (`permissions: contents: read`) workflow built for `burnoff@1.2.0`:
151
+
152
+ - Runs `npx -y burnoff@1.2.0 pr-cost` (automatically passing `--provider-usage .burnoff-ci/provider-usage.json` when present) to produce `.burnoff-ci/pr-cost.json` and `.burnoff-ci/pr-cost.md`.
153
+ - Runs `npx -y burnoff@1.2.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations`.
154
+ - Appends the Markdown breakdown to `$GITHUB_STEP_SUMMARY` and posts non-fork PR summary comments.
81
155
 
82
- See [`.github/workflows/burnoff-pr-gate.yml`](.github/workflows/burnoff-pr-gate.yml) for a SHA-pinned, least-privilege (`permissions: contents: read`) workflow that computes PR cost attribution, enforces `ci-gate --strict`, and posts PR summary comments on non-fork PRs.
156
+ > **Note on CI runners:** Ephemeral GitHub Actions runners do not have access to developers' local `~/.claude/projects/` transcripts. `failOnMissingTranscripts` automatically defaults to `true` when `CI` or `GITHUB_ACTIONS` is set (unless explicitly overridden in `.burnoff.yaml`), so upload `.burnoff-ci/provider-usage.json` or session transcripts before running `pr-cost` to enforce budgets cleanly.
83
157
 
84
158
  ## Environment Variables
85
159
 
package/bin/burnoff.mjs CHANGED
@@ -10,8 +10,7 @@ import { spawn } from 'node:child_process';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import {
12
12
  suppressSqliteExperimentalWarning,
13
- ensureSupportedNodeVersion,
14
- getHomeDir
13
+ ensureSupportedNodeVersion
15
14
  } from '../src/config/paths.mjs';
16
15
  import { isCliEntrypoint } from '../hooks/hook-io.mjs';
17
16
  import { atomicWriteFileSync } from '../src/storage/atomic-io.mjs';
@@ -28,9 +27,24 @@ function getPackageVersion() {
28
27
  } catch (err) {
29
28
  void err; // ignore: package.json read fallback
30
29
  }
31
- return '1.0.0';
30
+ return '1.2.0';
32
31
  }
33
32
 
33
+ const BOOLEAN_FLAGS = new Set([
34
+ 'json',
35
+ 'dry-run',
36
+ 'gc',
37
+ 'strict',
38
+ 'github-annotations',
39
+ 'markdown',
40
+ 'startup',
41
+ 'foreground',
42
+ 'skip-daemon',
43
+ 'global',
44
+ 'help',
45
+ 'version'
46
+ ]);
47
+
34
48
  function parseCliArgs(argv = []) {
35
49
  const positionals = [];
36
50
  const flags = {};
@@ -55,7 +69,7 @@ function parseCliArgs(argv = []) {
55
69
  } else {
56
70
  const key = arg.slice(2);
57
71
  const next = argv[i + 1];
58
- if (next !== undefined && !String(next).startsWith('-')) {
72
+ if (!BOOLEAN_FLAGS.has(key) && next !== undefined && !String(next).startsWith('-')) {
59
73
  flags[key] = next;
60
74
  i += 1;
61
75
  } else {
@@ -78,17 +92,18 @@ function writeOut(text, outPath, stream = process.stdout) {
78
92
 
79
93
  function formatHelp() {
80
94
  return [
81
- `burnoff v${getPackageVersion()} — Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code`,
95
+ `burnoff v${getPackageVersion()} — Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code & Google Antigravity`,
82
96
  '',
83
97
  'Usage:',
84
98
  ' burnoff <command> [options]',
85
99
  '',
86
100
  'Commands:',
87
- ' init [--dry-run] [--cwd <dir>] Install PreToolUse/PostToolUse hooks in .claude/settings.local.json',
88
- ' uninstall [--dry-run] [--cwd <dir>] Remove Burnoff hooks and .git/info/exclude entries',
101
+ ' init [--client claude|antigravity|both|auto] [--global] [--dry-run] [--cwd <dir>] Install Burnoff hooks',
102
+ ' uninstall [--client claude|antigravity|both|auto] [--global] [--dry-run] [--cwd <dir>] Remove Burnoff hooks',
89
103
  ' doctor [--gc] [--json] Run Node/SQLite/hooks/daemon/FTS5/ledger diagnostics',
90
- ' audit [--session <file>] [--json] Audit Claude Code JSONL transcripts and spend',
91
- ' pr-cost [--base main] [--json|--markdown] Attribute branch commits to Claude Code token/USD cost',
104
+ ' audit [--startup] [--client auto|claude|antigravity] [--session <file>] [--json] Audit transcripts or Turn-0 config',
105
+ ' pr-cost [--base main] [--client auto|claude|antigravity|both] [--json|--markdown] Attribute branch commits to AI cost',
106
+ ' export [--since <sha>] [--out <file>] Export PR attribution JSON for CI budget gate',
92
107
  ' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
93
108
  ' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
94
109
  ' search <turnId> [keyword] Query archived FTS5 tool outputs',
@@ -105,14 +120,25 @@ async function handleInit(flags, io) {
105
120
  const { initBurnoff } = await import('../src/cli/init.mjs');
106
121
  const res = initBurnoff({
107
122
  cwd: flags.cwd || process.cwd(),
123
+ homeDir: flags.home || undefined,
124
+ client: typeof flags.client === 'string' ? flags.client : 'claude',
125
+ global: Boolean(flags.global),
108
126
  dryRun: Boolean(flags['dry-run'])
109
127
  });
110
128
  if (flags.json) {
111
129
  io.stdout.write(JSON.stringify(res, null, 2) + '\n');
112
130
  } else {
131
+ const targets = [];
132
+ if (res.clients?.includes('claude')) targets.push(res.settingsPath);
133
+ if (res.clients?.includes('antigravity') && res.antigravityHooksPath) {
134
+ targets.push(res.antigravityHooksPath);
135
+ }
113
136
  io.stdout.write(
114
- `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${res.settingsPath}\n` +
115
- (res.excludePath ? ` git exclude: ${res.excludePath}\n` : '')
137
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${targets.join(' and ')}\n` +
138
+ (res.excludePath ? ` git exclude: ${res.excludePath}\n` : '') +
139
+ (Array.isArray(res.warnings) && res.warnings.length > 0
140
+ ? res.warnings.map((w) => ` warning: ${w}\n`).join('')
141
+ : '')
116
142
  );
117
143
  }
118
144
  return 0;
@@ -122,13 +148,21 @@ async function handleUninstall(flags, io) {
122
148
  const { uninstallBurnoff } = await import('../src/cli/init.mjs');
123
149
  const res = uninstallBurnoff({
124
150
  cwd: flags.cwd || process.cwd(),
151
+ homeDir: flags.home || undefined,
152
+ client: typeof flags.client === 'string' ? flags.client : undefined,
153
+ global: Boolean(flags.global),
125
154
  dryRun: Boolean(flags['dry-run'])
126
155
  });
127
156
  if (flags.json) {
128
157
  io.stdout.write(JSON.stringify(res, null, 2) + '\n');
129
158
  } else {
159
+ const targets = [];
160
+ if (res.clients?.includes('claude')) targets.push(res.settingsPath);
161
+ if (res.clients?.includes('antigravity') && res.antigravityHooksPath) {
162
+ targets.push(res.antigravityHooksPath);
163
+ }
130
164
  io.stdout.write(
131
- `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${res.settingsPath}\n`
165
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${targets.join(' and ')}\n`
132
166
  );
133
167
  }
134
168
  return 0;
@@ -138,7 +172,7 @@ async function handleDoctor(flags, io) {
138
172
  const { runDoctor, formatDoctorReport } = await import('../src/cli/doctor.mjs');
139
173
  const report = await runDoctor({
140
174
  cwd: flags.cwd || process.cwd(),
141
- homeDir: flags.home || getHomeDir(),
175
+ homeDir: flags.home || undefined,
142
176
  gc: Boolean(flags.gc),
143
177
  skipDaemonCheck: Boolean(flags['skip-daemon'])
144
178
  });
@@ -148,10 +182,24 @@ async function handleDoctor(flags, io) {
148
182
  }
149
183
 
150
184
  async function handleAudit(flags, io) {
185
+ const clientOpt = typeof flags.client === 'string' ? flags.client : 'auto';
186
+ if (flags.startup) {
187
+ const { runStartupAudit, formatStartupAuditReport } = await import('../src/cli/startup-audit.mjs');
188
+ const report = runStartupAudit({
189
+ cwd: flags.cwd || process.cwd(),
190
+ homeDir: flags.home || undefined,
191
+ days: flags.days ? Number(flags.days) : 7,
192
+ client: clientOpt
193
+ });
194
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatStartupAuditReport(report);
195
+ writeOut(text, flags.out, io.stdout);
196
+ return 0;
197
+ }
151
198
  const { auditClaudeSessions, formatAuditReport } = await import('../src/cli/audit.mjs');
152
199
  const report = auditClaudeSessions({
153
200
  cwd: flags.cwd || process.cwd(),
154
- homeDir: flags.home || getHomeDir(),
201
+ homeDir: flags.home || undefined,
202
+ client: clientOpt,
155
203
  sessionPath: typeof flags.session === 'string' ? flags.session : undefined,
156
204
  limit: flags.limit ? Number(flags.limit) : undefined
157
205
  });
@@ -164,7 +212,8 @@ async function handlePrCost(flags, io) {
164
212
  const { buildPrCostAttribution, formatPrAttributionMarkdown } = await import('../src/ci/pr-cost.mjs');
165
213
  const report = buildPrCostAttribution({
166
214
  cwd: flags.cwd || process.cwd(),
167
- homeDir: flags.home || getHomeDir(),
215
+ homeDir: flags.home || undefined,
216
+ client: typeof flags.client === 'string' ? flags.client : 'auto',
168
217
  base: typeof flags.base === 'string' ? flags.base : 'main',
169
218
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
170
219
  providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
@@ -180,11 +229,30 @@ async function handlePrCost(flags, io) {
180
229
  return 0;
181
230
  }
182
231
 
232
+ async function handleExport(flags, io) {
233
+ const { buildPrCostAttribution } = await import('../src/ci/pr-cost.mjs');
234
+ const report = buildPrCostAttribution({
235
+ cwd: flags.cwd || process.cwd(),
236
+ homeDir: flags.home || undefined,
237
+ client: typeof flags.client === 'string' ? flags.client : 'auto',
238
+ base: typeof flags.since === 'string' ? flags.since : typeof flags.base === 'string' ? flags.base : 'main',
239
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
240
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
241
+ });
242
+ if (!report.ok) {
243
+ io.stderr.write(`Burnoff export error: ${report.error || 'failed'}\n`);
244
+ return 1;
245
+ }
246
+ const text = JSON.stringify(report, null, 2) + '\n';
247
+ writeOut(text, flags.out, io.stdout);
248
+ return 0;
249
+ }
250
+
183
251
  async function handleCiGate(flags, io) {
184
252
  const { evaluateCiBudgetGate, formatCiGateMarkdown } = await import('../src/ci/ci-gate.mjs');
185
253
  const result = evaluateCiBudgetGate({
186
254
  cwd: flags.cwd || process.cwd(),
187
- homeDir: flags.home || getHomeDir(),
255
+ homeDir: flags.home || undefined,
188
256
  base: typeof flags.base === 'string' ? flags.base : 'main',
189
257
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
190
258
  inputPath: typeof flags.input === 'string' ? flags.input : undefined,
@@ -209,10 +277,29 @@ async function handleCiGate(flags, io) {
209
277
 
210
278
  async function handleTeamDigest(flags, io) {
211
279
  const { buildTeamDigest, formatTeamDigest } = await import('../src/ci/team-digest.mjs');
280
+ const { buildPrCostAttribution } = await import('../src/ci/pr-cost.mjs');
281
+ const cwd = flags.cwd || process.cwd();
282
+ const homeDir = flags.home || undefined;
283
+ const prReports = [];
284
+ try {
285
+ const prReport = buildPrCostAttribution({
286
+ cwd,
287
+ homeDir,
288
+ base: typeof flags.base === 'string' ? flags.base : 'main',
289
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
290
+ fallbackToRecent: true
291
+ });
292
+ if (prReport?.ok) {
293
+ prReports.push(prReport);
294
+ }
295
+ } catch {
296
+ // ignore: non-git workspace or unavailable git history falls back to session telemetry
297
+ }
212
298
  const digest = buildTeamDigest({
213
- cwd: flags.cwd || process.cwd(),
214
- homeDir: flags.home || getHomeDir(),
215
- days: flags.days ? Number(flags.days) : 7
299
+ cwd,
300
+ homeDir,
301
+ days: flags.days ? Number(flags.days) : 7,
302
+ prReports
216
303
  });
217
304
  const text = flags.json ? JSON.stringify(digest, null, 2) + '\n' : formatTeamDigest(digest);
218
305
  writeOut(text, flags.out, io.stdout);
@@ -235,20 +322,20 @@ async function handleSearch(positionals, flags, io) {
235
322
  turnId,
236
323
  keyword,
237
324
  limit: flags.limit ? Number(flags.limit) : 10,
238
- homeDir: flags.home || getHomeDir()
325
+ homeDir: flags.home || undefined
239
326
  };
240
327
  let res;
241
328
  if (typeof flags.db === 'string' && flags.db) {
242
329
  res = await searchToolLogsFts5(path.resolve(flags.db), searchOpts);
243
330
  } else {
244
- const wsDbPath = path.join(path.resolve(flags.cwd || process.cwd()), '.claude', 'cache', 'tool_logs_fts5.db');
245
- if (fs.existsSync(wsDbPath)) {
246
- res = await searchToolLogsFts5(wsDbPath, searchOpts);
247
- }
331
+ res = await searchToolLogsFts5(null, searchOpts);
248
332
  if (!res || !res.matchedLines || res.matchedLines.length === 0) {
249
- const homeRes = await searchToolLogsFts5(null, searchOpts);
250
- if (!res || (homeRes.matchedLines && homeRes.matchedLines.length > 0)) {
251
- res = homeRes;
333
+ const wsDbPath = path.join(path.resolve(flags.cwd || process.cwd()), '.claude', 'cache', 'tool_logs_fts5.db');
334
+ if (fs.existsSync(wsDbPath)) {
335
+ const wsRes = await searchToolLogsFts5(wsDbPath, searchOpts);
336
+ if (wsRes.matchedLines && wsRes.matchedLines.length > 0) {
337
+ res = wsRes;
338
+ }
252
339
  }
253
340
  }
254
341
  }
@@ -269,7 +356,7 @@ async function handleSearch(positionals, flags, io) {
269
356
  async function handleDaemon(positionals, flags, io) {
270
357
  const sub = String(positionals[1] || 'status').toLowerCase();
271
358
  const cwd = path.resolve(flags.cwd || process.cwd());
272
- const homeDir = flags.home || getHomeDir();
359
+ const homeDir = typeof flags.home === 'string' && flags.home.trim() ? flags.home.trim() : undefined;
273
360
  const { sendDaemonRpc, resolveFastIpcPipePath } = await import('../src/ipc/fast-client.mjs');
274
361
  const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: flags.ipc });
275
362
 
@@ -321,9 +408,11 @@ async function handleDaemon(positionals, flags, io) {
321
408
  }
322
409
 
323
410
  const cliEntry = path.join(PACKAGE_ROOT, 'bin', 'burnoff.mjs');
411
+ const spawnArgs = [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--ipc', ipcPath];
412
+ if (homeDir) spawnArgs.push('--home', homeDir);
324
413
  const child = spawn(
325
414
  process.execPath,
326
- [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--ipc', ipcPath],
415
+ spawnArgs,
327
416
  {
328
417
  cwd,
329
418
  detached: true,
@@ -332,7 +421,15 @@ async function handleDaemon(positionals, flags, io) {
332
421
  }
333
422
  );
334
423
  child.unref();
335
- io.stdout.write(`Burnoff daemon started (pid=${child.pid}, ipc=${ipcPath})\n`);
424
+ let readyPing = null;
425
+ for (let attempt = 0; attempt < 16; attempt += 1) {
426
+ readyPing = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 100 });
427
+ if (readyPing?.pong) break;
428
+ await new Promise((r) => setTimeout(r, 50));
429
+ }
430
+ io.stdout.write(
431
+ `Burnoff daemon started (pid=${readyPing?.pid || child.pid}, ipc=${ipcPath}, ready=${Boolean(readyPing?.pong)})\n`
432
+ );
336
433
  return 0;
337
434
  }
338
435
 
@@ -376,6 +473,8 @@ export async function runCli(argv = process.argv.slice(2), io = { stdout: proces
376
473
  return handleAudit(flags, io);
377
474
  case 'pr-cost':
378
475
  return handlePrCost(flags, io);
476
+ case 'export':
477
+ return handleExport(flags, io);
379
478
  case 'ci-gate':
380
479
  return handleCiGate(flags, io);
381
480
  case 'team-digest':
package/hooks/hook-io.mjs CHANGED
@@ -7,8 +7,9 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
+ import { getWorkspaceStateDir } from '../src/config/paths.mjs';
10
11
 
11
- const BOUNDED_READ_TOOL_RE = /^(?:default_api:)?(?:Read|read_file|view_file)$/i;
12
+ const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
12
13
  const SENSITIVE_SEGMENT_RE =
13
14
  /(?:^|[\\/])(?:\.env(?:\.[^\\/]*)?|\.git|\.ssh|\.aws|\.gnupg|\.npmrc|\.pypirc|\.netrc|id_rsa(?:\..*)?|id_dsa(?:\..*)?|id_ecdsa(?:\..*)?|id_ed25519(?:\..*)?|oauth_creds\.json|credentials\.json|[^\\/]*(?:secret|credential|token)[^\\/]*|CLAUDE\.md|AGENTS\.md)(?:[\\/]|$)/i;
14
15
  const BINARY_OR_MULTIMODAL_EXT_RE =
@@ -379,7 +380,7 @@ export function recordHookTrace(eventName, payload = {}, details = {}) {
379
380
  * Returns `false` whenever any active guard, lock, breaker failure state, policy file,
380
381
  * or read-interval overlap could require full evaluation.
381
382
  */
382
- export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
383
+ export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null } = {}) {
383
384
  if (!payload || typeof payload !== 'object') return false;
384
385
  if (payload.shieldForceActive || payload.shieldConfig || payload.consecutiveFailures) {
385
386
  return false;
@@ -391,21 +392,18 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
391
392
  const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
392
393
  if (!tIn || typeof tIn !== 'object') return false;
393
394
 
394
- const hasBounds =
395
- (tIn.StartLine !== undefined && tIn.StartLine !== null) ||
396
- (tIn.start_line !== undefined && tIn.start_line !== null) ||
397
- (tIn.EndLine !== undefined && tIn.EndLine !== null) ||
398
- (tIn.end_line !== undefined && tIn.end_line !== null) ||
399
- (tIn.offset !== undefined && tIn.offset !== null) ||
400
- (tIn.limit !== undefined && tIn.limit !== null);
401
- if (!hasBounds) return false;
395
+ const hasUpperLimit =
396
+ (tIn.limit !== undefined && tIn.limit !== null) ||
397
+ ((tIn.StartLine !== undefined || tIn.start_line !== undefined) &&
398
+ (tIn.EndLine !== undefined || tIn.end_line !== undefined));
399
+ if (!hasUpperLimit) return false;
402
400
 
403
401
  const limitNum = Number(tIn.limit);
404
402
  const startNum = Number(tIn.StartLine ?? tIn.start_line);
405
403
  const endNum = Number(tIn.EndLine ?? tIn.end_line);
406
404
  if (
407
- (Number.isFinite(limitNum) && limitNum > 150) ||
408
- (Number.isFinite(startNum) && Number.isFinite(endNum) && endNum - startNum + 1 > 150)
405
+ (tIn.limit !== undefined && tIn.limit !== null && (!Number.isFinite(limitNum) || limitNum <= 0 || limitNum > 150)) ||
406
+ (Number.isFinite(startNum) && Number.isFinite(endNum) && (endNum < startNum || endNum - startNum + 1 > 150))
409
407
  ) {
410
408
  return false;
411
409
  }
@@ -445,19 +443,30 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
445
443
  ) {
446
444
  return false;
447
445
  }
448
- if (fs.existsSync(path.join(baseCwd, '.claude', 'locks', 'active_scopes.json'))) {
446
+
447
+ const wsStateDir = getWorkspaceStateDir(baseCwd, homeDir);
448
+ if (
449
+ fs.existsSync(path.join(baseCwd, '.claude', 'locks', 'active_scopes.json')) ||
450
+ fs.existsSync(path.join(wsStateDir, 'active_scopes.json'))
451
+ ) {
449
452
  return false;
450
453
  }
451
454
 
452
- const sessionId = String(payload.session_id || payload.sessionId || 'default');
455
+ const sessionId = String(payload.session_id || payload.sessionId || payload.conversationId || 'default');
453
456
  const safeSid = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
454
- const breakerPath = path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
455
- if (fs.existsSync(breakerPath)) {
457
+ if (
458
+ fs.existsSync(path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`)) ||
459
+ fs.existsSync(path.join(wsStateDir, `burnoff_breaker_state_${safeSid}.json`))
460
+ ) {
456
461
  return false;
457
462
  }
458
463
 
459
- const snapPath = path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`);
460
- if (fs.existsSync(snapPath)) {
464
+ const snapCandidates = [
465
+ path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`),
466
+ path.join(wsStateDir, `read_snapshots_${safeSid.slice(0, 64)}.json`)
467
+ ];
468
+ for (const snapPath of snapCandidates) {
469
+ if (!fs.existsSync(snapPath)) continue;
461
470
  try {
462
471
  const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
463
472
  const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);