costclaw 0.2.0 → 0.2.1
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/README.md +114 -54
- package/dist/index.js +610 -110
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,54 +1,114 @@
|
|
|
1
|
-
# costclaw
|
|
2
|
-
|
|
3
|
-
A local cost and setup audit for [Claude Code](https://claude.com/claude-code).
|
|
4
|
-
Point it at your session logs and it shows where token spend leaks, scores your
|
|
5
|
-
setup across six pillars, and ranks fixes by the dollars they recover.
|
|
6
|
-
|
|
7
|
-
Your prompts never leave your machine. The audit parses the logs already on your
|
|
8
|
-
disk and prints a report. It uploads nothing.
|
|
9
|
-
|
|
10
|
-
## Use it
|
|
11
|
-
|
|
12
|
-
Requires Node 20+.
|
|
13
|
-
|
|
14
|
-
```bash
|
|
15
|
-
npx costclaw audit
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
That reads `~/.claude/projects` (override with `--path <dir>`) and prints:
|
|
19
|
-
|
|
20
|
-
```
|
|
21
|
-
CostClaw audit
|
|
22
|
-
Source: ~/.claude/projects (N sessions across M projects)
|
|
23
|
-
|
|
24
|
-
Recoverable spend (cache-miss exposure): $XXX.XX
|
|
25
|
-
|
|
26
|
-
Spend analyzed: $X,XXX.XX Cache hit: 96.3% Active hours: XXX.X
|
|
27
|
-
Overall setup score: 91 / 100 (Dialed in)
|
|
28
|
-
CLAUDE.md quality n/a
|
|
29
|
-
Context hygiene [###################.] 95
|
|
30
|
-
Prompting patterns [##################..] 92
|
|
31
|
-
Session management [####################] 100
|
|
32
|
-
Tool and MCP config [####################] 100
|
|
33
|
-
Cost discipline [##############......] 70
|
|
34
|
-
|
|
35
|
-
Top fixes by recoverable spend:
|
|
36
|
-
- [$XXX.XX] Recover spend lost to cache misses
|
|
37
|
-
Keep the start of each session stable so the prompt cache is reused.
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
## Options
|
|
41
|
-
|
|
42
|
-
```
|
|
43
|
-
costclaw audit [--path <dir>] [--claude-md <file>] [--json]
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
- `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
|
|
47
|
-
- `--claude-md <file>` score a CLAUDE.md file's quality.
|
|
48
|
-
- `--json` print the raw, derived `AuditRecord` instead of the human report.
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
1
|
+
# costclaw
|
|
2
|
+
|
|
3
|
+
A local cost and setup audit for [Claude Code](https://claude.com/claude-code).
|
|
4
|
+
Point it at your session logs and it shows where token spend leaks, scores your
|
|
5
|
+
setup across six pillars, and ranks fixes by the dollars they recover.
|
|
6
|
+
|
|
7
|
+
Your prompts never leave your machine. The audit parses the logs already on your
|
|
8
|
+
disk and prints a report. It uploads nothing.
|
|
9
|
+
|
|
10
|
+
## Use it
|
|
11
|
+
|
|
12
|
+
Requires Node 20+.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx costclaw audit
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
That reads `~/.claude/projects` (override with `--path <dir>`) and prints:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
CostClaw audit
|
|
22
|
+
Source: ~/.claude/projects (N sessions across M projects)
|
|
23
|
+
|
|
24
|
+
Recoverable spend (cache-miss exposure): $XXX.XX
|
|
25
|
+
|
|
26
|
+
Spend analyzed: $X,XXX.XX Cache hit: 96.3% Active hours: XXX.X
|
|
27
|
+
Overall setup score: 91 / 100 (Dialed in)
|
|
28
|
+
CLAUDE.md quality n/a
|
|
29
|
+
Context hygiene [###################.] 95
|
|
30
|
+
Prompting patterns [##################..] 92
|
|
31
|
+
Session management [####################] 100
|
|
32
|
+
Tool and MCP config [####################] 100
|
|
33
|
+
Cost discipline [##############......] 70
|
|
34
|
+
|
|
35
|
+
Top fixes by recoverable spend:
|
|
36
|
+
- [$XXX.XX] Recover spend lost to cache misses
|
|
37
|
+
Keep the start of each session stable so the prompt cache is reused.
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Options
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
|
|
47
|
+
- `--claude-md <file>` score a CLAUDE.md file's quality.
|
|
48
|
+
- `--json` print the raw, derived `AuditRecord` instead of the human report.
|
|
49
|
+
- `--html [file]` also write a self-contained HTML report (default
|
|
50
|
+
`costclaw-report.html` in the current directory) and open it in your browser.
|
|
51
|
+
The file inlines everything, so nothing is fetched and nothing is uploaded; the
|
|
52
|
+
terminal report still prints.
|
|
53
|
+
- `--card [file]` also write a shareable score card SVG (default
|
|
54
|
+
`costclaw-card.svg`): your score, band, recoverable spend, cache hit rate, and
|
|
55
|
+
strongest pillar. A static file, no fonts or network calls.
|
|
56
|
+
|
|
57
|
+
Run `costclaw --version` (or `-v` / `costclaw version`) to print the installed
|
|
58
|
+
CLI version.
|
|
59
|
+
|
|
60
|
+
## Badge
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npx costclaw badge
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Runs a fresh audit and writes a shields.io-style badge SVG (default
|
|
67
|
+
`costclaw-badge.svg`): a "costclaw" segment and your overall score, colored by
|
|
68
|
+
its band. Drop it in a README with a plain image tag:
|
|
69
|
+
|
|
70
|
+
```markdown
|
|
71
|
+

|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Optimize
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
npx costclaw optimize
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Turns the same audit into done-for-you artifacts: an optimized `CLAUDE.md`
|
|
85
|
+
scaffold, a prioritized fix playbook, and a conservative, project-derived
|
|
86
|
+
`settings.suggested.json` permission allowlist. It scans `--project <dir>`
|
|
87
|
+
(default: the current directory) to auto-fill the scaffold from your real files.
|
|
88
|
+
By default it dry-runs into `./costclaw-out` and touches none of your files.
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- `--write <file>` applies the optimized `CLAUDE.md` in place, after backing up
|
|
95
|
+
the original to `<file>.bak` and printing a diff.
|
|
96
|
+
- `--apply-settings [file]` merges the derived permission allowlist into your
|
|
97
|
+
Claude Code settings. Opt-in and additive: it only touches
|
|
98
|
+
`permissions.allow` and `permissions.deny` (a deduped union that keeps your
|
|
99
|
+
existing entries and orders them first) and never removes or changes any other
|
|
100
|
+
key. The default target is the scanned project's `.claude/settings.json`; pass
|
|
101
|
+
`[file]` to target another. It backs up the previous file to `<target>.bak`,
|
|
102
|
+
prints a diff, then writes pretty JSON. A missing target is created; a file it
|
|
103
|
+
cannot `JSON.parse` (for example JSONC with comments) is refused and left
|
|
104
|
+
untouched.
|
|
105
|
+
- `--force` allows overwriting an existing `.bak` backup for `--write` and
|
|
106
|
+
`--apply-settings`.
|
|
107
|
+
|
|
108
|
+
`optimize` needs a one-time license (`costclaw activate <key>`); `audit` is free.
|
|
109
|
+
|
|
110
|
+
## Privacy
|
|
111
|
+
|
|
112
|
+
The only thing the tool produces is a derived `AuditRecord`: totals and generated
|
|
113
|
+
prose, no prompt text, no file paths, no secrets. A hosted dashboard is on the
|
|
114
|
+
roadmap and would receive only that derived record, never your logs.
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { pathToFileURL } from "url";
|
|
5
|
+
|
|
3
6
|
// src/audit-command.ts
|
|
4
|
-
import { readFile as
|
|
7
|
+
import { readFile as readFile2, writeFile } from "fs/promises";
|
|
8
|
+
import { resolve } from "path";
|
|
9
|
+
import { spawn } from "child_process";
|
|
5
10
|
|
|
6
11
|
// ../../packages/engine/src/types.ts
|
|
7
12
|
function emptyTotals() {
|
|
@@ -60,8 +65,8 @@ function isOpus(model) {
|
|
|
60
65
|
|
|
61
66
|
// ../../packages/engine/src/sanitize.ts
|
|
62
67
|
var EM_OR_EN = /[—–]/;
|
|
63
|
-
function hasEmDash(
|
|
64
|
-
return EM_OR_EN.test(
|
|
68
|
+
function hasEmDash(text2) {
|
|
69
|
+
return EM_OR_EN.test(text2);
|
|
65
70
|
}
|
|
66
71
|
function sanitizeText(input) {
|
|
67
72
|
let out = input;
|
|
@@ -127,7 +132,7 @@ function extractTools(content) {
|
|
|
127
132
|
}
|
|
128
133
|
return { names, events };
|
|
129
134
|
}
|
|
130
|
-
function parseSession(
|
|
135
|
+
function parseSession(text2, opts = {}) {
|
|
131
136
|
const s = {
|
|
132
137
|
sessionUuid: null,
|
|
133
138
|
projectSlug: null,
|
|
@@ -155,7 +160,7 @@ function parseSession(text, opts = {}) {
|
|
|
155
160
|
const modelCounts = /* @__PURE__ */ new Map();
|
|
156
161
|
let cwd = null;
|
|
157
162
|
let seq = 0;
|
|
158
|
-
for (const line of
|
|
163
|
+
for (const line of text2.split("\n")) {
|
|
159
164
|
if (!line.trim()) continue;
|
|
160
165
|
const rec = safeParse(line);
|
|
161
166
|
if (!rec) {
|
|
@@ -325,6 +330,7 @@ var MISROUTE_MIN_EXPOSURE = 0.5;
|
|
|
325
330
|
var MISROUTE_BASELINE = "claude-sonnet-4-6";
|
|
326
331
|
var WORKFLOW_MIN_COST = 5;
|
|
327
332
|
var WORKFLOW_WARN_SHARE = 0.5;
|
|
333
|
+
var REDUNDANT_TARGET_MIN_FIRES = 10;
|
|
328
334
|
function thirdHit(turns, lo, hi) {
|
|
329
335
|
let read = 0;
|
|
330
336
|
let total = 0;
|
|
@@ -418,6 +424,57 @@ function ruleHeavyToolLoops(ctx) {
|
|
|
418
424
|
}
|
|
419
425
|
return out;
|
|
420
426
|
}
|
|
427
|
+
function targetNounFor(tool) {
|
|
428
|
+
if (["Bash", "PowerShell"].includes(tool)) return "command";
|
|
429
|
+
if (["WebFetch", "WebSearch"].includes(tool)) return "query";
|
|
430
|
+
if (tool === "Agent" || tool.startsWith("Task")) return "subagent";
|
|
431
|
+
return "file";
|
|
432
|
+
}
|
|
433
|
+
function ruleRedundantTargetThrash(ctx) {
|
|
434
|
+
const out = [];
|
|
435
|
+
for (const proj of ctx.projects) {
|
|
436
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
437
|
+
for (const s of proj.sessions) {
|
|
438
|
+
if (s.kind !== "main") continue;
|
|
439
|
+
const counts = /* @__PURE__ */ new Map();
|
|
440
|
+
for (const e of s.toolEvents) {
|
|
441
|
+
if (e.target == null) continue;
|
|
442
|
+
const byTarget = counts.get(e.name) ?? /* @__PURE__ */ new Map();
|
|
443
|
+
byTarget.set(e.target, (byTarget.get(e.target) ?? 0) + 1);
|
|
444
|
+
counts.set(e.name, byTarget);
|
|
445
|
+
}
|
|
446
|
+
const perToolMax = /* @__PURE__ */ new Map();
|
|
447
|
+
for (const [tool, byTarget] of counts) {
|
|
448
|
+
for (const n of byTarget.values()) {
|
|
449
|
+
if (n < REDUNDANT_TARGET_MIN_FIRES) continue;
|
|
450
|
+
perToolMax.set(tool, Math.max(perToolMax.get(tool) ?? 0, n));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
for (const [tool, n] of perToolMax) {
|
|
454
|
+
const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
|
|
455
|
+
entry.sessionsAffected += 1;
|
|
456
|
+
entry.maxFires = Math.max(entry.maxFires, n);
|
|
457
|
+
if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
|
|
458
|
+
byTool.set(tool, entry);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
for (const [tool, e] of byTool) {
|
|
462
|
+
const n = e.sessionsAffected;
|
|
463
|
+
const noun = targetNounFor(tool);
|
|
464
|
+
out.push({
|
|
465
|
+
ruleId: "REDUNDANT_TARGET_THRASH",
|
|
466
|
+
severity: "warn",
|
|
467
|
+
project: proj.slug,
|
|
468
|
+
title: `Repeated ${tool} calls on the same ${noun} in ${n} session${n === 1 ? "" : "s"}`,
|
|
469
|
+
description: `${tool} hit the same ${noun} up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of redundant repeated calls instead of new progress.`,
|
|
470
|
+
suggestedAction: `Cache or reuse the result instead of calling ${tool} again on the same ${noun}.`,
|
|
471
|
+
estimatedMonthlySavingsUsd: 0,
|
|
472
|
+
evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
421
478
|
function ruleShortSessionBloat(ctx) {
|
|
422
479
|
const out = [];
|
|
423
480
|
for (const proj of ctx.projects) {
|
|
@@ -535,6 +592,7 @@ var RULES = [
|
|
|
535
592
|
{ id: "BAD_CACHE_HIT", run: ruleBadCacheHit },
|
|
536
593
|
{ id: "HOT_PROJECT", run: ruleHotProject },
|
|
537
594
|
{ id: "HEAVY_TOOL_LOOPS", run: ruleHeavyToolLoops },
|
|
595
|
+
{ id: "REDUNDANT_TARGET_THRASH", run: ruleRedundantTargetThrash },
|
|
538
596
|
{ id: "SHORT_SESSION_BLOAT", run: ruleShortSessionBloat },
|
|
539
597
|
{ id: "MARATHON_SESSION", run: ruleMarathonSession },
|
|
540
598
|
{ id: "MODEL_MISROUTE", run: ruleModelMisroute },
|
|
@@ -619,8 +677,8 @@ function scoreStability(chars, volatileMarkers) {
|
|
|
619
677
|
const per1k = volatileMarkers / chars * 1e3;
|
|
620
678
|
return clamp(100 - per1k * 28);
|
|
621
679
|
}
|
|
622
|
-
function analyzeClaudeMd(
|
|
623
|
-
const raw = (
|
|
680
|
+
function analyzeClaudeMd(text2) {
|
|
681
|
+
const raw = (text2 ?? "").trim();
|
|
624
682
|
if (!raw) {
|
|
625
683
|
return {
|
|
626
684
|
present: false,
|
|
@@ -935,7 +993,7 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
935
993
|
checks.push(questionnaireCheck("clear_between", "Clearing between tasks", answers));
|
|
936
994
|
checks.push(questionnaireCheck("plan_first", "Planning first", answers));
|
|
937
995
|
checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
|
|
938
|
-
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
|
|
996
|
+
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS" || f.ruleId === "REDUNDANT_TARGET_THRASH");
|
|
939
997
|
const thrashSessions = new Set(
|
|
940
998
|
heavyLoops.flatMap((f) => {
|
|
941
999
|
const uuids = f.evidence?.["sessionUuids"];
|
|
@@ -950,7 +1008,7 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
950
1008
|
"prompting",
|
|
951
1009
|
"Tool looping",
|
|
952
1010
|
s.sessionsCount > 0 ? clamp2(100 - thrashShare * 180) : null,
|
|
953
|
-
s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No
|
|
1011
|
+
s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No sign of a stuck tool loop." : `${thrashSessions} of ${s.sessionsCount} sessions (${thrashPct}%) showed heavy tool repetition: one tool firing 100 or more times, or the same file, command, or target hit 10 or more times.`,
|
|
954
1012
|
"metrics"
|
|
955
1013
|
)
|
|
956
1014
|
);
|
|
@@ -1161,7 +1219,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1161
1219
|
const fixes = [];
|
|
1162
1220
|
const covered = /* @__PURE__ */ new Set();
|
|
1163
1221
|
const round22 = (n) => Math.round(n * 100) / 100;
|
|
1164
|
-
const
|
|
1222
|
+
const usd6 = (n) => {
|
|
1165
1223
|
const fixed = round22(n).toFixed(2);
|
|
1166
1224
|
const dot = fixed.indexOf(".");
|
|
1167
1225
|
const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
@@ -1189,7 +1247,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1189
1247
|
severity: sevForUsd(exposure),
|
|
1190
1248
|
wasteUsd: round22(exposure),
|
|
1191
1249
|
problem: sanitizeText(
|
|
1192
|
-
`Up to ${
|
|
1250
|
+
`Up to ${usd6(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
1193
1251
|
),
|
|
1194
1252
|
action: sanitizeText(
|
|
1195
1253
|
"Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
|
|
@@ -1270,7 +1328,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1270
1328
|
pillarName: PILLARS.cost_discipline.name,
|
|
1271
1329
|
severity: sevForUsd(misrouteUsd),
|
|
1272
1330
|
wasteUsd: round22(misrouteUsd),
|
|
1273
|
-
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${
|
|
1331
|
+
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd6(misrouteUsd)} more than a cheaper model would have.`),
|
|
1274
1332
|
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
|
|
1275
1333
|
basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1276
1334
|
});
|
|
@@ -1284,7 +1342,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1284
1342
|
pillarName: PILLARS.session_mgmt.name,
|
|
1285
1343
|
severity: sevForUsd(marathonUsd),
|
|
1286
1344
|
wasteUsd: round22(marathonUsd),
|
|
1287
|
-
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${
|
|
1345
|
+
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd6(marathonUsd)} for context in the later turns.`),
|
|
1288
1346
|
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1289
1347
|
basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
|
|
1290
1348
|
});
|
|
@@ -1297,7 +1355,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1297
1355
|
pillarName: PILLARS.cost_discipline.name,
|
|
1298
1356
|
severity: "info",
|
|
1299
1357
|
wasteUsd: 0,
|
|
1300
|
-
problem: sanitizeText(`Workflow and subagent runs cost about ${
|
|
1358
|
+
problem: sanitizeText(`Workflow and subagent runs cost about ${usd6(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
|
|
1301
1359
|
action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
|
|
1302
1360
|
basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
|
|
1303
1361
|
});
|
|
@@ -1344,8 +1402,8 @@ function usd(n) {
|
|
|
1344
1402
|
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1345
1403
|
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
1346
1404
|
}
|
|
1347
|
-
function clean(
|
|
1348
|
-
return sanitizeText(
|
|
1405
|
+
function clean(text2) {
|
|
1406
|
+
return sanitizeText(text2);
|
|
1349
1407
|
}
|
|
1350
1408
|
function weakCostDiscipline(scores) {
|
|
1351
1409
|
const p = scores.find((s) => s.id === "cost_discipline");
|
|
@@ -1819,7 +1877,7 @@ function toUsageMetrics(report) {
|
|
|
1819
1877
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
1820
1878
|
}));
|
|
1821
1879
|
const modelBreakdown = {};
|
|
1822
|
-
for (const [model,
|
|
1880
|
+
for (const [model, usd6] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd6);
|
|
1823
1881
|
return {
|
|
1824
1882
|
spendUsd: round2(s.cost_usd),
|
|
1825
1883
|
cacheSavingsUsd: round2(s.cache_savings_usd),
|
|
@@ -1857,6 +1915,7 @@ function buildAudit(input, opts = {}) {
|
|
|
1857
1915
|
const { headlineWasteUsd, headlineWasteLabel, fixes } = synthesize(report, pillars, cmd);
|
|
1858
1916
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
1859
1917
|
return {
|
|
1918
|
+
schemaVersion: "1",
|
|
1860
1919
|
id: randomUUID(),
|
|
1861
1920
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1862
1921
|
contactEmail: input.contactEmail?.trim() || null,
|
|
@@ -1884,7 +1943,8 @@ var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
|
1884
1943
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
1885
1944
|
|
|
1886
1945
|
// src/read-sessions.ts
|
|
1887
|
-
import { readdir
|
|
1946
|
+
import { readdir } from "fs/promises";
|
|
1947
|
+
import { readFileSync, openSync, closeSync } from "fs";
|
|
1888
1948
|
import { join, relative, sep } from "path";
|
|
1889
1949
|
import { homedir } from "os";
|
|
1890
1950
|
function defaultProjectsPath() {
|
|
@@ -1912,6 +1972,21 @@ function classify(rel) {
|
|
|
1912
1972
|
if (parts.includes("workflows")) return { kind: "workflow", parentSessionId: parent };
|
|
1913
1973
|
return { kind: "subagent", parentSessionId: parent };
|
|
1914
1974
|
}
|
|
1975
|
+
function lazyLog(full, meta) {
|
|
1976
|
+
return {
|
|
1977
|
+
name: meta.name,
|
|
1978
|
+
kind: meta.kind,
|
|
1979
|
+
parentSessionId: meta.parentSessionId,
|
|
1980
|
+
projectSlug: meta.projectSlug,
|
|
1981
|
+
get text() {
|
|
1982
|
+
try {
|
|
1983
|
+
return readFileSync(full, "utf8");
|
|
1984
|
+
} catch {
|
|
1985
|
+
return "";
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1915
1990
|
async function readSessions(rootPath) {
|
|
1916
1991
|
const logs = [];
|
|
1917
1992
|
const skipped = [];
|
|
@@ -1936,8 +2011,8 @@ async function readSessions(rootPath) {
|
|
|
1936
2011
|
const name = `${dir.name}/${rel}`;
|
|
1937
2012
|
const { kind, parentSessionId } = classify(rel);
|
|
1938
2013
|
try {
|
|
1939
|
-
|
|
1940
|
-
logs.push({ name,
|
|
2014
|
+
closeSync(openSync(full, "r"));
|
|
2015
|
+
logs.push(lazyLog(full, { name, kind, parentSessionId, projectSlug: dir.name }));
|
|
1941
2016
|
} catch {
|
|
1942
2017
|
skipped.push(name);
|
|
1943
2018
|
}
|
|
@@ -1955,6 +2030,15 @@ function bar(score, width = 20) {
|
|
|
1955
2030
|
const filled = Math.round(score / 100 * width);
|
|
1956
2031
|
return `[${"#".repeat(filled)}${".".repeat(width - filled)}] ${score}`;
|
|
1957
2032
|
}
|
|
2033
|
+
function unassessedLine(pillars) {
|
|
2034
|
+
const gaps = pillars.filter((p) => !p.assessed);
|
|
2035
|
+
if (gaps.length === 0) return null;
|
|
2036
|
+
const parts = gaps.map((p) => {
|
|
2037
|
+
const reason = p.checks[0]?.basis;
|
|
2038
|
+
return reason ? `${p.name} (${reason})` : p.name;
|
|
2039
|
+
});
|
|
2040
|
+
return `Not yet scored: ${parts.join(" ")}`;
|
|
2041
|
+
}
|
|
1958
2042
|
function formatAudit(record, meta) {
|
|
1959
2043
|
const m = record.usageMetrics;
|
|
1960
2044
|
const lines = [];
|
|
@@ -1996,18 +2080,235 @@ function formatAudit(record, meta) {
|
|
|
1996
2080
|
lines.push("");
|
|
1997
2081
|
lines.push(`Note: ${meta.skipped.length} file(s) could not be read and were skipped.`);
|
|
1998
2082
|
}
|
|
1999
|
-
|
|
2000
|
-
|
|
2083
|
+
const gapLine = unassessedLine(record.pillarScores);
|
|
2084
|
+
if (gapLine) {
|
|
2085
|
+
lines.push("");
|
|
2086
|
+
lines.push(gapLine);
|
|
2087
|
+
}
|
|
2001
2088
|
return lines.join("\n");
|
|
2002
2089
|
}
|
|
2003
2090
|
|
|
2091
|
+
// src/svg.ts
|
|
2092
|
+
var SYSTEM_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
|
2093
|
+
function esc(s) {
|
|
2094
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2095
|
+
}
|
|
2096
|
+
function bandColorForScore(score) {
|
|
2097
|
+
if (score < 40) return "#c0392b";
|
|
2098
|
+
if (score < 60) return "#e07a5f";
|
|
2099
|
+
if (score < 75) return "#d99a2b";
|
|
2100
|
+
if (score < 90) return "#5f8f4f";
|
|
2101
|
+
return "#3f7d4e";
|
|
2102
|
+
}
|
|
2103
|
+
function rect(x, y, w, h, fill, rx = 0) {
|
|
2104
|
+
return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}" fill="${fill}"></rect>`;
|
|
2105
|
+
}
|
|
2106
|
+
function text(x, y, s, opts = {}) {
|
|
2107
|
+
const size = opts.size ?? 13;
|
|
2108
|
+
const weight = opts.weight ?? 400;
|
|
2109
|
+
const fill = opts.fill ?? "#251d1a";
|
|
2110
|
+
const anchor = opts.anchor ?? "start";
|
|
2111
|
+
return `<text x="${x}" y="${y}" font-family="${SYSTEM_FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${esc(s)}</text>`;
|
|
2112
|
+
}
|
|
2113
|
+
function estimateTextWidth(s, size) {
|
|
2114
|
+
return Math.round(s.length * size * 0.62);
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// src/html-report.ts
|
|
2118
|
+
function usd3(n) {
|
|
2119
|
+
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2120
|
+
}
|
|
2121
|
+
function truncate(s, max) {
|
|
2122
|
+
return s.length > max ? s.slice(0, max - 3) + "..." : s;
|
|
2123
|
+
}
|
|
2124
|
+
function projectChart(projects) {
|
|
2125
|
+
if (projects.length === 0) {
|
|
2126
|
+
return `<p class="muted">No project spend to chart.</p>`;
|
|
2127
|
+
}
|
|
2128
|
+
const rowH = 30;
|
|
2129
|
+
const gap = 10;
|
|
2130
|
+
const labelW = 220;
|
|
2131
|
+
const barMax = 340;
|
|
2132
|
+
const valW = 96;
|
|
2133
|
+
const width = labelW + barMax + valW;
|
|
2134
|
+
const height = projects.length * (rowH + gap) - gap;
|
|
2135
|
+
const maxCost = Math.max(...projects.map((p) => p.costUsd), 0.01);
|
|
2136
|
+
const rows = projects.map((p, i) => {
|
|
2137
|
+
const y = i * (rowH + gap);
|
|
2138
|
+
const w = Math.max(3, Math.round(p.costUsd / maxCost * barMax));
|
|
2139
|
+
const mid = y + rowH / 2;
|
|
2140
|
+
const label = esc(truncate(p.slug, 32));
|
|
2141
|
+
return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${y + 3}" width="${w}" height="${rowH - 6}" rx="4" fill="#e07a5f"></rect><text x="${labelW + w + 8}" y="${mid}" class="c-val" dominant-baseline="middle">${esc(usd3(p.costUsd))}</text>`;
|
|
2142
|
+
}).join("");
|
|
2143
|
+
return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
|
|
2144
|
+
}
|
|
2145
|
+
function pillarBars(pillars) {
|
|
2146
|
+
return pillars.map((p) => {
|
|
2147
|
+
const name = esc(p.name);
|
|
2148
|
+
if (!p.assessed || p.score === null) {
|
|
2149
|
+
return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill p-na" style="width:100%"></span></span><span class="p-score muted">n/a</span></div>`;
|
|
2150
|
+
}
|
|
2151
|
+
const score = p.score;
|
|
2152
|
+
const color = bandColorForScore(score);
|
|
2153
|
+
return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill" style="width:${score}%;background:${color}"></span></span><span class="p-score">${score}</span></div>`;
|
|
2154
|
+
}).join("");
|
|
2155
|
+
}
|
|
2156
|
+
function dollarFixCard(f) {
|
|
2157
|
+
return `<li class="fix"><div class="fix-head"><span class="fix-amt">${esc(usd3(f.wasteUsd))}</span><span class="fix-title">${esc(f.title)}</span></div><p class="fix-problem">${esc(f.problem)}</p><p class="fix-action">${esc(f.action)}</p></li>`;
|
|
2158
|
+
}
|
|
2159
|
+
function otherFixCard(f) {
|
|
2160
|
+
return `<li class="fix other"><div class="fix-head"><span class="fix-title">${esc(f.title)}</span></div><p class="fix-action">${esc(f.action)}</p></li>`;
|
|
2161
|
+
}
|
|
2162
|
+
var STYLE = `
|
|
2163
|
+
:root { color-scheme: light; }
|
|
2164
|
+
* { box-sizing: border-box; }
|
|
2165
|
+
body {
|
|
2166
|
+
margin: 0;
|
|
2167
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
2168
|
+
color: #251d1a;
|
|
2169
|
+
background: #fefaf7;
|
|
2170
|
+
line-height: 1.5;
|
|
2171
|
+
}
|
|
2172
|
+
.wrap { max-width: 860px; margin: 0 auto; padding: 40px 24px 64px; }
|
|
2173
|
+
h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; }
|
|
2174
|
+
h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
|
|
2175
|
+
.sub { color: #7a6a63; font-size: 14px; margin: 0 0 8px; }
|
|
2176
|
+
.banner {
|
|
2177
|
+
margin: 28px 0 8px; padding: 22px 26px; border-radius: 14px;
|
|
2178
|
+
background: linear-gradient(135deg, #822d1d, #e07a5f); color: #fefaf7;
|
|
2179
|
+
box-shadow: 0 8px 24px rgba(130, 45, 29, 0.18);
|
|
2180
|
+
}
|
|
2181
|
+
.banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
|
|
2182
|
+
.banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
|
|
2183
|
+
.stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
|
|
2184
|
+
.stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
|
|
2185
|
+
.stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
2186
|
+
.stat .v { font-size: 20px; font-weight: 600; margin-top: 2px; }
|
|
2187
|
+
.score-head { display: flex; align-items: baseline; gap: 12px; }
|
|
2188
|
+
.score-head .big { font-size: 30px; font-weight: 700; }
|
|
2189
|
+
.score-head .band { font-size: 15px; color: #822d1d; font-weight: 600; }
|
|
2190
|
+
.pillar { display: flex; align-items: center; gap: 12px; margin: 8px 0; }
|
|
2191
|
+
.p-name { flex: 0 0 190px; font-size: 14px; }
|
|
2192
|
+
.p-track { flex: 1; height: 14px; background: #f0e2da; border-radius: 7px; overflow: hidden; }
|
|
2193
|
+
.p-fill { display: block; height: 100%; border-radius: 7px; }
|
|
2194
|
+
.p-fill.p-na { background: repeating-linear-gradient(45deg, #ece0d8, #ece0d8 6px, #f5ece6 6px, #f5ece6 12px); }
|
|
2195
|
+
.p-score { flex: 0 0 40px; text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; font-size: 14px; }
|
|
2196
|
+
.muted { color: #9a8a82; font-weight: 500; }
|
|
2197
|
+
.chart { background: #fff; border: 1px solid #f0e2da; border-radius: 12px; padding: 18px; overflow-x: auto; }
|
|
2198
|
+
.c-lbl { font-size: 13px; fill: #251d1a; }
|
|
2199
|
+
.c-val { font-size: 13px; fill: #822d1d; font-weight: 600; }
|
|
2200
|
+
ul.fixes { list-style: none; margin: 0; padding: 0; }
|
|
2201
|
+
.fix { background: #fff; border: 1px solid #f0e2da; border-left: 4px solid #e07a5f; border-radius: 10px; padding: 14px 18px; margin: 10px 0; }
|
|
2202
|
+
.fix.other { border-left-color: #cbb8ae; }
|
|
2203
|
+
.fix-head { display: flex; align-items: baseline; gap: 12px; }
|
|
2204
|
+
.fix-amt { font-size: 18px; font-weight: 700; color: #822d1d; font-variant-numeric: tabular-nums; }
|
|
2205
|
+
.fix-title { font-size: 15px; font-weight: 600; }
|
|
2206
|
+
.fix-problem { margin: 8px 0 4px; color: #5a4a43; font-size: 14px; }
|
|
2207
|
+
.fix-action { margin: 4px 0 0; font-size: 14px; }
|
|
2208
|
+
.footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid #f0e2da; color: #7a6a63; font-size: 13px; }
|
|
2209
|
+
.footer strong { color: #251d1a; }
|
|
2210
|
+
`;
|
|
2211
|
+
function renderHtml(record, meta) {
|
|
2212
|
+
const m = record.usageMetrics;
|
|
2213
|
+
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
2214
|
+
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
2215
|
+
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No directly recoverable dollars found. See issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
|
|
2216
|
+
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
2217
|
+
const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
|
|
2218
|
+
return `<!doctype html>
|
|
2219
|
+
<html lang="en">
|
|
2220
|
+
<head>
|
|
2221
|
+
<meta charset="utf-8" />
|
|
2222
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2223
|
+
<title>CostClaw audit report</title>
|
|
2224
|
+
<style>${STYLE}</style>
|
|
2225
|
+
</head>
|
|
2226
|
+
<body>
|
|
2227
|
+
<div class="wrap">
|
|
2228
|
+
<h1>CostClaw audit</h1>
|
|
2229
|
+
<p class="sub">Source: ${esc(meta.root)} (${meta.sessionCount} sessions across ${m.projectsCount} projects)</p>
|
|
2230
|
+
<p class="sub">Pricing snapshot: ${esc(m.pricingSnapshotDate)}</p>
|
|
2231
|
+
|
|
2232
|
+
<div class="banner">
|
|
2233
|
+
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
2234
|
+
<div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>
|
|
2235
|
+
</div>
|
|
2236
|
+
|
|
2237
|
+
<div class="stats">
|
|
2238
|
+
<div class="stat"><div class="k">Spend analyzed</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
|
|
2239
|
+
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
2240
|
+
<div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
2241
|
+
</div>
|
|
2242
|
+
|
|
2243
|
+
<h2>Spend by project</h2>
|
|
2244
|
+
<div class="chart">${projectChart(m.topProjects)}</div>
|
|
2245
|
+
|
|
2246
|
+
<h2>Setup score</h2>
|
|
2247
|
+
<div class="score-head">
|
|
2248
|
+
<span class="big">${record.overallScore} / 100</span>
|
|
2249
|
+
<span class="band">${esc(record.band.label)}</span>
|
|
2250
|
+
</div>
|
|
2251
|
+
${pillarBars(record.pillarScores)}
|
|
2252
|
+
|
|
2253
|
+
<h2>Top fixes by recoverable spend</h2>
|
|
2254
|
+
${dollarSection}
|
|
2255
|
+
${otherSection}
|
|
2256
|
+
${skippedNote}
|
|
2257
|
+
|
|
2258
|
+
<div class="footer">
|
|
2259
|
+
<strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
|
|
2260
|
+
your prompts, file contents, and paths never left this computer. Generated ${esc(record.createdAt)}.
|
|
2261
|
+
</div>
|
|
2262
|
+
</div>
|
|
2263
|
+
</body>
|
|
2264
|
+
</html>
|
|
2265
|
+
`;
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
// src/card.ts
|
|
2269
|
+
var WIDTH = 600;
|
|
2270
|
+
var HEIGHT = 315;
|
|
2271
|
+
var INK = "#251d1a";
|
|
2272
|
+
var UMBER = "#822d1d";
|
|
2273
|
+
var PAPER = "#fefaf7";
|
|
2274
|
+
var BORDER = "#f0e2da";
|
|
2275
|
+
var MUTED = "#7a6a63";
|
|
2276
|
+
function usd4(n) {
|
|
2277
|
+
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2278
|
+
}
|
|
2279
|
+
function strongestPillar(pillars) {
|
|
2280
|
+
const assessed = pillars.filter((p) => p.assessed && p.score !== null);
|
|
2281
|
+
if (assessed.length === 0) return null;
|
|
2282
|
+
return assessed.reduce((best, p) => p.score > best.score ? p : best);
|
|
2283
|
+
}
|
|
2284
|
+
function renderCard(record) {
|
|
2285
|
+
const scoreColor = bandColorForScore(record.overallScore);
|
|
2286
|
+
const strongest = strongestPillar(record.pillarScores);
|
|
2287
|
+
const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
|
|
2288
|
+
const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
|
|
2289
|
+
const wasteText = usd4(record.headlineWasteUsd);
|
|
2290
|
+
const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
|
|
2291
|
+
const scoreText = String(record.overallScore);
|
|
2292
|
+
const scoreX = 32;
|
|
2293
|
+
const scoreW = estimateTextWidth(scoreText, 72);
|
|
2294
|
+
const outOf100X = scoreX + scoreW + 8;
|
|
2295
|
+
const pillLabel = record.band.label;
|
|
2296
|
+
const pillW = estimateTextWidth(pillLabel, 14) + 32;
|
|
2297
|
+
const pillY = 168;
|
|
2298
|
+
const pillH = 30;
|
|
2299
|
+
const statX = 32;
|
|
2300
|
+
const statY = 224;
|
|
2301
|
+
const statGap = 30;
|
|
2302
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="img" aria-label="${esc(ariaLabel)}">` + rect(0, 0, WIDTH, HEIGHT, PAPER, 16) + `<rect x="0.5" y="0.5" width="${WIDTH - 1}" height="${HEIGHT - 1}" rx="16" fill="none" stroke="${BORDER}"></rect>` + text(32, 48, "CostClaw", { size: 22, weight: 700, fill: UMBER }) + text(scoreX, 150, scoreText, { size: 72, weight: 700, fill: INK }) + text(outOf100X, 150, "/ 100", { size: 22, weight: 600, fill: MUTED }) + rect(32, pillY, pillW, pillH, scoreColor, 15) + text(32 + pillW / 2, pillY + pillH / 2 + 5, pillLabel, { size: 14, weight: 700, fill: "#ffffff", anchor: "middle" }) + text(statX, statY, `Recoverable spend: ${wasteText}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap, `Cache hit rate: ${cacheHitPct}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap * 2, `Strongest pillar: ${strongestText}`, { size: 15, weight: 600, fill: INK }) + `</svg>`;
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2004
2305
|
// src/read-setup.ts
|
|
2005
|
-
import { readFile
|
|
2306
|
+
import { readFile } from "fs/promises";
|
|
2006
2307
|
import { join as join2 } from "path";
|
|
2007
2308
|
import { homedir as homedir2 } from "os";
|
|
2008
2309
|
async function readJson(path) {
|
|
2009
2310
|
try {
|
|
2010
|
-
const parsed = JSON.parse(await
|
|
2311
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
2011
2312
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
2012
2313
|
} catch {
|
|
2013
2314
|
return null;
|
|
@@ -2047,6 +2348,19 @@ async function readSetup(home = homedir2()) {
|
|
|
2047
2348
|
}
|
|
2048
2349
|
|
|
2049
2350
|
// src/audit-command.ts
|
|
2351
|
+
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
2352
|
+
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
2353
|
+
function openInBrowser(target) {
|
|
2354
|
+
try {
|
|
2355
|
+
const platform = process.platform;
|
|
2356
|
+
const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
2357
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
2358
|
+
child.on("error", () => {
|
|
2359
|
+
});
|
|
2360
|
+
child.unref();
|
|
2361
|
+
} catch {
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2050
2364
|
async function loadAuditInputs(opts) {
|
|
2051
2365
|
const root = opts.path || defaultProjectsPath();
|
|
2052
2366
|
const { logs, skipped } = await readSessions(root);
|
|
@@ -2055,7 +2369,7 @@ async function loadAuditInputs(opts) {
|
|
|
2055
2369
|
}
|
|
2056
2370
|
let claudeMd;
|
|
2057
2371
|
if (opts.claudeMdPath) {
|
|
2058
|
-
claudeMd = await
|
|
2372
|
+
claudeMd = await readFile2(opts.claudeMdPath, "utf8");
|
|
2059
2373
|
}
|
|
2060
2374
|
return { logs, claudeMd, root, skipped };
|
|
2061
2375
|
}
|
|
@@ -2063,16 +2377,35 @@ async function runAudit(opts) {
|
|
|
2063
2377
|
const { logs, claudeMd, root, skipped } = await loadAuditInputs(opts);
|
|
2064
2378
|
const setup = await readSetup();
|
|
2065
2379
|
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
|
|
2066
|
-
|
|
2380
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped });
|
|
2381
|
+
const notices = [];
|
|
2382
|
+
if (opts.html) {
|
|
2383
|
+
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
2384
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped });
|
|
2385
|
+
await writeFile(target, doc, "utf8");
|
|
2386
|
+
openInBrowser(target);
|
|
2387
|
+
notices.push(`HTML report written to ${target}`);
|
|
2388
|
+
}
|
|
2389
|
+
if (opts.card) {
|
|
2390
|
+
const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
|
|
2391
|
+
const svg = renderCard(record);
|
|
2392
|
+
await writeFile(target, svg, "utf8");
|
|
2393
|
+
notices.push(`Score card written to ${target}`);
|
|
2394
|
+
}
|
|
2395
|
+
if (opts.json) {
|
|
2396
|
+
for (const notice of notices) process.stderr.write(notice + "\n");
|
|
2397
|
+
} else if (notices.length > 0) {
|
|
2398
|
+
output += "\n\n" + notices.join("\n\n");
|
|
2399
|
+
}
|
|
2067
2400
|
return { output, record };
|
|
2068
2401
|
}
|
|
2069
2402
|
|
|
2070
2403
|
// src/optimize-command.ts
|
|
2071
|
-
import { mkdir, writeFile, readFile as
|
|
2072
|
-
import { join as join4 } from "path";
|
|
2404
|
+
import { mkdir, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
|
|
2405
|
+
import { join as join4, dirname } from "path";
|
|
2073
2406
|
|
|
2074
2407
|
// src/project-scan.ts
|
|
2075
|
-
import { readdir as readdir2, readFile as
|
|
2408
|
+
import { readdir as readdir2, readFile as readFile3, stat } from "fs/promises";
|
|
2076
2409
|
import { join as join3, basename } from "path";
|
|
2077
2410
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
2078
2411
|
"node_modules",
|
|
@@ -2102,7 +2435,7 @@ var DIR_NOTES = {
|
|
|
2102
2435
|
};
|
|
2103
2436
|
async function readText(p) {
|
|
2104
2437
|
try {
|
|
2105
|
-
return await
|
|
2438
|
+
return await readFile3(p, "utf8");
|
|
2106
2439
|
} catch {
|
|
2107
2440
|
return null;
|
|
2108
2441
|
}
|
|
@@ -2128,18 +2461,18 @@ async function listEntries(dir) {
|
|
|
2128
2461
|
function pushUnique(arr, value) {
|
|
2129
2462
|
if (!arr.includes(value)) arr.push(value);
|
|
2130
2463
|
}
|
|
2131
|
-
function parseJson(
|
|
2132
|
-
if (
|
|
2464
|
+
function parseJson(text2) {
|
|
2465
|
+
if (text2 === null) return null;
|
|
2133
2466
|
try {
|
|
2134
|
-
const parsed = JSON.parse(
|
|
2467
|
+
const parsed = JSON.parse(text2);
|
|
2135
2468
|
return parsed && typeof parsed === "object" ? parsed : null;
|
|
2136
2469
|
} catch {
|
|
2137
2470
|
return null;
|
|
2138
2471
|
}
|
|
2139
2472
|
}
|
|
2140
|
-
function parseEnvNames(
|
|
2473
|
+
function parseEnvNames(text2) {
|
|
2141
2474
|
const names = [];
|
|
2142
|
-
for (const raw of
|
|
2475
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2143
2476
|
const line = raw.trim();
|
|
2144
2477
|
if (line === "" || line.startsWith("#")) continue;
|
|
2145
2478
|
const eq = line.indexOf("=");
|
|
@@ -2318,7 +2651,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
2318
2651
|
profile.preCommit = `run ${lintCmd} and ${typecheckCmd} before committing`;
|
|
2319
2652
|
}
|
|
2320
2653
|
}
|
|
2321
|
-
function parsePyproject(
|
|
2654
|
+
function parsePyproject(text2) {
|
|
2322
2655
|
const tables = /* @__PURE__ */ new Set();
|
|
2323
2656
|
let name = null;
|
|
2324
2657
|
let description = null;
|
|
@@ -2331,7 +2664,7 @@ function parsePyproject(text) {
|
|
|
2331
2664
|
const m = cleaned.match(/^[A-Za-z0-9_.\-]+/);
|
|
2332
2665
|
if (m) pushUnique(deps, m[0].toLowerCase());
|
|
2333
2666
|
};
|
|
2334
|
-
for (const raw of
|
|
2667
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2335
2668
|
const line = raw.trim();
|
|
2336
2669
|
if (line === "" || line.startsWith("#")) continue;
|
|
2337
2670
|
const header = line.match(/^\[([^\]]+)\]$/);
|
|
@@ -2383,9 +2716,9 @@ var PY_STACK = {
|
|
|
2383
2716
|
sqlalchemy: "SQLAlchemy",
|
|
2384
2717
|
pydantic: "Pydantic"
|
|
2385
2718
|
};
|
|
2386
|
-
function pyDepsFromRequirements(
|
|
2719
|
+
function pyDepsFromRequirements(text2) {
|
|
2387
2720
|
const deps = [];
|
|
2388
|
-
for (const raw of
|
|
2721
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2389
2722
|
const line = raw.trim();
|
|
2390
2723
|
if (line === "" || line.startsWith("#") || line.startsWith("-")) continue;
|
|
2391
2724
|
const m = line.match(/^[A-Za-z0-9_.\-]+/);
|
|
@@ -2443,12 +2776,12 @@ async function scanPython(dir, files, profile) {
|
|
|
2443
2776
|
}
|
|
2444
2777
|
}
|
|
2445
2778
|
async function scanRust(dir, profile) {
|
|
2446
|
-
const
|
|
2779
|
+
const text2 = await readText(join3(dir, "Cargo.toml"));
|
|
2447
2780
|
pushUnique(profile.stack, "Rust");
|
|
2448
2781
|
profile.packageManager = "cargo";
|
|
2449
|
-
if (
|
|
2782
|
+
if (text2 !== null) {
|
|
2450
2783
|
let section = "";
|
|
2451
|
-
for (const raw of
|
|
2784
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2452
2785
|
const line = raw.trim();
|
|
2453
2786
|
const header = line.match(/^\[([^\]]+)\]$/);
|
|
2454
2787
|
if (header) {
|
|
@@ -2469,11 +2802,11 @@ async function scanRust(dir, profile) {
|
|
|
2469
2802
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
2470
2803
|
}
|
|
2471
2804
|
async function scanGo(dir, profile) {
|
|
2472
|
-
const
|
|
2805
|
+
const text2 = await readText(join3(dir, "go.mod"));
|
|
2473
2806
|
pushUnique(profile.stack, "Go");
|
|
2474
2807
|
profile.packageManager = "go";
|
|
2475
|
-
if (
|
|
2476
|
-
const m =
|
|
2808
|
+
if (text2 !== null) {
|
|
2809
|
+
const m = text2.match(/^module\s+(\S+)/m);
|
|
2477
2810
|
if (m) {
|
|
2478
2811
|
const mod = m[1];
|
|
2479
2812
|
profile.name = mod.includes("/") ? mod.slice(mod.lastIndexOf("/") + 1) : mod;
|
|
@@ -2483,9 +2816,9 @@ async function scanGo(dir, profile) {
|
|
|
2483
2816
|
profile.commands.push({ label: "test", command: "go test ./..." });
|
|
2484
2817
|
profile.commands.push({ label: "lint", command: "go vet ./..." });
|
|
2485
2818
|
}
|
|
2486
|
-
function parseMakefile(
|
|
2819
|
+
function parseMakefile(text2) {
|
|
2487
2820
|
const targets = [];
|
|
2488
|
-
for (const raw of
|
|
2821
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2489
2822
|
if (/^\t/.test(raw)) continue;
|
|
2490
2823
|
const m = raw.match(/^([A-Za-z0-9_.\-]+)\s*:(?!=)/);
|
|
2491
2824
|
if (m) {
|
|
@@ -2495,8 +2828,8 @@ function parseMakefile(text) {
|
|
|
2495
2828
|
}
|
|
2496
2829
|
return targets;
|
|
2497
2830
|
}
|
|
2498
|
-
function parseReadme(
|
|
2499
|
-
const lines =
|
|
2831
|
+
function parseReadme(text2) {
|
|
2832
|
+
const lines = text2.split(/\r?\n/);
|
|
2500
2833
|
let name = null;
|
|
2501
2834
|
let i = 0;
|
|
2502
2835
|
for (; i < lines.length; i++) {
|
|
@@ -2547,9 +2880,9 @@ async function scanProject(dir) {
|
|
|
2547
2880
|
await scanGo(dir, profile);
|
|
2548
2881
|
}
|
|
2549
2882
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
2550
|
-
const
|
|
2551
|
-
if (
|
|
2552
|
-
for (const t of parseMakefile(
|
|
2883
|
+
const text2 = await readText(join3(dir, "Makefile"));
|
|
2884
|
+
if (text2 !== null) {
|
|
2885
|
+
for (const t of parseMakefile(text2)) {
|
|
2553
2886
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
2554
2887
|
}
|
|
2555
2888
|
}
|
|
@@ -2557,9 +2890,9 @@ async function scanProject(dir) {
|
|
|
2557
2890
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
2558
2891
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
2559
2892
|
if (readmeName) {
|
|
2560
|
-
const
|
|
2561
|
-
if (
|
|
2562
|
-
const parsed = parseReadme(
|
|
2893
|
+
const text2 = await readText(join3(dir, readmeName));
|
|
2894
|
+
if (text2 !== null) {
|
|
2895
|
+
const parsed = parseReadme(text2);
|
|
2563
2896
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
2564
2897
|
if (profile.description === null && parsed.description !== null) {
|
|
2565
2898
|
profile.description = parsed.description;
|
|
@@ -2570,8 +2903,8 @@ async function scanProject(dir) {
|
|
|
2570
2903
|
profile.structure = await detectStructure(dir, dirs);
|
|
2571
2904
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
2572
2905
|
if (envFile) {
|
|
2573
|
-
const
|
|
2574
|
-
if (
|
|
2906
|
+
const text2 = await readText(join3(dir, envFile));
|
|
2907
|
+
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
2575
2908
|
}
|
|
2576
2909
|
return profile;
|
|
2577
2910
|
}
|
|
@@ -2580,7 +2913,7 @@ async function scanProject(dir) {
|
|
|
2580
2913
|
var OPTIMIZED_NAME = "CLAUDE.optimized.md";
|
|
2581
2914
|
var PLAYBOOK_NAME = "PLAYBOOK.md";
|
|
2582
2915
|
var SETTINGS_NAME = "settings.suggested.json";
|
|
2583
|
-
function
|
|
2916
|
+
function usd5(n) {
|
|
2584
2917
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2585
2918
|
}
|
|
2586
2919
|
function describeDetection(project) {
|
|
@@ -2613,6 +2946,78 @@ function lineDiff(oldText, newText) {
|
|
|
2613
2946
|
if (lines.length === 0) lines.push(" (no line-level changes)");
|
|
2614
2947
|
return lines.join("\n");
|
|
2615
2948
|
}
|
|
2949
|
+
function asStringArray(value) {
|
|
2950
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
2951
|
+
}
|
|
2952
|
+
function unionStrings(existing, additions) {
|
|
2953
|
+
const out = [];
|
|
2954
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2955
|
+
for (const v of existing) {
|
|
2956
|
+
if (!seen.has(v)) {
|
|
2957
|
+
seen.add(v);
|
|
2958
|
+
out.push(v);
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
for (const v of additions) {
|
|
2962
|
+
if (!seen.has(v)) {
|
|
2963
|
+
seen.add(v);
|
|
2964
|
+
out.push(v);
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
return out;
|
|
2968
|
+
}
|
|
2969
|
+
function isPlainObject(value) {
|
|
2970
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2971
|
+
}
|
|
2972
|
+
async function applyDerivedSettings(target, suggestedJson, force) {
|
|
2973
|
+
const backup = `${target}.bak`;
|
|
2974
|
+
if (await pathExists(backup) && !force) {
|
|
2975
|
+
throw new Error(
|
|
2976
|
+
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
let existingText = "";
|
|
2980
|
+
let existing = {};
|
|
2981
|
+
if (await pathExists(target)) {
|
|
2982
|
+
existingText = await readFile4(target, "utf8");
|
|
2983
|
+
if (existingText.trim() !== "") {
|
|
2984
|
+
let parsed;
|
|
2985
|
+
try {
|
|
2986
|
+
parsed = JSON.parse(existingText);
|
|
2987
|
+
} catch {
|
|
2988
|
+
throw new Error(
|
|
2989
|
+
`Could not parse ${target} as JSON, so it was left untouched. If it contains comments or trailing commas (JSONC), remove them, or point --apply-settings at a plain JSON file.`
|
|
2990
|
+
);
|
|
2991
|
+
}
|
|
2992
|
+
if (!isPlainObject(parsed)) {
|
|
2993
|
+
throw new Error(
|
|
2994
|
+
`Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
|
|
2995
|
+
);
|
|
2996
|
+
}
|
|
2997
|
+
existing = parsed;
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
const suggested = JSON.parse(suggestedJson);
|
|
3001
|
+
const suggestedAllow = asStringArray(suggested.permissions?.allow);
|
|
3002
|
+
const suggestedDeny = asStringArray(suggested.permissions?.deny);
|
|
3003
|
+
const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
|
|
3004
|
+
const mergedPerms = { ...existingPerms };
|
|
3005
|
+
mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
|
|
3006
|
+
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
3007
|
+
const merged = { ...existing, permissions: mergedPerms };
|
|
3008
|
+
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
3009
|
+
await mkdir(dirname(target), { recursive: true });
|
|
3010
|
+
await writeFile2(backup, existingText, "utf8");
|
|
3011
|
+
await writeFile2(target, mergedText, "utf8");
|
|
3012
|
+
return [
|
|
3013
|
+
`Merged the derived permission allowlist into ${target}`,
|
|
3014
|
+
`Backed up the previous file to ${backup}`,
|
|
3015
|
+
"Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
|
|
3016
|
+
"",
|
|
3017
|
+
"Diff (previous vs merged):",
|
|
3018
|
+
lineDiff(existingText, mergedText)
|
|
3019
|
+
];
|
|
3020
|
+
}
|
|
2616
3021
|
async function runOptimize(opts) {
|
|
2617
3022
|
const { logs, claudeMd } = await loadAuditInputs({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
2618
3023
|
const report = analyzeUploads(logs);
|
|
@@ -2626,9 +3031,9 @@ async function runOptimize(opts) {
|
|
|
2626
3031
|
const outDir = opts.out || join4(process.cwd(), "costclaw-out");
|
|
2627
3032
|
await mkdir(outDir, { recursive: true });
|
|
2628
3033
|
const playbookPath = join4(outDir, PLAYBOOK_NAME);
|
|
2629
|
-
await
|
|
3034
|
+
await writeFile2(playbookPath, result.playbook, "utf8");
|
|
2630
3035
|
const settingsPath = join4(outDir, SETTINGS_NAME);
|
|
2631
|
-
await
|
|
3036
|
+
await writeFile2(settingsPath, result.settingsJson, "utf8");
|
|
2632
3037
|
const lines = [];
|
|
2633
3038
|
lines.push("CostClaw optimize");
|
|
2634
3039
|
lines.push("");
|
|
@@ -2642,10 +3047,10 @@ async function runOptimize(opts) {
|
|
|
2642
3047
|
}
|
|
2643
3048
|
let original = "";
|
|
2644
3049
|
if (await pathExists(target)) {
|
|
2645
|
-
original = await
|
|
3050
|
+
original = await readFile4(target, "utf8");
|
|
2646
3051
|
}
|
|
2647
|
-
await
|
|
2648
|
-
await
|
|
3052
|
+
await writeFile2(backup, original, "utf8");
|
|
3053
|
+
await writeFile2(target, result.optimizedClaudeMd, "utf8");
|
|
2649
3054
|
lines.push(`Backed up the original to ${backup}`);
|
|
2650
3055
|
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
2651
3056
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -2658,19 +3063,26 @@ async function runOptimize(opts) {
|
|
|
2658
3063
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
2659
3064
|
} else {
|
|
2660
3065
|
const optimizedPath = join4(outDir, OPTIMIZED_NAME);
|
|
2661
|
-
await
|
|
3066
|
+
await writeFile2(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
2662
3067
|
lines.push("Dry run (no files of yours were changed).");
|
|
2663
3068
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
2664
3069
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
2665
3070
|
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
2666
3071
|
lines.push("");
|
|
2667
3072
|
lines.push(describeDetection(project));
|
|
2668
|
-
lines.push(`Recoverable spend (cache-miss exposure): ${
|
|
3073
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
|
|
2669
3074
|
lines.push("");
|
|
2670
3075
|
lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
|
|
2671
3076
|
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
2672
3077
|
lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
|
|
2673
|
-
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied
|
|
3078
|
+
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied unless you ask.");
|
|
3079
|
+
lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
|
|
3080
|
+
}
|
|
3081
|
+
if (opts.applySettings) {
|
|
3082
|
+
const target = opts.applySettingsPath || join4(projectDir, ".claude", "settings.json");
|
|
3083
|
+
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
3084
|
+
lines.push("");
|
|
3085
|
+
lines.push(...applyLines);
|
|
2674
3086
|
}
|
|
2675
3087
|
if (result.notes.length > 0) {
|
|
2676
3088
|
lines.push("");
|
|
@@ -2682,8 +3094,39 @@ async function runOptimize(opts) {
|
|
|
2682
3094
|
return { output: lines.join("\n") };
|
|
2683
3095
|
}
|
|
2684
3096
|
|
|
3097
|
+
// src/badge-command.ts
|
|
3098
|
+
import { writeFile as writeFile3 } from "fs/promises";
|
|
3099
|
+
import { resolve as resolve2 } from "path";
|
|
3100
|
+
|
|
3101
|
+
// src/badge.ts
|
|
3102
|
+
var HEIGHT2 = 20;
|
|
3103
|
+
var FONT_SIZE = 11;
|
|
3104
|
+
var PAD_X = 8;
|
|
3105
|
+
var LEFT_LABEL = "costclaw";
|
|
3106
|
+
var LEFT_COLOR = "#822d1d";
|
|
3107
|
+
var CLIP_ID = "costclaw-badge-round";
|
|
3108
|
+
function renderBadge(record) {
|
|
3109
|
+
const scoreLabel = `${record.overallScore}/100`;
|
|
3110
|
+
const leftW = estimateTextWidth(LEFT_LABEL, FONT_SIZE) + PAD_X * 2;
|
|
3111
|
+
const rightW = estimateTextWidth(scoreLabel, FONT_SIZE) + PAD_X * 2;
|
|
3112
|
+
const width = leftW + rightW;
|
|
3113
|
+
const rightColor = bandColorForScore(record.overallScore);
|
|
3114
|
+
const ariaLabel = `costclaw score: ${scoreLabel} (${record.band.label})`;
|
|
3115
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT2}" viewBox="0 0 ${width} ${HEIGHT2}" role="img" aria-label="${esc(ariaLabel)}"><clipPath id="${CLIP_ID}">${rect(0, 0, width, HEIGHT2, "#ffffff", 3)}</clipPath><g clip-path="url(#${CLIP_ID})">` + rect(0, 0, leftW, HEIGHT2, LEFT_COLOR) + rect(leftW, 0, rightW, HEIGHT2, rightColor) + `</g>` + text(leftW / 2, 14, LEFT_LABEL, { size: FONT_SIZE, weight: 600, fill: "#fefaf7", anchor: "middle" }) + text(leftW + rightW / 2, 14, scoreLabel, { size: FONT_SIZE, weight: 700, fill: "#ffffff", anchor: "middle" }) + `</svg>`;
|
|
3116
|
+
}
|
|
3117
|
+
|
|
3118
|
+
// src/badge-command.ts
|
|
3119
|
+
var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
3120
|
+
async function runBadge(opts) {
|
|
3121
|
+
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
3122
|
+
const svg = renderBadge(record);
|
|
3123
|
+
const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
|
|
3124
|
+
await writeFile3(target, svg, "utf8");
|
|
3125
|
+
return { output: `Badge written to ${target}`, record, target };
|
|
3126
|
+
}
|
|
3127
|
+
|
|
2685
3128
|
// src/license.ts
|
|
2686
|
-
import { mkdir as mkdir2, readFile as
|
|
3129
|
+
import { mkdir as mkdir2, readFile as readFile5, writeFile as writeFile4, rm } from "fs/promises";
|
|
2687
3130
|
import { join as join5 } from "path";
|
|
2688
3131
|
import { homedir as homedir3, hostname } from "os";
|
|
2689
3132
|
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
@@ -2722,6 +3165,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
|
2722
3165
|
const parts = licenseKey.trim().split(".");
|
|
2723
3166
|
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
2724
3167
|
const [prefix, payloadPart, signaturePart] = parts;
|
|
3168
|
+
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
2725
3169
|
try {
|
|
2726
3170
|
const publicKey = createPublicKey(publicKeyPem);
|
|
2727
3171
|
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
@@ -2736,7 +3180,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
|
2736
3180
|
}
|
|
2737
3181
|
async function readStoredLicense(dir) {
|
|
2738
3182
|
try {
|
|
2739
|
-
const data = JSON.parse(await
|
|
3183
|
+
const data = JSON.parse(await readFile5(licenseFile(dir), "utf8"));
|
|
2740
3184
|
if (!data || typeof data.licenseKey !== "string") return null;
|
|
2741
3185
|
return data;
|
|
2742
3186
|
} catch {
|
|
@@ -2745,7 +3189,7 @@ async function readStoredLicense(dir) {
|
|
|
2745
3189
|
}
|
|
2746
3190
|
async function writeStoredLicense(dir, lic) {
|
|
2747
3191
|
await mkdir2(dir, { recursive: true });
|
|
2748
|
-
await
|
|
3192
|
+
await writeFile4(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
2749
3193
|
}
|
|
2750
3194
|
async function clearStoredLicense(dir) {
|
|
2751
3195
|
await rm(licenseFile(dir), { force: true });
|
|
@@ -2797,14 +3241,89 @@ function getFlag(args, name) {
|
|
|
2797
3241
|
const i = args.indexOf(name);
|
|
2798
3242
|
return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
|
|
2799
3243
|
}
|
|
3244
|
+
function optionalPathAfter(args, flag) {
|
|
3245
|
+
const i = args.indexOf(flag);
|
|
3246
|
+
if (i < 0) return void 0;
|
|
3247
|
+
const next = args[i + 1];
|
|
3248
|
+
return next !== void 0 && !next.startsWith("-") ? next : void 0;
|
|
3249
|
+
}
|
|
3250
|
+
function parseAuditFlags(args) {
|
|
3251
|
+
const html = args.includes("--html");
|
|
3252
|
+
const card = args.includes("--card");
|
|
3253
|
+
return {
|
|
3254
|
+
path: getFlag(args, "--path"),
|
|
3255
|
+
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3256
|
+
json: args.includes("--json"),
|
|
3257
|
+
html,
|
|
3258
|
+
htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
|
|
3259
|
+
card,
|
|
3260
|
+
cardPath: card ? optionalPathAfter(args, "--card") : void 0
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
function parseBadgeFlags(args) {
|
|
3264
|
+
return {
|
|
3265
|
+
path: getFlag(args, "--path"),
|
|
3266
|
+
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3267
|
+
out: getFlag(args, "--out")
|
|
3268
|
+
};
|
|
3269
|
+
}
|
|
3270
|
+
function cliVersion() {
|
|
3271
|
+
return true ? "0.2.1" : "0.0.0-dev";
|
|
3272
|
+
}
|
|
3273
|
+
function helpText() {
|
|
3274
|
+
return [
|
|
3275
|
+
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
3276
|
+
"",
|
|
3277
|
+
"Usage:",
|
|
3278
|
+
" costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
|
|
3279
|
+
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
3280
|
+
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
3281
|
+
" costclaw activate <license-key> [--name <machine-name>]",
|
|
3282
|
+
" costclaw deactivate",
|
|
3283
|
+
" costclaw --version",
|
|
3284
|
+
"",
|
|
3285
|
+
"audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
|
|
3286
|
+
"machine and prints a cost report plus a six-pillar setup score. It is free.",
|
|
3287
|
+
"--html writes a self-contained report (default: costclaw-report.html) and opens",
|
|
3288
|
+
"it in your browser; the terminal report still prints.",
|
|
3289
|
+
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
3290
|
+
"score, band, recoverable spend, cache hit rate, and your strongest pillar.",
|
|
3291
|
+
"",
|
|
3292
|
+
"badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
|
|
3293
|
+
"costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
|
|
3294
|
+
"in a README with an <img> tag; it is a static, self-contained file.",
|
|
3295
|
+
"",
|
|
3296
|
+
"optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
|
|
3297
|
+
"scaffold and a prioritized fix playbook. It also scans --project <dir>",
|
|
3298
|
+
"(default: the current directory) to auto-fill the scaffold's name, commands,",
|
|
3299
|
+
"structure, and other facts from your real project files. By default it",
|
|
3300
|
+
"dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
|
|
3301
|
+
"optimized CLAUDE.md in place after backing up the original and printing a diff.",
|
|
3302
|
+
"--apply-settings [file] additively merges the derived permission allowlist into",
|
|
3303
|
+
"the project's .claude/settings.json (or [file]); it only touches",
|
|
3304
|
+
"permissions.allow and permissions.deny, backs up the original, and prints a diff.",
|
|
3305
|
+
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
3306
|
+
"costclaw activate <key>. activate and deactivate move that license between",
|
|
3307
|
+
"machines. audit never needs a license.",
|
|
3308
|
+
"",
|
|
3309
|
+
"Everything runs locally. Nothing is uploaded. Activation is a signed license",
|
|
3310
|
+
"key verified on this machine: there is no license server and no network call.",
|
|
3311
|
+
""
|
|
3312
|
+
].join("\n");
|
|
3313
|
+
}
|
|
2800
3314
|
async function main() {
|
|
2801
3315
|
const [command, ...args] = process.argv.slice(2);
|
|
3316
|
+
if (command === "--version" || command === "-v" || command === "version") {
|
|
3317
|
+
process.stdout.write(cliVersion() + "\n");
|
|
3318
|
+
return;
|
|
3319
|
+
}
|
|
2802
3320
|
if (command === "audit") {
|
|
2803
|
-
const { output } = await runAudit(
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
3321
|
+
const { output } = await runAudit(parseAuditFlags(args));
|
|
3322
|
+
process.stdout.write(output + "\n");
|
|
3323
|
+
return;
|
|
3324
|
+
}
|
|
3325
|
+
if (command === "badge") {
|
|
3326
|
+
const { output } = await runBadge(parseBadgeFlags(args));
|
|
2808
3327
|
process.stdout.write(output + "\n");
|
|
2809
3328
|
return;
|
|
2810
3329
|
}
|
|
@@ -2834,51 +3353,32 @@ Run: costclaw optimize
|
|
|
2834
3353
|
process.stderr.write(gate.message + "\n");
|
|
2835
3354
|
process.exit(1);
|
|
2836
3355
|
}
|
|
2837
|
-
if (gate.offline) {
|
|
2838
|
-
process.stderr.write("Could not reach the license server; running on your saved activation.\n");
|
|
2839
|
-
}
|
|
2840
3356
|
const { output } = await runOptimize({
|
|
2841
3357
|
path: getFlag(args, "--path"),
|
|
2842
3358
|
claudeMdPath: getFlag(args, "--claude-md"),
|
|
2843
3359
|
projectDir: getFlag(args, "--project") || process.cwd(),
|
|
2844
3360
|
out: getFlag(args, "--out"),
|
|
2845
3361
|
write: getFlag(args, "--write"),
|
|
2846
|
-
force: args.includes("--force")
|
|
3362
|
+
force: args.includes("--force"),
|
|
3363
|
+
applySettings: args.includes("--apply-settings"),
|
|
3364
|
+
applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
|
|
2847
3365
|
});
|
|
2848
3366
|
process.stdout.write(output + "\n");
|
|
2849
3367
|
return;
|
|
2850
3368
|
}
|
|
2851
|
-
process.stderr.write(
|
|
2852
|
-
[
|
|
2853
|
-
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
2854
|
-
"",
|
|
2855
|
-
"Usage:",
|
|
2856
|
-
" costclaw audit [--path <dir>] [--claude-md <file>] [--json]",
|
|
2857
|
-
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--force]",
|
|
2858
|
-
" costclaw activate <license-key> [--name <machine-name>]",
|
|
2859
|
-
" costclaw deactivate",
|
|
2860
|
-
"",
|
|
2861
|
-
"audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
|
|
2862
|
-
"machine and prints a cost report plus a six-pillar setup score. It is free.",
|
|
2863
|
-
"",
|
|
2864
|
-
"optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
|
|
2865
|
-
"scaffold and a prioritized fix playbook. It also scans --project <dir>",
|
|
2866
|
-
"(default: the current directory) to auto-fill the scaffold's name, commands,",
|
|
2867
|
-
"structure, and other facts from your real project files. By default it",
|
|
2868
|
-
"dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
|
|
2869
|
-
"optimized CLAUDE.md in place after backing up the original and printing a diff.",
|
|
2870
|
-
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
2871
|
-
"costclaw activate <key>. activate and deactivate move that license between",
|
|
2872
|
-
"machines. audit never needs a license.",
|
|
2873
|
-
"",
|
|
2874
|
-
"Everything runs locally. Nothing is uploaded. The only network call is the",
|
|
2875
|
-
"license check to Lemon Squeezy, which sends just the key, never your logs.",
|
|
2876
|
-
""
|
|
2877
|
-
].join("\n") + "\n"
|
|
2878
|
-
);
|
|
3369
|
+
process.stderr.write(helpText() + "\n");
|
|
2879
3370
|
process.exit(command ? 1 : 0);
|
|
2880
3371
|
}
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
3372
|
+
var isEntryPoint = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
3373
|
+
if (isEntryPoint) {
|
|
3374
|
+
main().catch((err) => {
|
|
3375
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
3376
|
+
process.exit(1);
|
|
3377
|
+
});
|
|
3378
|
+
}
|
|
3379
|
+
export {
|
|
3380
|
+
cliVersion,
|
|
3381
|
+
helpText,
|
|
3382
|
+
parseAuditFlags,
|
|
3383
|
+
parseBadgeFlags
|
|
3384
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|