burnoff 1.1.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 (38) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  2. package/README.md +66 -78
  3. package/bin/burnoff.mjs +67 -23
  4. package/hooks/hook-io.mjs +19 -7
  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 +7 -5
  9. package/src/ci/ci-gate.mjs +22 -0
  10. package/src/ci/pr-cost.mjs +42 -10
  11. package/src/ci/team-digest.mjs +5 -3
  12. package/src/cli/audit.mjs +103 -18
  13. package/src/cli/doctor.mjs +209 -14
  14. package/src/cli/init.mjs +349 -96
  15. package/src/cli/startup-audit.mjs +500 -24
  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/loader.mjs +11 -4
  20. package/src/config/paths.mjs +62 -2
  21. package/src/config/policy.mjs +34 -5
  22. package/src/config/pricing.mjs +16 -5
  23. package/src/guards/loop-breaker.mjs +198 -13
  24. package/src/guards/post-tool-engine.mjs +289 -29
  25. package/src/guards/pre-tool-engine.mjs +336 -129
  26. package/src/guards/read-clamp.mjs +78 -18
  27. package/src/guards/session-hook.mjs +207 -0
  28. package/src/guards/shell-guard.mjs +583 -73
  29. package/src/ipc/daemon.mjs +50 -8
  30. package/src/ipc/fast-client.mjs +62 -5
  31. package/src/ipc/protocol.mjs +1 -1
  32. package/src/storage/antigravity-parser.mjs +258 -0
  33. package/src/storage/file-lock.mjs +13 -4
  34. package/src/storage/fts5-archive.mjs +4 -4
  35. package/src/storage/jsonl-parser.mjs +7 -1
  36. package/src/storage/ledger.mjs +10 -3
  37. package/src/storage/sqlite-client.mjs +4 -2
  38. package/hooks/hooks.json +0 -12
@@ -30,13 +30,13 @@ jobs:
30
30
  if [ -s .burnoff-ci/provider-usage.json ]; then
31
31
  USAGE_FLAG="--provider-usage .burnoff-ci/provider-usage.json"
32
32
  fi
33
- npx -y burnoff@1.1.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --json --out .burnoff-ci/pr-cost.json
34
- npx -y burnoff@1.1.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --markdown --out .burnoff-ci/pr-cost.md
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
35
 
36
36
  - name: Enforce CI Token-Budget Gate
37
37
  id: gate
38
38
  run: |
39
- npx -y burnoff@1.1.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations --out .burnoff-ci/ci-gate.md
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
40
  cat .burnoff-ci/pr-cost.md >> "$GITHUB_STEP_SUMMARY"
41
41
  cat .burnoff-ci/ci-gate.md >> "$GITHUB_STEP_SUMMARY"
42
42
  echo "summary_path=.burnoff-ci/pr-cost.md" >> "$GITHUB_OUTPUT"
package/README.md CHANGED
@@ -1,124 +1,118 @@
1
1
  # Burnoff
2
2
 
3
- **Burnoff CI — Infracost-style AI spend gates, Turn-0 config linting, deterministic circuit breakers, and bounded file-read guards for Claude Code teams.**
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 gives engineering teams deterministic local guardrails and enforceable pull-request cost governance for Claude Code — stopping runaway failure loops, blocking destructive shell commands and credential leaks, bounding oversized file reads, linting Turn-0 startup bloat, and gating PR AI spend in GitHub Actions.
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
- - **Infracost-Style PR Spend Gates:** Correlates branch commits to Claude Code session spend, optionally reconciles against provider billing exports (`--provider-usage`), and enforces `.burnoff.yaml` budgets in GitHub Actions without touching shared `.claude/settings.json`.
10
- - **Turn-0 Startup Config Linter:** Audits `.mcp.json`, Claude Code settings, rule files, and tool bloat before a session starts, flagging reclaimable per-turn prompt overhead and misconfigurations.
11
- - **Deterministic Runaway Loop Breaker:** Halts repeating tool or command failure loops after 3 consecutive identical failures using cross-process state locking, exempting read-only recovery steps and resetting cleanly on success or `git stash`.
12
- - **Destructive Shell & Credential Guards:** Blocks high-risk shell/git commands (`git push --force`, `--no-verify`, `rm -rf`) and sensitive credential/env reads (allowing `.env.example` templates), while routing reversible resets through interactive confirmation.
13
- - **Bounded File-Read & CLI Output Guards:** Clamps oversized non-code reads (`250 lines / 16 KB`), skips overlapping re-reads, leaves active source files unclamped, and archives verbose test/build stdout into local SQLite FTS5 (`burnoff search`) while preserving critical failure lines.
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
15
  ## Requirements & Scope
16
16
 
17
- - **Supported Agent:** Designed specifically for **Claude Code** (`v1.1.0` supports Claude Code only).
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 atomic JSONL fallback mode).
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
19
  - **Dependencies:** **Zero runtime npm dependencies.**
20
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`) |
32
+
21
33
  ## Quickstart
22
34
 
23
- Install Burnoff in your project (or globally), preview changes, wire Claude Code hooks, and run your Turn-0 health & startup audit:
35
+ Install Burnoff in your project, preview changes, wire hooks, and run your Turn-0 health & startup audit:
24
36
 
25
37
  ```bash
26
38
  npm i -D burnoff
27
39
  npx burnoff init --dry-run
28
- npx burnoff init
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
29
44
  npx burnoff audit --startup
30
45
  npx burnoff doctor
46
+ npx burnoff doctor --gc # Prune >14d caches & rotate prior-month ledger
31
47
  ```
32
48
 
33
49
  Remove hooks cleanly at any time:
34
50
 
35
51
  ```bash
36
52
  npx burnoff uninstall
53
+ npx burnoff uninstall --client antigravity [--global]
37
54
  ```
38
55
 
39
- ## Verified `v1.1.0` Output Samples
56
+ ## Smoke Test (`PreToolUse` exit `2`)
40
57
 
41
- ### 1. Turn-0 Startup Config Audit (`burnoff audit --startup`)
58
+ Verify that the `PreToolUse` guard blocks secret reads before execution:
42
59
 
43
- ```text
44
- Burnoff Claude Code Turn-0 Startup Audit | Findings: 2 | Reclaimable: ~14,500 tok/turn (est.) (~$1.01/wk)
45
- - MCP startup tax: 0 tok/turn (deferred loading active)
46
- - [pass] Chrome default disabled (or actively used)
47
- - [warn] Artifact built-in tool active (cli, 0 calls in 7d, ~8500 tok/turn est.)
48
- Note: Setting enableArtifact: false in settings.json is a one-way global lock and cannot be re-enabled per session with --settings.
49
- Fix (never use): Set "enableArtifact": false in ~/.claude/settings.json (permanent one-way global lock).
50
- Fix (occasional): Leave "enableArtifact" unset and run terminal coding with: claude --disallowedTools Artifact
51
- - [warn] Bundled skills/workflows enabled (~6000 tok/turn est.)
52
- Fix: Set "disableBundledSkills": true and "disableWorkflows": true in ~/.claude/settings.json (or pass per-session: claude --settings '{"disableBundledSkills":true,"disableWorkflows":true}').
53
- - Rules [pass]: 1 file(s), 1 discrete rules, ~13 est. tokens
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=$?"
54
62
  ```
55
63
 
56
- ### 2. Deterministic Secret & Destructive Guard Block (`PreToolUse` exit `2`)
64
+ Expected output:
57
65
 
58
66
  ```text
59
- $ echo '{"session_id":"smoke-1","tool_name":"Bash","tool_input":{"command":"cat .env;echo ok"}}' | npx burnoff-pretool
60
67
  [Burnoff DET-02 Secret & Credential Boundary] Access to sensitive credential path ".env" is blocked. (.env.example / .env.sample are permitted.)
61
- # exits with code 2 before execution
68
+ exit=2
62
69
  ```
63
70
 
64
- ### 3. PR Cost Attribution & CI Budget Gate (`pr-cost` + `ci-gate --strict`)
71
+ ## Measured Hook Latency & `Read`-Clamp Savings
65
72
 
66
- ```markdown
67
- ### Burnoff PR Token & Cost Attribution (`HEAD~1..HEAD`)
73
+ Measured directly on **Windows (`win32`, Node `v25.6.0`)** (reproduce locally with `npm run test:bench`):
68
74
 
69
- | Metric | Value |
70
- | :--- | :--- |
71
- | **Commits / Files Changed** | `1` commits · `1` files (`+1 / -0`) |
72
- | **Total Attributed Tokens** | `0.0k` |
73
- | **Cache Hit Rate** | `0%` |
74
- | **Estimated PR AI Cost** | `$0.0000` (`$0.0000 / 100 LOC`) |
75
- | **Preventable Waste Ratio** | `0%` (`0.0k` tok) |
76
- | **Estimated Saved USD** | `$0.0172` |
77
- | **Ring-0 Violations** | `1` |
78
-
79
- ### Burnoff CI / PR Token-Budget Gate: **FAIL** (`mode: enforce`)
80
-
81
- | Check | Actual | Limit | Status |
82
- | :--- | :---: | :---: | :---: |
83
- | `MAX_PR_COST_USD` | `$0.0000` | `<=$15.00` | **PASS** |
84
- | `MAX_PR_TOKENS` | `0` | `<=1,500,000` | **PASS** |
85
- | `MIN_CACHE_HIT_PCT` | `0%` | `>=50%` | **PASS** |
86
- | `MAX_WASTE_RATIO_PCT` | `0%` | `<=35%` | **PASS** |
87
- | `MAX_RING0_VIOLATIONS` | `1` | `<=0` | **FAIL** |
88
-
89
- #### Notices
90
-
91
- - **MISSING_TRANSCRIPTS**: No Claude Code session transcripts matched this PR window (0 tokens attributed). Upload .burnoff-ci/provider-usage.json or session transcripts, or set failOnMissingTranscripts: true to enforce.
92
- ```
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.
93
85
 
94
86
  ## Local-Only Trust & Privacy
95
87
 
96
- Burnoff runs 100% locally via Claude Code hook subprocesses and local CLI commands:
88
+ Burnoff runs 100% locally via hook subprocesses and local CLI commands:
97
89
 
98
90
  - **Zero outbound network calls & zero proxy/MITM:** Your prompts, source code, and credentials never leave your machine.
99
91
  - **Exact paths touched:**
100
- - `~/.burnoff/` (or `$BURNOFF_HOME`): savings ledger, loop-breaker state, read-interval snapshots, FTS5/fallback CLI log archive, and optional local warm daemon socket/pipe.
101
- - `.claude/settings.local.json`: repo-local hook wiring only (never modifies shared `.claude/settings.json`).
102
- - `.git/info/exclude`: ignores `.claude/settings.local.json` privately so `git status` stays spotless without touching `.gitignore`.
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`.
103
97
 
104
98
  ## CLI Commands
105
99
 
106
100
  | Command | Purpose |
107
101
  | :--- | :--- |
108
- | `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`. |
109
103
  | `burnoff uninstall [--dry-run]` | Remove Burnoff hooks and `.git/info/exclude` block. |
110
104
  | `burnoff doctor [--gc] [--json]` | Inspect Node/SQLite FTS5, `.burnoff.yaml`, hook wiring, warm daemon, ledger, and prune >14d caches with `--gc`. |
111
105
  | `burnoff audit --startup [--json]` | Run the Turn-0 startup config linter across `.mcp.json`, Claude Code settings, and rule files. |
112
- | `burnoff audit [--session <file>] [--json]` | Parse Claude Code JSONL transcripts (`~/.claude/projects/`) and report per-session cost, cache hit %, and >200k-cliff turns. |
106
+ | `burnoff audit [--session <file>] [--json]` | Parse local JSONL transcripts (`~/.claude/projects/`) and report per-session cost, cache hit %, and >200k-cliff turns. |
113
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. |
114
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`). |
115
- | `burnoff team-digest [--days 7]` | Output a 5-line weekly Engineering Manager summary of spend, cache efficiency, top cost driver, and guard savings. |
109
+ | `burnoff team-digest [--days 7]` | Output a 5-line weekly summary of local spend, cache efficiency, top cost driver, and guard savings. |
116
110
  | `burnoff search <turnId> [keyword]` | Search archived FTS5 CLI output without re-running expensive test or build commands. |
117
111
  | `burnoff daemon <start\|stop\|status>` | Manage the workspace-scoped warm IPC daemon (`~/.burnoff/run/` or Windows named pipe). |
118
112
 
119
- ## Team Policy (`.burnoff.yaml`)
113
+ ## For Teams: Repo Policy & GitHub Actions
120
114
 
121
- 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:
122
116
 
123
117
  ```yaml
124
118
  guards:
@@ -126,6 +120,11 @@ guards:
126
120
  det04Threshold: 3
127
121
  strictTestIntegrity: false
128
122
  scopeLockEnabled: true
123
+ subagentFanoutEnabled: true
124
+ subagentFanoutAction: advisory
125
+ subagentMaxBurstCount: 4
126
+ subagentBurstWindowSec: 60
127
+ subagentMaxPromptChars: 8000
129
128
 
130
129
  readClamp:
131
130
  enabled: true
@@ -148,24 +147,13 @@ ciBudgetGate:
148
147
  failOnMissingTranscripts: false
149
148
  ```
150
149
 
151
- ## GitHub Actions PR Gate
152
-
153
- 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.1.0`:
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`:
154
151
 
155
- - Runs `npx -y burnoff@1.1.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`.
156
- - Runs `npx -y burnoff@1.1.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations`.
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`.
157
154
  - Appends the Markdown breakdown to `$GITHUB_STEP_SUMMARY` and posts non-fork PR summary comments.
158
155
 
159
- ## Burnoff Team Cloud (Waitlist)
160
-
161
- Need organization-wide AI spend governance across repositories without syncing local developer transcripts into CI artifacts?
162
-
163
- - **Pricing:** `$19 / active AI-committing dev / mo` (10-seat minimum = `$190/mo` floor).
164
- - **Org-Wide Governance:** Centralized `.burnoff.yaml` policy enforcement and branch-protection status checks across all repositories.
165
- - **Provider Billing Reconciliation:** Automated Anthropic Admin API, AWS Bedrock, and Google Vertex AI invoice reconciliation against PR attribution.
166
- - **Executive Reporting:** Scheduled Slack weekly Engineering Manager digests (`team-digest`) and cache-efficiency alerts.
167
-
168
- Open an issue titled `[Waitlist] Burnoff Team Cloud` in the repository to request early access.
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.
169
157
 
170
158
  ## Environment Variables
171
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,7 +27,7 @@ function getPackageVersion() {
28
27
  } catch (err) {
29
28
  void err; // ignore: package.json read fallback
30
29
  }
31
- return '1.1.0';
30
+ return '1.2.0';
32
31
  }
33
32
 
34
33
  const BOOLEAN_FLAGS = new Set([
@@ -41,6 +40,7 @@ const BOOLEAN_FLAGS = new Set([
41
40
  'startup',
42
41
  'foreground',
43
42
  'skip-daemon',
43
+ 'global',
44
44
  'help',
45
45
  'version'
46
46
  ]);
@@ -92,17 +92,18 @@ function writeOut(text, outPath, stream = process.stdout) {
92
92
 
93
93
  function formatHelp() {
94
94
  return [
95
- `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`,
96
96
  '',
97
97
  'Usage:',
98
98
  ' burnoff <command> [options]',
99
99
  '',
100
100
  'Commands:',
101
- ' init [--dry-run] [--cwd <dir>] Install PreToolUse/PostToolUse hooks in .claude/settings.local.json',
102
- ' 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',
103
103
  ' doctor [--gc] [--json] Run Node/SQLite/hooks/daemon/FTS5/ledger diagnostics',
104
- ' audit [--startup] [--session <file>] [--json] Audit Claude Code JSONL transcripts or Turn-0 startup config',
105
- ' 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',
106
107
  ' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
107
108
  ' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
108
109
  ' search <turnId> [keyword] Query archived FTS5 tool outputs',
@@ -119,13 +120,21 @@ async function handleInit(flags, io) {
119
120
  const { initBurnoff } = await import('../src/cli/init.mjs');
120
121
  const res = initBurnoff({
121
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),
122
126
  dryRun: Boolean(flags['dry-run'])
123
127
  });
124
128
  if (flags.json) {
125
129
  io.stdout.write(JSON.stringify(res, null, 2) + '\n');
126
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
+ }
127
136
  io.stdout.write(
128
- `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${res.settingsPath}\n` +
137
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${targets.join(' and ')}\n` +
129
138
  (res.excludePath ? ` git exclude: ${res.excludePath}\n` : '') +
130
139
  (Array.isArray(res.warnings) && res.warnings.length > 0
131
140
  ? res.warnings.map((w) => ` warning: ${w}\n`).join('')
@@ -139,13 +148,21 @@ async function handleUninstall(flags, io) {
139
148
  const { uninstallBurnoff } = await import('../src/cli/init.mjs');
140
149
  const res = uninstallBurnoff({
141
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),
142
154
  dryRun: Boolean(flags['dry-run'])
143
155
  });
144
156
  if (flags.json) {
145
157
  io.stdout.write(JSON.stringify(res, null, 2) + '\n');
146
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
+ }
147
164
  io.stdout.write(
148
- `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${res.settingsPath}\n`
165
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${targets.join(' and ')}\n`
149
166
  );
150
167
  }
151
168
  return 0;
@@ -155,7 +172,7 @@ async function handleDoctor(flags, io) {
155
172
  const { runDoctor, formatDoctorReport } = await import('../src/cli/doctor.mjs');
156
173
  const report = await runDoctor({
157
174
  cwd: flags.cwd || process.cwd(),
158
- homeDir: flags.home || getHomeDir(),
175
+ homeDir: flags.home || undefined,
159
176
  gc: Boolean(flags.gc),
160
177
  skipDaemonCheck: Boolean(flags['skip-daemon'])
161
178
  });
@@ -165,21 +182,24 @@ async function handleDoctor(flags, io) {
165
182
  }
166
183
 
167
184
  async function handleAudit(flags, io) {
185
+ const clientOpt = typeof flags.client === 'string' ? flags.client : 'auto';
168
186
  if (flags.startup) {
169
- const { runClaudeStartupAudit, formatClaudeStartupAuditReport } = await import('../src/cli/startup-audit.mjs');
170
- const report = runClaudeStartupAudit({
187
+ const { runStartupAudit, formatStartupAuditReport } = await import('../src/cli/startup-audit.mjs');
188
+ const report = runStartupAudit({
171
189
  cwd: flags.cwd || process.cwd(),
172
- homeDir: flags.home || getHomeDir(),
173
- days: flags.days ? Number(flags.days) : 7
190
+ homeDir: flags.home || undefined,
191
+ days: flags.days ? Number(flags.days) : 7,
192
+ client: clientOpt
174
193
  });
175
- const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatClaudeStartupAuditReport(report);
194
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatStartupAuditReport(report);
176
195
  writeOut(text, flags.out, io.stdout);
177
196
  return 0;
178
197
  }
179
198
  const { auditClaudeSessions, formatAuditReport } = await import('../src/cli/audit.mjs');
180
199
  const report = auditClaudeSessions({
181
200
  cwd: flags.cwd || process.cwd(),
182
- homeDir: flags.home || getHomeDir(),
201
+ homeDir: flags.home || undefined,
202
+ client: clientOpt,
183
203
  sessionPath: typeof flags.session === 'string' ? flags.session : undefined,
184
204
  limit: flags.limit ? Number(flags.limit) : undefined
185
205
  });
@@ -192,7 +212,8 @@ async function handlePrCost(flags, io) {
192
212
  const { buildPrCostAttribution, formatPrAttributionMarkdown } = await import('../src/ci/pr-cost.mjs');
193
213
  const report = buildPrCostAttribution({
194
214
  cwd: flags.cwd || process.cwd(),
195
- homeDir: flags.home || getHomeDir(),
215
+ homeDir: flags.home || undefined,
216
+ client: typeof flags.client === 'string' ? flags.client : 'auto',
196
217
  base: typeof flags.base === 'string' ? flags.base : 'main',
197
218
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
198
219
  providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
@@ -208,11 +229,30 @@ async function handlePrCost(flags, io) {
208
229
  return 0;
209
230
  }
210
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
+
211
251
  async function handleCiGate(flags, io) {
212
252
  const { evaluateCiBudgetGate, formatCiGateMarkdown } = await import('../src/ci/ci-gate.mjs');
213
253
  const result = evaluateCiBudgetGate({
214
254
  cwd: flags.cwd || process.cwd(),
215
- homeDir: flags.home || getHomeDir(),
255
+ homeDir: flags.home || undefined,
216
256
  base: typeof flags.base === 'string' ? flags.base : 'main',
217
257
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
218
258
  inputPath: typeof flags.input === 'string' ? flags.input : undefined,
@@ -239,7 +279,7 @@ async function handleTeamDigest(flags, io) {
239
279
  const { buildTeamDigest, formatTeamDigest } = await import('../src/ci/team-digest.mjs');
240
280
  const { buildPrCostAttribution } = await import('../src/ci/pr-cost.mjs');
241
281
  const cwd = flags.cwd || process.cwd();
242
- const homeDir = flags.home || getHomeDir();
282
+ const homeDir = flags.home || undefined;
243
283
  const prReports = [];
244
284
  try {
245
285
  const prReport = buildPrCostAttribution({
@@ -282,7 +322,7 @@ async function handleSearch(positionals, flags, io) {
282
322
  turnId,
283
323
  keyword,
284
324
  limit: flags.limit ? Number(flags.limit) : 10,
285
- homeDir: flags.home || getHomeDir()
325
+ homeDir: flags.home || undefined
286
326
  };
287
327
  let res;
288
328
  if (typeof flags.db === 'string' && flags.db) {
@@ -316,7 +356,7 @@ async function handleSearch(positionals, flags, io) {
316
356
  async function handleDaemon(positionals, flags, io) {
317
357
  const sub = String(positionals[1] || 'status').toLowerCase();
318
358
  const cwd = path.resolve(flags.cwd || process.cwd());
319
- const homeDir = flags.home || getHomeDir();
359
+ const homeDir = typeof flags.home === 'string' && flags.home.trim() ? flags.home.trim() : undefined;
320
360
  const { sendDaemonRpc, resolveFastIpcPipePath } = await import('../src/ipc/fast-client.mjs');
321
361
  const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: flags.ipc });
322
362
 
@@ -368,9 +408,11 @@ async function handleDaemon(positionals, flags, io) {
368
408
  }
369
409
 
370
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);
371
413
  const child = spawn(
372
414
  process.execPath,
373
- [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--home', homeDir, '--ipc', ipcPath],
415
+ spawnArgs,
374
416
  {
375
417
  cwd,
376
418
  detached: true,
@@ -431,6 +473,8 @@ export async function runCli(argv = process.argv.slice(2), io = { stdout: proces
431
473
  return handleAudit(flags, io);
432
474
  case 'pr-cost':
433
475
  return handlePrCost(flags, io);
476
+ case 'export':
477
+ return handleExport(flags, io);
434
478
  case 'ci-gate':
435
479
  return handleCiGate(flags, io);
436
480
  case 'team-digest':
package/hooks/hook-io.mjs CHANGED
@@ -7,6 +7,7 @@
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
12
  const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
12
13
  const SENSITIVE_SEGMENT_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;
@@ -442,19 +443,30 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
442
443
  ) {
443
444
  return false;
444
445
  }
445
- 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
+ ) {
446
452
  return false;
447
453
  }
448
454
 
449
- const sessionId = String(payload.session_id || payload.sessionId || 'default');
455
+ const sessionId = String(payload.session_id || payload.sessionId || payload.conversationId || 'default');
450
456
  const safeSid = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
451
- const breakerPath = path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
452
- 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
+ ) {
453
461
  return false;
454
462
  }
455
463
 
456
- const snapPath = path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`);
457
- 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;
458
470
  try {
459
471
  const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
460
472
  const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
@@ -15,6 +15,7 @@ import {
15
15
  tryTier1PostToolFastPath
16
16
  } from './hook-io.mjs';
17
17
  import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
18
+ import { getClientAdapter, normalizeHookEvent } from '../src/clients/detect.mjs';
18
19
 
19
20
  let _engineMod = null;
20
21
  if (!isCliEntrypoint(import.meta.url)) {
@@ -39,60 +40,56 @@ export function runPostToolUseHook(event = {}, options = {}) {
39
40
  return _engineMod.runPostToolUseHook(event, options);
40
41
  }
41
42
 
43
+ function emitPostToolResult(res, payload, traceBase, pathLabel, ioOverride) {
44
+ if (res.stdout) {
45
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: pathLabel, exitCode: 0 });
46
+ exitWithStdoutJson(res.stdout, ioOverride);
47
+ } else {
48
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: pathLabel, exitCode: 0 });
49
+ exitPassThrough(ioOverride.exitFn);
50
+ }
51
+ }
52
+
42
53
  export async function executePostToolUseCli(cliOptions = {}) {
43
54
  const readPayload = cliOptions.readPayload || readStdinJsonAsync;
44
55
  const ioOverride = cliOptions.ioOverride || {};
45
56
  let payload = {};
57
+ let detectedClient = 'claude-code';
46
58
  try {
47
59
  payload = await readPayload(cliOptions.timeoutMs);
60
+ const { client, adapter, canonical } = normalizeHookEvent(payload, cliOptions.hookOptions);
61
+ detectedClient = client;
48
62
  const hasCustomOptions = Boolean(cliOptions.runHook || cliOptions.hookOptions);
49
63
  const traceBase = { tracePath: cliOptions.tracePath };
50
64
 
51
65
  if (cliOptions.runHook) {
52
66
  const res = cliOptions.runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
53
- if (res.stdout) {
54
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'custom', exitCode: 0 });
55
- exitWithStdoutJson(res.stdout, ioOverride);
56
- } else {
57
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'custom', exitCode: 0 });
58
- exitPassThrough(ioOverride.exitFn);
59
- }
67
+ emitPostToolResult(res, payload, traceBase, 'custom', ioOverride);
60
68
  return;
61
69
  }
62
70
 
63
71
  if (!hasCustomOptions) {
64
- if (tryTier1PostToolFastPath(payload)) {
65
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'tier1_fast', exitCode: 0 });
66
- exitPassThrough(ioOverride.exitFn);
72
+ const tier1 = tryTier1PostToolFastPath(canonical);
73
+ if (tier1) {
74
+ const rendered = client === 'antigravity' ? adapter.renderPost(tier1) : tier1;
75
+ emitPostToolResult(rendered, payload, traceBase, 'tier1_fast', ioOverride);
67
76
  return;
68
77
  }
69
78
 
70
79
  const ipcRes = await tryFastDaemonRpc(
71
- 'hook.claude.postToolUse',
72
- { event: payload },
80
+ 'hook.postToolUse',
81
+ { client, event: payload },
73
82
  { ipcPath: cliOptions.ipcPath }
74
83
  );
75
84
  if (ipcRes && ipcRes.fullVerdict === true) {
76
- if (ipcRes.stdout) {
77
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'daemon_ipc', exitCode: 0 });
78
- exitWithStdoutJson(ipcRes.stdout, ioOverride);
79
- } else {
80
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'daemon_ipc', exitCode: 0 });
81
- exitPassThrough(ioOverride.exitFn);
82
- }
85
+ emitPostToolResult(ipcRes, payload, traceBase, 'daemon_ipc', ioOverride);
83
86
  return;
84
87
  }
85
88
  }
86
89
 
87
90
  const { runPostToolUseHook: runCore } = await import('../src/guards/post-tool-engine.mjs');
88
91
  const res = runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
89
- if (res.stdout) {
90
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'core', exitCode: 0 });
91
- exitWithStdoutJson(res.stdout, ioOverride);
92
- } else {
93
- recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'core', exitCode: 0 });
94
- exitPassThrough(ioOverride.exitFn);
95
- }
92
+ emitPostToolResult(res, payload, traceBase, 'core', ioOverride);
96
93
  } catch (err) {
97
94
  recordHookTrace('PostToolUse', payload, {
98
95
  tracePath: cliOptions.tracePath,
@@ -101,6 +98,16 @@ export async function executePostToolUseCli(cliOptions = {}) {
101
98
  exitCode: 0,
102
99
  error: err?.message || String(err)
103
100
  });
101
+ if (detectedClient === 'antigravity') {
102
+ const failRes = getClientAdapter(detectedClient).renderFailOpen(err?.message || String(err), 'PostToolUse');
103
+ const writeStderr =
104
+ ioOverride.stderrWrite ||
105
+ ioOverride.writeStderr ||
106
+ ((s) => globalThis.process?.stderr?.write?.(s));
107
+ writeStderr(failRes.stderr);
108
+ exitWithStdoutJson(failRes.stdout, ioOverride);
109
+ return;
110
+ }
104
111
  exitDiagnosticZero(err?.message || String(err), 'PostToolUse', ioOverride);
105
112
  }
106
113
  }