burnoff 1.0.0 → 1.1.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/.github/workflows/burnoff-pr-gate.yml +75 -0
- package/README.md +100 -14
- package/bin/burnoff.mjs +71 -16
- package/hooks/hook-io.mjs +8 -11
- package/package.json +3 -2
- package/src/ci/ci-gate.mjs +62 -9
- package/src/ci/pr-cost.mjs +167 -14
- package/src/ci/team-digest.mjs +1 -1
- package/src/cli/audit.mjs +74 -5
- package/src/cli/doctor.mjs +22 -12
- package/src/cli/init.mjs +92 -5
- package/src/cli/startup-audit.mjs +2348 -0
- package/src/config/catalog.json +188 -45
- package/src/config/loader.mjs +85 -9
- package/src/config/paths.mjs +30 -0
- package/src/config/policy.mjs +69 -12
- package/src/config/pricing.mjs +1022 -0
- package/src/config/uncached-attribution.mjs +719 -0
- package/src/guards/loop-breaker.mjs +72 -14
- package/src/guards/post-tool-engine.mjs +33 -12
- package/src/guards/pre-tool-engine.mjs +54 -2
- package/src/guards/read-clamp.mjs +73 -59
- package/src/guards/shell-guard.mjs +45 -19
- package/src/storage/atomic-io.mjs +2 -2
- package/src/storage/file-lock.mjs +53 -9
- package/src/storage/fts5-archive.mjs +27 -12
- package/src/storage/jsonl-parser.mjs +202 -19
- package/src/storage/ledger.mjs +7 -9
- package/src/storage/sqlite-client.mjs +31 -9
|
@@ -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.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
|
|
35
|
+
|
|
36
|
+
- name: Enforce CI Token-Budget Gate
|
|
37
|
+
id: gate
|
|
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
|
|
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,28 +1,32 @@
|
|
|
1
1
|
# Burnoff
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
**Burnoff CI — Infracost-style AI spend gates, Turn-0 config linting, deterministic circuit breakers, and bounded file-read guards for Claude Code teams.**
|
|
4
4
|
|
|
5
|
-
Burnoff
|
|
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.
|
|
6
6
|
|
|
7
7
|
## Why Burnoff?
|
|
8
8
|
|
|
9
|
-
- **
|
|
10
|
-
- **
|
|
11
|
-
- **
|
|
12
|
-
- **
|
|
13
|
-
- **
|
|
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.
|
|
14
14
|
|
|
15
|
-
## Requirements
|
|
15
|
+
## Requirements & Scope
|
|
16
16
|
|
|
17
|
-
- **
|
|
18
|
-
- **
|
|
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).
|
|
19
|
+
- **Dependencies:** **Zero runtime npm dependencies.**
|
|
19
20
|
|
|
20
21
|
## Quickstart
|
|
21
22
|
|
|
22
|
-
Install
|
|
23
|
+
Install Burnoff in your project (or globally), preview changes, wire Claude Code hooks, and run your Turn-0 health & startup audit:
|
|
23
24
|
|
|
24
25
|
```bash
|
|
26
|
+
npm i -D burnoff
|
|
27
|
+
npx burnoff init --dry-run
|
|
25
28
|
npx burnoff init
|
|
29
|
+
npx burnoff audit --startup
|
|
26
30
|
npx burnoff doctor
|
|
27
31
|
```
|
|
28
32
|
|
|
@@ -32,6 +36,71 @@ Remove hooks cleanly at any time:
|
|
|
32
36
|
npx burnoff uninstall
|
|
33
37
|
```
|
|
34
38
|
|
|
39
|
+
## Verified `v1.1.0` Output Samples
|
|
40
|
+
|
|
41
|
+
### 1. Turn-0 Startup Config Audit (`burnoff audit --startup`)
|
|
42
|
+
|
|
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
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 2. Deterministic Secret & Destructive Guard Block (`PreToolUse` exit `2`)
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
$ echo '{"session_id":"smoke-1","tool_name":"Bash","tool_input":{"command":"cat .env;echo ok"}}' | npx burnoff-pretool
|
|
60
|
+
[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
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 3. PR Cost Attribution & CI Budget Gate (`pr-cost` + `ci-gate --strict`)
|
|
65
|
+
|
|
66
|
+
```markdown
|
|
67
|
+
### Burnoff PR Token & Cost Attribution (`HEAD~1..HEAD`)
|
|
68
|
+
|
|
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
|
+
```
|
|
93
|
+
|
|
94
|
+
## Local-Only Trust & Privacy
|
|
95
|
+
|
|
96
|
+
Burnoff runs 100% locally via Claude Code hook subprocesses and local CLI commands:
|
|
97
|
+
|
|
98
|
+
- **Zero outbound network calls & zero proxy/MITM:** Your prompts, source code, and credentials never leave your machine.
|
|
99
|
+
- **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`.
|
|
103
|
+
|
|
35
104
|
## CLI Commands
|
|
36
105
|
|
|
37
106
|
| Command | Purpose |
|
|
@@ -39,9 +108,10 @@ npx burnoff uninstall
|
|
|
39
108
|
| `burnoff init [--dry-run]` | Wire `PreToolUse` and `PostToolUse` hooks in `.claude/settings.local.json` and update `.git/info/exclude`. |
|
|
40
109
|
| `burnoff uninstall [--dry-run]` | Remove Burnoff hooks and `.git/info/exclude` block. |
|
|
41
110
|
| `burnoff doctor [--gc] [--json]` | Inspect Node/SQLite FTS5, `.burnoff.yaml`, hook wiring, warm daemon, ledger, and prune >14d caches with `--gc`. |
|
|
42
|
-
| `burnoff audit
|
|
111
|
+
| `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. |
|
|
43
113
|
| `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`). |
|
|
114
|
+
| `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`). |
|
|
45
115
|
| `burnoff team-digest [--days 7]` | Output a 5-line weekly Engineering Manager summary of spend, cache efficiency, top cost driver, and guard savings. |
|
|
46
116
|
| `burnoff search <turnId> [keyword]` | Search archived FTS5 CLI output without re-running expensive test or build commands. |
|
|
47
117
|
| `burnoff daemon <start\|stop\|status>` | Manage the workspace-scoped warm IPC daemon (`~/.burnoff/run/` or Windows named pipe). |
|
|
@@ -75,11 +145,27 @@ ciBudgetGate:
|
|
|
75
145
|
maxWasteRatioPct: 35
|
|
76
146
|
maxRing0Violations: 0
|
|
77
147
|
mode: enforce
|
|
148
|
+
failOnMissingTranscripts: false
|
|
78
149
|
```
|
|
79
150
|
|
|
80
151
|
## GitHub Actions PR Gate
|
|
81
152
|
|
|
82
|
-
See [`.github/workflows/burnoff-pr-gate.yml`](.github/workflows/burnoff-pr-gate.yml) for a SHA-pinned, least-privilege (`permissions: contents: read`) workflow
|
|
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`:
|
|
154
|
+
|
|
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`.
|
|
157
|
+
- Appends the Markdown breakdown to `$GITHUB_STEP_SUMMARY` and posts non-fork PR summary comments.
|
|
158
|
+
|
|
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.
|
|
83
169
|
|
|
84
170
|
## Environment Variables
|
|
85
171
|
|
package/bin/burnoff.mjs
CHANGED
|
@@ -28,9 +28,23 @@ function getPackageVersion() {
|
|
|
28
28
|
} catch (err) {
|
|
29
29
|
void err; // ignore: package.json read fallback
|
|
30
30
|
}
|
|
31
|
-
return '1.
|
|
31
|
+
return '1.1.0';
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
const BOOLEAN_FLAGS = new Set([
|
|
35
|
+
'json',
|
|
36
|
+
'dry-run',
|
|
37
|
+
'gc',
|
|
38
|
+
'strict',
|
|
39
|
+
'github-annotations',
|
|
40
|
+
'markdown',
|
|
41
|
+
'startup',
|
|
42
|
+
'foreground',
|
|
43
|
+
'skip-daemon',
|
|
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 {
|
|
@@ -87,7 +101,7 @@ function formatHelp() {
|
|
|
87
101
|
' init [--dry-run] [--cwd <dir>] Install PreToolUse/PostToolUse hooks in .claude/settings.local.json',
|
|
88
102
|
' uninstall [--dry-run] [--cwd <dir>] Remove Burnoff hooks and .git/info/exclude entries',
|
|
89
103
|
' doctor [--gc] [--json] Run Node/SQLite/hooks/daemon/FTS5/ledger diagnostics',
|
|
90
|
-
' audit [--session <file>] [--json]
|
|
104
|
+
' audit [--startup] [--session <file>] [--json] Audit Claude Code JSONL transcripts or Turn-0 startup config',
|
|
91
105
|
' pr-cost [--base main] [--json|--markdown] Attribute branch commits to Claude Code token/USD cost',
|
|
92
106
|
' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
|
|
93
107
|
' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
|
|
@@ -112,7 +126,10 @@ async function handleInit(flags, io) {
|
|
|
112
126
|
} else {
|
|
113
127
|
io.stdout.write(
|
|
114
128
|
`Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${res.settingsPath}\n` +
|
|
115
|
-
(res.excludePath ? ` git exclude: ${res.excludePath}\n` : '')
|
|
129
|
+
(res.excludePath ? ` git exclude: ${res.excludePath}\n` : '') +
|
|
130
|
+
(Array.isArray(res.warnings) && res.warnings.length > 0
|
|
131
|
+
? res.warnings.map((w) => ` warning: ${w}\n`).join('')
|
|
132
|
+
: '')
|
|
116
133
|
);
|
|
117
134
|
}
|
|
118
135
|
return 0;
|
|
@@ -148,6 +165,17 @@ async function handleDoctor(flags, io) {
|
|
|
148
165
|
}
|
|
149
166
|
|
|
150
167
|
async function handleAudit(flags, io) {
|
|
168
|
+
if (flags.startup) {
|
|
169
|
+
const { runClaudeStartupAudit, formatClaudeStartupAuditReport } = await import('../src/cli/startup-audit.mjs');
|
|
170
|
+
const report = runClaudeStartupAudit({
|
|
171
|
+
cwd: flags.cwd || process.cwd(),
|
|
172
|
+
homeDir: flags.home || getHomeDir(),
|
|
173
|
+
days: flags.days ? Number(flags.days) : 7
|
|
174
|
+
});
|
|
175
|
+
const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatClaudeStartupAuditReport(report);
|
|
176
|
+
writeOut(text, flags.out, io.stdout);
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
151
179
|
const { auditClaudeSessions, formatAuditReport } = await import('../src/cli/audit.mjs');
|
|
152
180
|
const report = auditClaudeSessions({
|
|
153
181
|
cwd: flags.cwd || process.cwd(),
|
|
@@ -209,10 +237,29 @@ async function handleCiGate(flags, io) {
|
|
|
209
237
|
|
|
210
238
|
async function handleTeamDigest(flags, io) {
|
|
211
239
|
const { buildTeamDigest, formatTeamDigest } = await import('../src/ci/team-digest.mjs');
|
|
240
|
+
const { buildPrCostAttribution } = await import('../src/ci/pr-cost.mjs');
|
|
241
|
+
const cwd = flags.cwd || process.cwd();
|
|
242
|
+
const homeDir = flags.home || getHomeDir();
|
|
243
|
+
const prReports = [];
|
|
244
|
+
try {
|
|
245
|
+
const prReport = buildPrCostAttribution({
|
|
246
|
+
cwd,
|
|
247
|
+
homeDir,
|
|
248
|
+
base: typeof flags.base === 'string' ? flags.base : 'main',
|
|
249
|
+
head: typeof flags.head === 'string' ? flags.head : 'HEAD',
|
|
250
|
+
fallbackToRecent: true
|
|
251
|
+
});
|
|
252
|
+
if (prReport?.ok) {
|
|
253
|
+
prReports.push(prReport);
|
|
254
|
+
}
|
|
255
|
+
} catch {
|
|
256
|
+
// ignore: non-git workspace or unavailable git history falls back to session telemetry
|
|
257
|
+
}
|
|
212
258
|
const digest = buildTeamDigest({
|
|
213
|
-
cwd
|
|
214
|
-
homeDir
|
|
215
|
-
days: flags.days ? Number(flags.days) : 7
|
|
259
|
+
cwd,
|
|
260
|
+
homeDir,
|
|
261
|
+
days: flags.days ? Number(flags.days) : 7,
|
|
262
|
+
prReports
|
|
216
263
|
});
|
|
217
264
|
const text = flags.json ? JSON.stringify(digest, null, 2) + '\n' : formatTeamDigest(digest);
|
|
218
265
|
writeOut(text, flags.out, io.stdout);
|
|
@@ -241,14 +288,14 @@ async function handleSearch(positionals, flags, io) {
|
|
|
241
288
|
if (typeof flags.db === 'string' && flags.db) {
|
|
242
289
|
res = await searchToolLogsFts5(path.resolve(flags.db), searchOpts);
|
|
243
290
|
} else {
|
|
244
|
-
|
|
245
|
-
if (fs.existsSync(wsDbPath)) {
|
|
246
|
-
res = await searchToolLogsFts5(wsDbPath, searchOpts);
|
|
247
|
-
}
|
|
291
|
+
res = await searchToolLogsFts5(null, searchOpts);
|
|
248
292
|
if (!res || !res.matchedLines || res.matchedLines.length === 0) {
|
|
249
|
-
const
|
|
250
|
-
if (
|
|
251
|
-
|
|
293
|
+
const wsDbPath = path.join(path.resolve(flags.cwd || process.cwd()), '.claude', 'cache', 'tool_logs_fts5.db');
|
|
294
|
+
if (fs.existsSync(wsDbPath)) {
|
|
295
|
+
const wsRes = await searchToolLogsFts5(wsDbPath, searchOpts);
|
|
296
|
+
if (wsRes.matchedLines && wsRes.matchedLines.length > 0) {
|
|
297
|
+
res = wsRes;
|
|
298
|
+
}
|
|
252
299
|
}
|
|
253
300
|
}
|
|
254
301
|
}
|
|
@@ -323,7 +370,7 @@ async function handleDaemon(positionals, flags, io) {
|
|
|
323
370
|
const cliEntry = path.join(PACKAGE_ROOT, 'bin', 'burnoff.mjs');
|
|
324
371
|
const child = spawn(
|
|
325
372
|
process.execPath,
|
|
326
|
-
[cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--ipc', ipcPath],
|
|
373
|
+
[cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--home', homeDir, '--ipc', ipcPath],
|
|
327
374
|
{
|
|
328
375
|
cwd,
|
|
329
376
|
detached: true,
|
|
@@ -332,7 +379,15 @@ async function handleDaemon(positionals, flags, io) {
|
|
|
332
379
|
}
|
|
333
380
|
);
|
|
334
381
|
child.unref();
|
|
335
|
-
|
|
382
|
+
let readyPing = null;
|
|
383
|
+
for (let attempt = 0; attempt < 16; attempt += 1) {
|
|
384
|
+
readyPing = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 100 });
|
|
385
|
+
if (readyPing?.pong) break;
|
|
386
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
387
|
+
}
|
|
388
|
+
io.stdout.write(
|
|
389
|
+
`Burnoff daemon started (pid=${readyPing?.pid || child.pid}, ipc=${ipcPath}, ready=${Boolean(readyPing?.pong)})\n`
|
|
390
|
+
);
|
|
336
391
|
return 0;
|
|
337
392
|
}
|
|
338
393
|
|
package/hooks/hook-io.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import fs from 'node:fs';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { fileURLToPath } from 'node:url';
|
|
10
10
|
|
|
11
|
-
const BOUNDED_READ_TOOL_RE = /^(?:
|
|
11
|
+
const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
|
|
12
12
|
const SENSITIVE_SEGMENT_RE =
|
|
13
13
|
/(?:^|[\\/])(?:\.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
14
|
const BINARY_OR_MULTIMODAL_EXT_RE =
|
|
@@ -391,21 +391,18 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
|
|
|
391
391
|
const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
|
|
392
392
|
if (!tIn || typeof tIn !== 'object') return false;
|
|
393
393
|
|
|
394
|
-
const
|
|
395
|
-
(tIn.
|
|
396
|
-
(tIn.
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
(tIn.offset !== undefined && tIn.offset !== null) ||
|
|
400
|
-
(tIn.limit !== undefined && tIn.limit !== null);
|
|
401
|
-
if (!hasBounds) return false;
|
|
394
|
+
const hasUpperLimit =
|
|
395
|
+
(tIn.limit !== undefined && tIn.limit !== null) ||
|
|
396
|
+
((tIn.StartLine !== undefined || tIn.start_line !== undefined) &&
|
|
397
|
+
(tIn.EndLine !== undefined || tIn.end_line !== undefined));
|
|
398
|
+
if (!hasUpperLimit) return false;
|
|
402
399
|
|
|
403
400
|
const limitNum = Number(tIn.limit);
|
|
404
401
|
const startNum = Number(tIn.StartLine ?? tIn.start_line);
|
|
405
402
|
const endNum = Number(tIn.EndLine ?? tIn.end_line);
|
|
406
403
|
if (
|
|
407
|
-
(Number.isFinite(limitNum)
|
|
408
|
-
(Number.isFinite(startNum) && Number.isFinite(endNum) && endNum - startNum + 1 > 150)
|
|
404
|
+
(tIn.limit !== undefined && tIn.limit !== null && (!Number.isFinite(limitNum) || limitNum <= 0 || limitNum > 150)) ||
|
|
405
|
+
(Number.isFinite(startNum) && Number.isFinite(endNum) && (endNum < startNum || endNum - startNum + 1 > 150))
|
|
409
406
|
) {
|
|
410
407
|
return false;
|
|
411
408
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burnoff",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"bin/",
|
|
32
32
|
"hooks/",
|
|
33
33
|
"src/",
|
|
34
|
+
".github/workflows/burnoff-pr-gate.yml",
|
|
34
35
|
"LICENSE",
|
|
35
36
|
"README.md"
|
|
36
37
|
],
|
|
@@ -39,6 +40,6 @@
|
|
|
39
40
|
"test": "node --test test/*.test.mjs",
|
|
40
41
|
"test:bench": "node --test test/ipc-daemon-bench.test.mjs",
|
|
41
42
|
"doctor": "node bin/burnoff.mjs doctor",
|
|
42
|
-
"check:brands": "node -e \"import('node:fs').then(async fs=>{const p=await import('node:path');const bad=new RegExp(['ctx'+'top','high'+'beam','attention[-_]'+'horizon','ga-visual'+'izer-v2','anti'+'gravity','pro_'+'license','ah-status'+'line'].join('|'),'i');const dirs=['bin','hooks','src','.github'];let hits=[];const walk=(d)=>{if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())walk(f);else if(/\\.(mjs|json|ya?ml|md)$/.test(e.name)){const t=fs.readFileSync(f,'utf8');if(bad.test(t))hits.push(f);}}};dirs.forEach(walk);['package.json','README.md'].forEach(f=>{if(fs.existsSync(f)&&bad.test(fs.readFileSync(f,'utf8')))hits.push(f);});if(hits.length){console.error('Brand leaks:',hits);process.exit(1);}console.log('Zero legacy brand strings found.');})\""
|
|
43
|
+
"check:brands": "node -e \"import('node:fs').then(async fs=>{const p=await import('node:path');const bad=new RegExp(['ctx'+'top','high'+'beam','attention[-_]'+'horizon','ga-visual'+'izer-v2','anti'+'gravity','pro_'+'license','ah-status'+'line','\\\\bHB'+'-(?:CFG|MCP|SEC)-','\\\\ba'+'gy','default'+'_api:','phase0'+'_' ].join('|'),'i');const dirs=['bin','hooks','src','.github'];let hits=[];const walk=(d)=>{if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())walk(f);else if(/\\.(mjs|json|ya?ml|md)$/.test(e.name)){const t=fs.readFileSync(f,'utf8');if(bad.test(t))hits.push(f);}}};dirs.forEach(walk);['package.json','README.md'].forEach(f=>{if(fs.existsSync(f)&&bad.test(fs.readFileSync(f,'utf8')))hits.push(f);});if(hits.length){console.error('Brand leaks:',hits);process.exit(1);}console.log('Zero legacy brand strings found.');})\""
|
|
43
44
|
}
|
|
44
45
|
}
|
package/src/ci/ci-gate.mjs
CHANGED
|
@@ -18,7 +18,8 @@ export const DEFAULT_CI_BUDGET_POLICY = Object.freeze({
|
|
|
18
18
|
minCacheHitPct: 50,
|
|
19
19
|
maxWasteRatioPct: 35,
|
|
20
20
|
maxRing0Violations: 0,
|
|
21
|
-
mode: 'enforce'
|
|
21
|
+
mode: 'enforce',
|
|
22
|
+
failOnMissingTranscripts: false
|
|
22
23
|
});
|
|
23
24
|
|
|
24
25
|
function toFiniteNumber(value) {
|
|
@@ -35,9 +36,14 @@ function toFiniteNumber(value) {
|
|
|
35
36
|
export function loadCiBudgetPolicy(cwd, overrides = {}) {
|
|
36
37
|
const repoDir = path.resolve(cwd || process.cwd());
|
|
37
38
|
const loaded = loadBurnoffPolicy(repoDir);
|
|
38
|
-
const filePolicy =
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
const filePolicy =
|
|
40
|
+
loaded.exists && !loaded.parseError
|
|
41
|
+
? loaded.rawCiBudgetGate && typeof loaded.rawCiBudgetGate === 'object'
|
|
42
|
+
? loaded.rawCiBudgetGate
|
|
43
|
+
: loaded.ciBudgetGate && typeof loaded.ciBudgetGate === 'object'
|
|
44
|
+
? loaded.ciBudgetGate
|
|
45
|
+
: {}
|
|
46
|
+
: {};
|
|
41
47
|
|
|
42
48
|
const merged = { ...DEFAULT_CI_BUDGET_POLICY };
|
|
43
49
|
|
|
@@ -64,6 +70,9 @@ export function loadCiBudgetPolicy(cwd, overrides = {}) {
|
|
|
64
70
|
if (toFiniteNumber(layer.maxRing0Violations) !== null) {
|
|
65
71
|
merged.maxRing0Violations = toFiniteNumber(layer.maxRing0Violations);
|
|
66
72
|
}
|
|
73
|
+
if (typeof layer.failOnMissingTranscripts === 'boolean') {
|
|
74
|
+
merged.failOnMissingTranscripts = layer.failOnMissingTranscripts;
|
|
75
|
+
}
|
|
67
76
|
if (layer.mode !== undefined && layer.mode !== null) {
|
|
68
77
|
merged.mode = String(layer.mode).toLowerCase();
|
|
69
78
|
}
|
|
@@ -148,9 +157,34 @@ export function evaluateCiBudgetGate(options = {}) {
|
|
|
148
157
|
const cacheHitPct = Number(summary.cacheHitPct || 0);
|
|
149
158
|
const wasteRatioPct = Number(summary.wasteRatioPct || 0);
|
|
150
159
|
const ring0Violations = Number(summary.ring0Violations || 0);
|
|
160
|
+
const sessionCount =
|
|
161
|
+
typeof summary.sessionCount === 'number' && Number.isFinite(summary.sessionCount)
|
|
162
|
+
? summary.sessionCount
|
|
163
|
+
: null;
|
|
164
|
+
const missingTranscripts =
|
|
165
|
+
reconciledCostUsd === null &&
|
|
166
|
+
totalTokens === 0 &&
|
|
167
|
+
totalInputTokens === 0 &&
|
|
168
|
+
totalCacheReadTokens === 0 &&
|
|
169
|
+
(sessionCount === null || sessionCount === 0);
|
|
151
170
|
|
|
171
|
+
const notices = [];
|
|
152
172
|
const violations = [];
|
|
153
173
|
|
|
174
|
+
if (missingTranscripts) {
|
|
175
|
+
const noticeMsg =
|
|
176
|
+
'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.';
|
|
177
|
+
notices.push({ code: 'MISSING_TRANSCRIPTS', message: noticeMsg });
|
|
178
|
+
if (policy.failOnMissingTranscripts === true) {
|
|
179
|
+
violations.push({
|
|
180
|
+
ruleId: 'MISSING_TRANSCRIPTS',
|
|
181
|
+
actual: 0,
|
|
182
|
+
limit: 1,
|
|
183
|
+
message: noticeMsg
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
154
188
|
if (effectiveCostUsd > policy.maxPrCostUsd) {
|
|
155
189
|
violations.push({
|
|
156
190
|
ruleId: 'MAX_PR_COST_USD',
|
|
@@ -205,9 +239,14 @@ export function evaluateCiBudgetGate(options = {}) {
|
|
|
205
239
|
}
|
|
206
240
|
|
|
207
241
|
const annotationLevel = verdict === 'FAIL' ? '::error' : '::warning';
|
|
208
|
-
const annotations =
|
|
209
|
-
(v) => `${annotationLevel} title=Burnoff CI Budget Gate (${v.ruleId})::${v.message}`
|
|
210
|
-
|
|
242
|
+
const annotations = [
|
|
243
|
+
...violations.map((v) => `${annotationLevel} title=Burnoff CI Budget Gate (${v.ruleId})::${v.message}`),
|
|
244
|
+
...(verdict !== 'FAIL'
|
|
245
|
+
? notices
|
|
246
|
+
.filter((n) => !violations.some((v) => v.ruleId === n.code))
|
|
247
|
+
.map((n) => `::warning title=Burnoff CI Budget Gate (${n.code})::${n.message}`)
|
|
248
|
+
: [])
|
|
249
|
+
];
|
|
211
250
|
|
|
212
251
|
return {
|
|
213
252
|
ok: verdict !== 'FAIL',
|
|
@@ -217,14 +256,17 @@ export function evaluateCiBudgetGate(options = {}) {
|
|
|
217
256
|
metrics: {
|
|
218
257
|
estimatedCostUsd,
|
|
219
258
|
reconciledCostUsd,
|
|
259
|
+
effectiveCostUsd,
|
|
220
260
|
attributionVariancePct,
|
|
221
261
|
totalTokens,
|
|
222
262
|
cacheHitPct,
|
|
223
263
|
wasteRatioPct,
|
|
224
264
|
ring0Violations,
|
|
225
265
|
totalInputTokens,
|
|
226
|
-
totalCacheReadTokens
|
|
266
|
+
totalCacheReadTokens,
|
|
267
|
+
sessionCount
|
|
227
268
|
},
|
|
269
|
+
notices,
|
|
228
270
|
violations,
|
|
229
271
|
annotations
|
|
230
272
|
};
|
|
@@ -239,19 +281,30 @@ export function formatCiGateMarkdown(result = {}) {
|
|
|
239
281
|
const violatedSet = new Set((result.violations || []).map((v) => v.ruleId));
|
|
240
282
|
|
|
241
283
|
const statusTag = (ruleId) => (violatedSet.has(ruleId) ? result.verdict : 'PASS');
|
|
284
|
+
const costDisplay =
|
|
285
|
+
typeof m.reconciledCostUsd === 'number' && m.reconciledCostUsd > Number(m.estimatedCostUsd || 0)
|
|
286
|
+
? `$${m.reconciledCostUsd.toFixed(4)} (reconciled)`
|
|
287
|
+
: `$${Number(m.estimatedCostUsd || 0).toFixed(4)}`;
|
|
242
288
|
|
|
243
289
|
const lines = [
|
|
244
290
|
`### Burnoff CI / PR Token-Budget Gate: **${result.verdict || 'UNKNOWN'}** (\`mode: ${p.mode}\`)`,
|
|
245
291
|
'',
|
|
246
292
|
'| Check | Actual | Limit | Status |',
|
|
247
293
|
'| :--- | :---: | :---: | :---: |',
|
|
248
|
-
`| \`MAX_PR_COST_USD\` |
|
|
294
|
+
`| \`MAX_PR_COST_USD\` | \`${costDisplay}\` | \`<=$${Number(p.maxPrCostUsd).toFixed(2)}\` | **${statusTag('MAX_PR_COST_USD')}** |`,
|
|
249
295
|
`| \`MAX_PR_TOKENS\` | \`${Number(m.totalTokens || 0).toLocaleString('en-US')}\` | \`<=${Number(p.maxPrTokens).toLocaleString('en-US')}\` | **${statusTag('MAX_PR_TOKENS')}** |`,
|
|
250
296
|
`| \`MIN_CACHE_HIT_PCT\` | \`${m.cacheHitPct ?? 0}%\` | \`>=${p.minCacheHitPct}%\` | **${statusTag('MIN_CACHE_HIT_PCT')}** |`,
|
|
251
297
|
`| \`MAX_WASTE_RATIO_PCT\` | \`${m.wasteRatioPct ?? 0}%\` | \`<=${p.maxWasteRatioPct}%\` | **${statusTag('MAX_WASTE_RATIO_PCT')}** |`,
|
|
252
298
|
`| \`MAX_RING0_VIOLATIONS\` | \`${m.ring0Violations ?? 0}\` | \`<=${p.maxRing0Violations}\` | **${statusTag('MAX_RING0_VIOLATIONS')}** |`
|
|
253
299
|
];
|
|
254
300
|
|
|
301
|
+
if (Array.isArray(result.notices) && result.notices.length > 0) {
|
|
302
|
+
lines.push('', '#### Notices', '');
|
|
303
|
+
for (const n of result.notices) {
|
|
304
|
+
lines.push(`- **${n.code}**: ${n.message}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
255
308
|
if (Array.isArray(result.violations) && result.violations.length > 0) {
|
|
256
309
|
lines.push('', '#### Violations', '');
|
|
257
310
|
for (const v of result.violations) {
|