costclaw 0.2.4 → 0.4.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/README.md +40 -2
- package/dist/index.js +319 -88
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -44,15 +44,52 @@ Top fixes by recoverable spend:
|
|
|
44
44
|
Evidence: XX% of input tokens missed the cache across N sessions.
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
+
## On a subscription? Declare your plan
|
|
48
|
+
|
|
49
|
+
Every dollar the audit prints is an API-equivalent price: what those tokens
|
|
50
|
+
would cost at pay-as-you-go rates. On a Claude subscription (Pro or Max) your
|
|
51
|
+
marginal token cost is zero, so those dollars are not money back - they measure
|
|
52
|
+
your rate-limit headroom. Declare your plan once and the audit reframes itself
|
|
53
|
+
honestly:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npx costclaw audit --plan max20x # or pro, max5x; --plan api switches back
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The headline becomes recoverable usage - the share of your token consumption
|
|
60
|
+
you could win back - with the dollars demoted to API-equivalent context:
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
Recoverable usage (cache-miss exposure): 14.3% of analyzed usage ($1134.61 at API rates)
|
|
64
|
+
|
|
65
|
+
Usage analyzed (API-equivalent): $7921.99 Cache hit: 96.2% Active hours: 1889.7
|
|
66
|
+
Plan: max20x. Dollar figures are API-equivalent token value, not money back;
|
|
67
|
+
recovering them buys rate-limit headroom (more work per usage window).
|
|
68
|
+
Usage windows (5h, like your rate limit): median $8.10, busiest $34.20; busiest week $310.55 (API-equivalent)
|
|
69
|
+
Recovering 14.3% buys about 17% more work per window: up to ~42 extra minutes in a window like your busiest.
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The usage windows are modeled from your own activity timestamps, mirroring how
|
|
73
|
+
the limits actually work: a 5-hour window opens at your first activity, and a
|
|
74
|
+
weekly cap sits above it. Nothing is assumed about Anthropic's actual budgets;
|
|
75
|
+
everything is relative to your observed consumption ("busiest" is the 90th
|
|
76
|
+
percentile window, so one freak outlier does not set the bar).
|
|
77
|
+
|
|
78
|
+
The value is saved to `~/.costclaw/config.json`, so later runs (and `optimize`)
|
|
79
|
+
remember it. The findings and their ranking are identical either way; only the
|
|
80
|
+
unit is framed to match how you actually pay.
|
|
81
|
+
|
|
47
82
|
## Options
|
|
48
83
|
|
|
49
84
|
```
|
|
50
|
-
costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]
|
|
85
|
+
costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]
|
|
51
86
|
```
|
|
52
87
|
|
|
53
88
|
- `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
|
|
54
89
|
- `--claude-md <file>` score a specific CLAUDE.md file's quality (by default the
|
|
55
90
|
audit scores `~/.claude/CLAUDE.md` when it exists).
|
|
91
|
+
- `--plan <api|pro|max5x|max20x>` declare how you pay for Claude (see above);
|
|
92
|
+
persisted for later runs.
|
|
56
93
|
- `--json` print the raw, derived `AuditRecord` instead of the human report.
|
|
57
94
|
- `--html [file]` also write a self-contained HTML report (default
|
|
58
95
|
`costclaw-report.html` in the current directory) and open it in your browser.
|
|
@@ -97,7 +134,8 @@ Fixes resolved since the baseline:
|
|
|
97
134
|
The marginal cache hit rate covers only the period between the two audits, which
|
|
98
135
|
a lifetime average hides. You can also diff two explicit records saved with
|
|
99
136
|
`costclaw audit --json`: `costclaw diff baseline.json current.json`. Add `--json`
|
|
100
|
-
for the machine-readable diff. Free, like the audit.
|
|
137
|
+
for the machine-readable diff. Free, like the audit. The history keeps the newest
|
|
138
|
+
50 snapshots and prunes older ones automatically.
|
|
101
139
|
|
|
102
140
|
## Badge
|
|
103
141
|
|
package/dist/index.js
CHANGED
|
@@ -3,16 +3,14 @@
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
5
|
|
|
6
|
-
// src/audit-command.ts
|
|
7
|
-
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
8
|
-
import { join as join3, resolve } from "path";
|
|
9
|
-
import { homedir as homedir3 } from "os";
|
|
10
|
-
import { spawn } from "child_process";
|
|
11
|
-
|
|
12
6
|
// ../../packages/engine/src/types.ts
|
|
13
7
|
function emptyTotals() {
|
|
14
8
|
return { input_tokens: 0, output_tokens: 0, cache_creation_tokens: 0, cache_read_tokens: 0 };
|
|
15
9
|
}
|
|
10
|
+
var PLANS = ["api", "pro", "max5x", "max20x"];
|
|
11
|
+
function isPlan(value) {
|
|
12
|
+
return PLANS.includes(value);
|
|
13
|
+
}
|
|
16
14
|
|
|
17
15
|
// ../../packages/engine/src/pricing.ts
|
|
18
16
|
var PRICING_SNAPSHOT_DATE = "2026-05-13";
|
|
@@ -155,9 +153,12 @@ function parseSession(text2, opts = {}) {
|
|
|
155
153
|
skippedLines: 0,
|
|
156
154
|
kind: opts.kind ?? "main",
|
|
157
155
|
parentSessionId: opts.parentSessionId ?? null,
|
|
158
|
-
turnCache: []
|
|
156
|
+
turnCache: [],
|
|
157
|
+
costBuckets: []
|
|
159
158
|
};
|
|
160
159
|
const seen = /* @__PURE__ */ new Set();
|
|
160
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
161
|
+
const BUCKET_MS = 15 * 60 * 1e3;
|
|
161
162
|
const modelCounts = /* @__PURE__ */ new Map();
|
|
162
163
|
let cwd = null;
|
|
163
164
|
let seq = 0;
|
|
@@ -200,8 +201,16 @@ function parseSession(text2, opts = {}) {
|
|
|
200
201
|
s.totals.output_tokens += Number(usage.output_tokens) || 0;
|
|
201
202
|
s.totals.cache_creation_tokens += Number(usage.cache_creation_input_tokens) || 0;
|
|
202
203
|
s.totals.cache_read_tokens += Number(usage.cache_read_input_tokens) || 0;
|
|
203
|
-
|
|
204
|
+
const fragmentUsd = costForUsage(model, usage);
|
|
205
|
+
s.cost_usd += fragmentUsd;
|
|
204
206
|
s.cache_savings_usd += cacheSavingsForUsage(model, usage);
|
|
207
|
+
if (rec.timestamp) {
|
|
208
|
+
const ms = Date.parse(rec.timestamp);
|
|
209
|
+
if (!Number.isNaN(ms)) {
|
|
210
|
+
const t = Math.floor(ms / BUCKET_MS);
|
|
211
|
+
buckets.set(t, (buckets.get(t) ?? 0) + fragmentUsd);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
205
214
|
s.turnCache.push({
|
|
206
215
|
read: Number(usage.cache_read_input_tokens) || 0,
|
|
207
216
|
miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
|
|
@@ -209,6 +218,7 @@ function parseSession(text2, opts = {}) {
|
|
|
209
218
|
}
|
|
210
219
|
}
|
|
211
220
|
}
|
|
221
|
+
s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd7]) => ({ t, usd: usd7 }));
|
|
212
222
|
s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
|
|
213
223
|
let best = null;
|
|
214
224
|
let bestCount = 0;
|
|
@@ -1212,10 +1222,11 @@ function sizeFix(cmd) {
|
|
|
1212
1222
|
action: "Your CLAUDE.md is thin. Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
|
|
1213
1223
|
};
|
|
1214
1224
|
}
|
|
1215
|
-
function synthesize(report, pillars, cmd) {
|
|
1225
|
+
function synthesize(report, pillars, cmd, plan = "api") {
|
|
1216
1226
|
const headlineWasteUsd = cacheMissExposureUsd(report);
|
|
1217
|
-
const headlineWasteLabel = "Recoverable spend (cache-miss exposure)";
|
|
1227
|
+
const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
|
|
1218
1228
|
const spend = report.summary.cost_usd;
|
|
1229
|
+
const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
|
|
1219
1230
|
const exposure = headlineWasteUsd;
|
|
1220
1231
|
const fixes = [];
|
|
1221
1232
|
const covered = /* @__PURE__ */ new Set();
|
|
@@ -1388,10 +1399,79 @@ function synthesize(report, pillars, cmd) {
|
|
|
1388
1399
|
return {
|
|
1389
1400
|
headlineWasteUsd,
|
|
1390
1401
|
headlineWasteLabel,
|
|
1402
|
+
headlineWasteShare,
|
|
1391
1403
|
fixes
|
|
1392
1404
|
};
|
|
1393
1405
|
}
|
|
1394
1406
|
|
|
1407
|
+
// ../../packages/engine/src/windows.ts
|
|
1408
|
+
var BUCKET_MINUTES = 15;
|
|
1409
|
+
var WINDOW_BUCKETS = 5 * 60 / BUCKET_MINUTES;
|
|
1410
|
+
var WEEK_BUCKETS = 7 * 24 * 60 / BUCKET_MINUTES;
|
|
1411
|
+
function median(sortedAsc) {
|
|
1412
|
+
const n = sortedAsc.length;
|
|
1413
|
+
if (n === 0) return 0;
|
|
1414
|
+
const mid = Math.floor(n / 2);
|
|
1415
|
+
return n % 2 === 1 ? sortedAsc[mid] : (sortedAsc[mid - 1] + sortedAsc[mid]) / 2;
|
|
1416
|
+
}
|
|
1417
|
+
function p90Index(n) {
|
|
1418
|
+
return Math.max(0, Math.ceil(0.9 * n) - 1);
|
|
1419
|
+
}
|
|
1420
|
+
function computeWindowStats(report) {
|
|
1421
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1422
|
+
for (const project of report.projects) {
|
|
1423
|
+
for (const session of project.sessions) {
|
|
1424
|
+
for (const b of session.costBuckets) merged.set(b.t, (merged.get(b.t) ?? 0) + b.usd);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
const buckets = [...merged.entries()].sort((a, b) => a[0] - b[0]);
|
|
1428
|
+
if (buckets.length === 0) {
|
|
1429
|
+
return {
|
|
1430
|
+
assessed: false,
|
|
1431
|
+
windowsCount: 0,
|
|
1432
|
+
medianWindowUsd: 0,
|
|
1433
|
+
p90WindowUsd: 0,
|
|
1434
|
+
maxWindowUsd: 0,
|
|
1435
|
+
p90WindowActiveMinutes: 0,
|
|
1436
|
+
weeksCount: 0,
|
|
1437
|
+
medianWeekUsd: 0,
|
|
1438
|
+
maxWeekUsd: 0
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
const windows = [];
|
|
1442
|
+
let windowStart = -Infinity;
|
|
1443
|
+
for (const [t, usd7] of buckets) {
|
|
1444
|
+
if (t >= windowStart + WINDOW_BUCKETS) {
|
|
1445
|
+
windows.push({ usd: 0, activeMinutes: 0 });
|
|
1446
|
+
windowStart = t;
|
|
1447
|
+
}
|
|
1448
|
+
const w = windows[windows.length - 1];
|
|
1449
|
+
w.usd += usd7;
|
|
1450
|
+
w.activeMinutes += BUCKET_MINUTES;
|
|
1451
|
+
}
|
|
1452
|
+
const firstT = buckets[0][0];
|
|
1453
|
+
const weeks = /* @__PURE__ */ new Map();
|
|
1454
|
+
for (const [t, usd7] of buckets) {
|
|
1455
|
+
const week = Math.floor((t - firstT) / WEEK_BUCKETS);
|
|
1456
|
+
weeks.set(week, (weeks.get(week) ?? 0) + usd7);
|
|
1457
|
+
}
|
|
1458
|
+
const byUsd = windows.slice().sort((a, b) => a.usd - b.usd);
|
|
1459
|
+
const usdAsc = byUsd.map((w) => w.usd);
|
|
1460
|
+
const p90 = byUsd[p90Index(byUsd.length)];
|
|
1461
|
+
const weekUsdAsc = [...weeks.values()].sort((a, b) => a - b);
|
|
1462
|
+
return {
|
|
1463
|
+
assessed: true,
|
|
1464
|
+
windowsCount: windows.length,
|
|
1465
|
+
medianWindowUsd: median(usdAsc),
|
|
1466
|
+
p90WindowUsd: p90.usd,
|
|
1467
|
+
maxWindowUsd: usdAsc[usdAsc.length - 1],
|
|
1468
|
+
p90WindowActiveMinutes: p90.activeMinutes,
|
|
1469
|
+
weeksCount: weekUsdAsc.length,
|
|
1470
|
+
medianWeekUsd: median(weekUsdAsc),
|
|
1471
|
+
maxWeekUsd: weekUsdAsc[weekUsdAsc.length - 1]
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1395
1475
|
// ../../packages/engine/src/optimize.ts
|
|
1396
1476
|
function usd(n) {
|
|
1397
1477
|
const rounded = Math.round(n * 100) / 100;
|
|
@@ -1893,6 +1973,17 @@ function toUsageMetrics(report) {
|
|
|
1893
1973
|
pricingSnapshotDate: PRICING_SNAPSHOT_DATE
|
|
1894
1974
|
};
|
|
1895
1975
|
}
|
|
1976
|
+
function roundWindows(w) {
|
|
1977
|
+
return {
|
|
1978
|
+
...w,
|
|
1979
|
+
medianWindowUsd: round2(w.medianWindowUsd),
|
|
1980
|
+
p90WindowUsd: round2(w.p90WindowUsd),
|
|
1981
|
+
maxWindowUsd: round2(w.maxWindowUsd),
|
|
1982
|
+
p90WindowActiveMinutes: Math.round(w.p90WindowActiveMinutes),
|
|
1983
|
+
medianWeekUsd: round2(w.medianWeekUsd),
|
|
1984
|
+
maxWeekUsd: round2(w.maxWeekUsd)
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1896
1987
|
function cleanFix(f) {
|
|
1897
1988
|
return {
|
|
1898
1989
|
...f,
|
|
@@ -1913,7 +2004,8 @@ function buildAudit(input, opts = {}) {
|
|
|
1913
2004
|
const report = analyzeUploads(input.logs);
|
|
1914
2005
|
const cmd = analyzeClaudeMd(input.claudeMd);
|
|
1915
2006
|
const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire, input.setup);
|
|
1916
|
-
const
|
|
2007
|
+
const plan = input.plan ?? "api";
|
|
2008
|
+
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd, plan);
|
|
1917
2009
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
1918
2010
|
return {
|
|
1919
2011
|
schemaVersion: "1",
|
|
@@ -1932,6 +2024,9 @@ function buildAudit(input, opts = {}) {
|
|
|
1932
2024
|
band: { ...band, description: sanitizeText(band.description) },
|
|
1933
2025
|
headlineWasteUsd: round2(headlineWasteUsd),
|
|
1934
2026
|
headlineWasteLabel: sanitizeText(headlineWasteLabel),
|
|
2027
|
+
plan,
|
|
2028
|
+
headlineWasteShare: round4(headlineWasteShare),
|
|
2029
|
+
usageWindows: roundWindows(computeWindowStats(report)),
|
|
1935
2030
|
fixes: fixes.map(cleanFix),
|
|
1936
2031
|
writer: opts.writer ?? "template",
|
|
1937
2032
|
paid: false
|
|
@@ -1960,7 +2055,8 @@ function side(r) {
|
|
|
1960
2055
|
cacheHitRate: round42(m.cacheHitRate),
|
|
1961
2056
|
overallScore: r.overallScore,
|
|
1962
2057
|
band: r.band.label,
|
|
1963
|
-
sessionsCount: m.sessionsCount
|
|
2058
|
+
sessionsCount: m.sessionsCount,
|
|
2059
|
+
plan: r.plan
|
|
1964
2060
|
};
|
|
1965
2061
|
}
|
|
1966
2062
|
function diffAudits(a, b) {
|
|
@@ -2029,6 +2125,12 @@ var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
|
2029
2125
|
var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
2030
2126
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
2031
2127
|
|
|
2128
|
+
// src/audit-command.ts
|
|
2129
|
+
import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
2130
|
+
import { join as join4, resolve } from "path";
|
|
2131
|
+
import { homedir as homedir3 } from "os";
|
|
2132
|
+
import { spawn } from "child_process";
|
|
2133
|
+
|
|
2032
2134
|
// src/read-sessions.ts
|
|
2033
2135
|
import { readdir } from "fs/promises";
|
|
2034
2136
|
import { readFileSync, openSync, closeSync } from "fs";
|
|
@@ -2145,17 +2247,47 @@ function unassessedLine(pillars) {
|
|
|
2145
2247
|
}
|
|
2146
2248
|
function formatAudit(record, meta) {
|
|
2147
2249
|
const m = record.usageMetrics;
|
|
2250
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2251
|
+
const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
|
|
2252
|
+
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2148
2253
|
const lines = [];
|
|
2149
2254
|
lines.push("CostClaw audit");
|
|
2150
2255
|
lines.push(`Source: ${meta.root} (${meta.sessionCount} sessions across ${m.projectsCount} projects)`);
|
|
2151
2256
|
if (meta.claudeMdSource) lines.push(`CLAUDE.md: ${meta.claudeMdSource}`);
|
|
2152
2257
|
lines.push("");
|
|
2153
|
-
lines.push(
|
|
2258
|
+
lines.push(
|
|
2259
|
+
subscription ? `${record.headlineWasteLabel}: ${shareText} of analyzed usage (${usd2(record.headlineWasteUsd)} at API rates)` : `${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`
|
|
2260
|
+
);
|
|
2154
2261
|
lines.push("");
|
|
2155
|
-
lines.push(
|
|
2262
|
+
lines.push(
|
|
2263
|
+
`${subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed"}: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`
|
|
2264
|
+
);
|
|
2156
2265
|
lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
|
|
2157
2266
|
const mix = modelMix(m.modelBreakdown);
|
|
2158
2267
|
if (mix) lines.push(`Model spend: ${mix}`);
|
|
2268
|
+
const w = record.usageWindows;
|
|
2269
|
+
if (subscription) {
|
|
2270
|
+
lines.push(
|
|
2271
|
+
`Plan: ${record.plan}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).`
|
|
2272
|
+
);
|
|
2273
|
+
if (w?.assessed) {
|
|
2274
|
+
lines.push(
|
|
2275
|
+
`Usage windows (5h, like your rate limit): median ${usd2(w.medianWindowUsd)}, busiest ${usd2(w.p90WindowUsd)}; busiest week ${usd2(w.maxWeekUsd)} (API-equivalent)`
|
|
2276
|
+
);
|
|
2277
|
+
if (share >= 0.01 && share < 1) {
|
|
2278
|
+
const gain = share / (1 - share);
|
|
2279
|
+
const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
|
|
2280
|
+
lines.push(
|
|
2281
|
+
`Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`
|
|
2282
|
+
);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
} else if (meta.planSource === "default") {
|
|
2286
|
+
const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${usd2(w.medianWeekUsd)} at API rates.` : "";
|
|
2287
|
+
lines.push(
|
|
2288
|
+
`Dollar figures are API-equivalent rates.${burn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.`
|
|
2289
|
+
);
|
|
2290
|
+
}
|
|
2159
2291
|
if (m.topProjects.length > 0) {
|
|
2160
2292
|
lines.push("");
|
|
2161
2293
|
lines.push("Top projects by spend:");
|
|
@@ -2297,6 +2429,7 @@ h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
|
|
|
2297
2429
|
}
|
|
2298
2430
|
.banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
|
|
2299
2431
|
.banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
|
|
2432
|
+
.banner .amount-sub { font-size: 15px; font-weight: 500; margin-top: 2px; opacity: 0.9; }
|
|
2300
2433
|
.stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
|
|
2301
2434
|
.stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
|
|
2302
2435
|
.stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
@@ -2330,6 +2463,21 @@ ul.fixes { list-style: none; margin: 0; padding: 0; }
|
|
|
2330
2463
|
function renderHtml(record, meta) {
|
|
2331
2464
|
const m = record.usageMetrics;
|
|
2332
2465
|
const mix = modelMix(m.modelBreakdown);
|
|
2466
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2467
|
+
const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
|
|
2468
|
+
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2469
|
+
const bannerAmount = subscription ? `<div class="amount">${shareText} of analyzed usage</div><div class="amount-sub">${esc(usd3(record.headlineWasteUsd))} at API rates</div>` : `<div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>`;
|
|
2470
|
+
const spendLabel = subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed";
|
|
2471
|
+
const w = record.usageWindows;
|
|
2472
|
+
let headroom = "";
|
|
2473
|
+
if (subscription && w?.assessed && share >= 0.01 && share < 1) {
|
|
2474
|
+
const gain = share / (1 - share);
|
|
2475
|
+
const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
|
|
2476
|
+
headroom = ` Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`;
|
|
2477
|
+
}
|
|
2478
|
+
const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${esc(usd3(w.medianWeekUsd))} at API rates.` : "";
|
|
2479
|
+
const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).${headroom}</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
|
|
2480
|
+
const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd3(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (p90)</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest week</div><div class="v">${esc(usd3(w.maxWeekUsd))}</div></div></div>` : "";
|
|
2333
2481
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
2334
2482
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
2335
2483
|
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>`;
|
|
@@ -2352,15 +2500,16 @@ ${meta.claudeMdSource ? `<p class="sub">CLAUDE.md: ${esc(meta.claudeMdSource)}</
|
|
|
2352
2500
|
|
|
2353
2501
|
<div class="banner">
|
|
2354
2502
|
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
2355
|
-
|
|
2503
|
+
${bannerAmount}
|
|
2356
2504
|
</div>
|
|
2357
|
-
|
|
2505
|
+
${planNote}
|
|
2358
2506
|
<div class="stats">
|
|
2359
|
-
<div class="stat"><div class="k"
|
|
2507
|
+
<div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
|
|
2360
2508
|
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
2361
2509
|
<div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
2362
2510
|
${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${esc(mix)}</div></div>` : ""}
|
|
2363
2511
|
</div>
|
|
2512
|
+
${windowTiles}
|
|
2364
2513
|
|
|
2365
2514
|
<h2>Spend by project</h2>
|
|
2366
2515
|
<div class="chart">${projectChart(m.topProjects)}</div>
|
|
@@ -2408,7 +2557,10 @@ function renderCard(record) {
|
|
|
2408
2557
|
const strongest = strongestPillar(record.pillarScores);
|
|
2409
2558
|
const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
|
|
2410
2559
|
const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
|
|
2411
|
-
const
|
|
2560
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2561
|
+
const spend = record.usageMetrics.spendUsd;
|
|
2562
|
+
const share = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
|
|
2563
|
+
const wasteLine = subscription ? `Recoverable usage: ${(share * 100).toFixed(1)}%` : `Recoverable spend: ${usd4(record.headlineWasteUsd)}`;
|
|
2412
2564
|
const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
|
|
2413
2565
|
const scoreText = String(record.overallScore);
|
|
2414
2566
|
const scoreX = 32;
|
|
@@ -2421,7 +2573,7 @@ function renderCard(record) {
|
|
|
2421
2573
|
const statX = 32;
|
|
2422
2574
|
const statY = 224;
|
|
2423
2575
|
const statGap = 30;
|
|
2424
|
-
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,
|
|
2576
|
+
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, wasteLine, { 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>`;
|
|
2425
2577
|
}
|
|
2426
2578
|
|
|
2427
2579
|
// src/read-setup.ts
|
|
@@ -2469,9 +2621,49 @@ async function readSetup(home = homedir2()) {
|
|
|
2469
2621
|
};
|
|
2470
2622
|
}
|
|
2471
2623
|
|
|
2624
|
+
// src/config.ts
|
|
2625
|
+
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
2626
|
+
import { join as join3 } from "path";
|
|
2627
|
+
function configFile(dir) {
|
|
2628
|
+
return join3(dir, "config.json");
|
|
2629
|
+
}
|
|
2630
|
+
async function readRaw(dir) {
|
|
2631
|
+
try {
|
|
2632
|
+
const parsed = JSON.parse(await readFile2(configFile(dir), "utf8"));
|
|
2633
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
2634
|
+
} catch {
|
|
2635
|
+
return {};
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
async function readCliConfig(dir) {
|
|
2639
|
+
const raw = await readRaw(dir);
|
|
2640
|
+
const cfg = {};
|
|
2641
|
+
if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
|
|
2642
|
+
return cfg;
|
|
2643
|
+
}
|
|
2644
|
+
async function saveCliConfig(dir, patch) {
|
|
2645
|
+
const merged = { ...await readRaw(dir), ...patch };
|
|
2646
|
+
await mkdir(dir, { recursive: true });
|
|
2647
|
+
await writeFile(configFile(dir), JSON.stringify(merged, null, 2), "utf8");
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2472
2650
|
// src/audit-command.ts
|
|
2651
|
+
async function resolvePlan(configDir, flag) {
|
|
2652
|
+
if (flag) {
|
|
2653
|
+
try {
|
|
2654
|
+
await saveCliConfig(configDir, { plan: flag });
|
|
2655
|
+
} catch (err) {
|
|
2656
|
+
process.stderr.write(`Could not save the plan setting: ${err instanceof Error ? err.message : String(err)}
|
|
2657
|
+
`);
|
|
2658
|
+
}
|
|
2659
|
+
return { plan: flag, planSource: "flag" };
|
|
2660
|
+
}
|
|
2661
|
+
const saved = (await readCliConfig(configDir)).plan;
|
|
2662
|
+
return saved ? { plan: saved, planSource: "config" } : { plan: "api", planSource: "default" };
|
|
2663
|
+
}
|
|
2473
2664
|
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
2474
2665
|
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
2666
|
+
var SNAPSHOT_KEEP = 50;
|
|
2475
2667
|
function openInBrowser(target) {
|
|
2476
2668
|
try {
|
|
2477
2669
|
const platform = process.platform;
|
|
@@ -2492,12 +2684,12 @@ async function loadAuditInputs(opts) {
|
|
|
2492
2684
|
let claudeMd;
|
|
2493
2685
|
let claudeMdSource = null;
|
|
2494
2686
|
if (opts.claudeMdPath) {
|
|
2495
|
-
claudeMd = await
|
|
2687
|
+
claudeMd = await readFile3(opts.claudeMdPath, "utf8");
|
|
2496
2688
|
claudeMdSource = resolve(opts.claudeMdPath);
|
|
2497
2689
|
} else {
|
|
2498
|
-
const fallback =
|
|
2690
|
+
const fallback = join4(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
|
|
2499
2691
|
try {
|
|
2500
|
-
claudeMd = await
|
|
2692
|
+
claudeMd = await readFile3(fallback, "utf8");
|
|
2501
2693
|
claudeMdSource = fallback;
|
|
2502
2694
|
} catch {
|
|
2503
2695
|
}
|
|
@@ -2511,32 +2703,38 @@ async function runAudit(opts) {
|
|
|
2511
2703
|
home: opts.home
|
|
2512
2704
|
});
|
|
2513
2705
|
const setup = await readSetup();
|
|
2514
|
-
const
|
|
2706
|
+
const configDir = join4(opts.home ?? homedir3(), ".costclaw");
|
|
2707
|
+
const { plan, planSource } = await resolvePlan(configDir, opts.plan);
|
|
2708
|
+
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
|
|
2515
2709
|
let snapshotNotice = null;
|
|
2516
2710
|
try {
|
|
2517
|
-
const historyDir =
|
|
2518
|
-
await
|
|
2711
|
+
const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
|
|
2712
|
+
await mkdir2(historyDir, { recursive: true });
|
|
2519
2713
|
const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
|
|
2520
|
-
await
|
|
2714
|
+
await writeFile2(join4(historyDir, name), JSON.stringify(record, null, 2), "utf8");
|
|
2715
|
+
const snapshots = (await readdir2(historyDir)).filter((f) => f.endsWith(".json")).sort();
|
|
2716
|
+
for (const stale of snapshots.slice(0, Math.max(0, snapshots.length - SNAPSHOT_KEEP))) {
|
|
2717
|
+
await rm(join4(historyDir, stale), { force: true });
|
|
2718
|
+
}
|
|
2521
2719
|
snapshotNotice = "Snapshot saved for costclaw diff.";
|
|
2522
2720
|
} catch (err) {
|
|
2523
2721
|
process.stderr.write(`Could not save the audit snapshot: ${err instanceof Error ? err.message : String(err)}
|
|
2524
2722
|
`);
|
|
2525
2723
|
}
|
|
2526
|
-
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
2724
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
2527
2725
|
const notices = [];
|
|
2528
2726
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
2529
2727
|
if (opts.html) {
|
|
2530
2728
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
2531
|
-
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
2532
|
-
await
|
|
2729
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
2730
|
+
await writeFile2(target, doc, "utf8");
|
|
2533
2731
|
openInBrowser(target);
|
|
2534
2732
|
notices.push(`HTML report written to ${target}`);
|
|
2535
2733
|
}
|
|
2536
2734
|
if (opts.card) {
|
|
2537
2735
|
const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
|
|
2538
2736
|
const svg = renderCard(record);
|
|
2539
|
-
await
|
|
2737
|
+
await writeFile2(target, svg, "utf8");
|
|
2540
2738
|
notices.push(`Score card written to ${target}`);
|
|
2541
2739
|
}
|
|
2542
2740
|
if (opts.json) {
|
|
@@ -2548,12 +2746,13 @@ async function runAudit(opts) {
|
|
|
2548
2746
|
}
|
|
2549
2747
|
|
|
2550
2748
|
// src/optimize-command.ts
|
|
2551
|
-
import { mkdir as
|
|
2552
|
-
import { join as
|
|
2749
|
+
import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat as stat2 } from "fs/promises";
|
|
2750
|
+
import { join as join6, dirname } from "path";
|
|
2751
|
+
import { homedir as homedir4 } from "os";
|
|
2553
2752
|
|
|
2554
2753
|
// src/project-scan.ts
|
|
2555
|
-
import { readdir as
|
|
2556
|
-
import { join as
|
|
2754
|
+
import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
|
|
2755
|
+
import { join as join5, basename } from "path";
|
|
2557
2756
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
2558
2757
|
"node_modules",
|
|
2559
2758
|
".git",
|
|
@@ -2582,7 +2781,7 @@ var DIR_NOTES = {
|
|
|
2582
2781
|
};
|
|
2583
2782
|
async function readText(p) {
|
|
2584
2783
|
try {
|
|
2585
|
-
return await
|
|
2784
|
+
return await readFile4(p, "utf8");
|
|
2586
2785
|
} catch {
|
|
2587
2786
|
return null;
|
|
2588
2787
|
}
|
|
@@ -2592,7 +2791,7 @@ async function listEntries(dir) {
|
|
|
2592
2791
|
const dirs = [];
|
|
2593
2792
|
let entries;
|
|
2594
2793
|
try {
|
|
2595
|
-
entries = await
|
|
2794
|
+
entries = await readdir3(dir, { withFileTypes: true });
|
|
2596
2795
|
} catch {
|
|
2597
2796
|
return { files, dirs };
|
|
2598
2797
|
}
|
|
@@ -2693,7 +2892,7 @@ async function detectTestsLocation(dir, files, dirs) {
|
|
|
2693
2892
|
if (dirs.includes("__tests__")) return "tests in __tests__/";
|
|
2694
2893
|
if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
2695
2894
|
if (dirs.includes("src")) {
|
|
2696
|
-
const sub = await listEntries(
|
|
2895
|
+
const sub = await listEntries(join5(dir, "src"));
|
|
2697
2896
|
if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
|
|
2698
2897
|
return "tests alongside source (*.test.* / *.spec.*)";
|
|
2699
2898
|
}
|
|
@@ -2776,7 +2975,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
2776
2975
|
if (oneFileCmd !== null && "test" in scripts) {
|
|
2777
2976
|
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
2778
2977
|
}
|
|
2779
|
-
const tsconfig = parseJson(await readText(
|
|
2978
|
+
const tsconfig = parseJson(await readText(join5(dir, "tsconfig.json")));
|
|
2780
2979
|
if (tsconfig) {
|
|
2781
2980
|
const co = tsconfig.compilerOptions;
|
|
2782
2981
|
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
@@ -2879,7 +3078,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2879
3078
|
const deps = [];
|
|
2880
3079
|
const tables = /* @__PURE__ */ new Set();
|
|
2881
3080
|
let hasPoetry = false;
|
|
2882
|
-
const pyprojectText = await readText(
|
|
3081
|
+
const pyprojectText = await readText(join5(dir, "pyproject.toml"));
|
|
2883
3082
|
if (pyprojectText !== null) {
|
|
2884
3083
|
const parsed = parsePyproject(pyprojectText);
|
|
2885
3084
|
name = parsed.name;
|
|
@@ -2889,7 +3088,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2889
3088
|
hasPoetry = parsed.hasPoetry;
|
|
2890
3089
|
}
|
|
2891
3090
|
if (files.includes("requirements.txt")) {
|
|
2892
|
-
const reqText = await readText(
|
|
3091
|
+
const reqText = await readText(join5(dir, "requirements.txt"));
|
|
2893
3092
|
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
2894
3093
|
}
|
|
2895
3094
|
if (name !== null && name.trim() !== "") profile.name = name;
|
|
@@ -2923,7 +3122,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2923
3122
|
}
|
|
2924
3123
|
}
|
|
2925
3124
|
async function scanRust(dir, profile) {
|
|
2926
|
-
const text2 = await readText(
|
|
3125
|
+
const text2 = await readText(join5(dir, "Cargo.toml"));
|
|
2927
3126
|
pushUnique(profile.stack, "Rust");
|
|
2928
3127
|
profile.packageManager = "cargo";
|
|
2929
3128
|
if (text2 !== null) {
|
|
@@ -2949,7 +3148,7 @@ async function scanRust(dir, profile) {
|
|
|
2949
3148
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
2950
3149
|
}
|
|
2951
3150
|
async function scanGo(dir, profile) {
|
|
2952
|
-
const text2 = await readText(
|
|
3151
|
+
const text2 = await readText(join5(dir, "go.mod"));
|
|
2953
3152
|
pushUnique(profile.stack, "Go");
|
|
2954
3153
|
profile.packageManager = "go";
|
|
2955
3154
|
if (text2 !== null) {
|
|
@@ -3014,7 +3213,7 @@ async function scanProject(dir) {
|
|
|
3014
3213
|
const profile = emptyProfile(basename(dir));
|
|
3015
3214
|
const { files, dirs } = await listEntries(dir);
|
|
3016
3215
|
if (files.includes("package.json")) {
|
|
3017
|
-
const pkg = parseJson(await readText(
|
|
3216
|
+
const pkg = parseJson(await readText(join5(dir, "package.json")));
|
|
3018
3217
|
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
3019
3218
|
}
|
|
3020
3219
|
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
@@ -3027,7 +3226,7 @@ async function scanProject(dir) {
|
|
|
3027
3226
|
await scanGo(dir, profile);
|
|
3028
3227
|
}
|
|
3029
3228
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
3030
|
-
const text2 = await readText(
|
|
3229
|
+
const text2 = await readText(join5(dir, "Makefile"));
|
|
3031
3230
|
if (text2 !== null) {
|
|
3032
3231
|
for (const t of parseMakefile(text2)) {
|
|
3033
3232
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
@@ -3037,7 +3236,7 @@ async function scanProject(dir) {
|
|
|
3037
3236
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
3038
3237
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
3039
3238
|
if (readmeName) {
|
|
3040
|
-
const text2 = await readText(
|
|
3239
|
+
const text2 = await readText(join5(dir, readmeName));
|
|
3041
3240
|
if (text2 !== null) {
|
|
3042
3241
|
const parsed = parseReadme(text2);
|
|
3043
3242
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
@@ -3050,7 +3249,7 @@ async function scanProject(dir) {
|
|
|
3050
3249
|
profile.structure = await detectStructure(dir, dirs);
|
|
3051
3250
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
3052
3251
|
if (envFile) {
|
|
3053
|
-
const text2 = await readText(
|
|
3252
|
+
const text2 = await readText(join5(dir, envFile));
|
|
3054
3253
|
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
3055
3254
|
}
|
|
3056
3255
|
return profile;
|
|
@@ -3126,7 +3325,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
3126
3325
|
let existingText = "";
|
|
3127
3326
|
let existing = {};
|
|
3128
3327
|
if (await pathExists(target)) {
|
|
3129
|
-
existingText = await
|
|
3328
|
+
existingText = await readFile5(target, "utf8");
|
|
3130
3329
|
if (existingText.trim() !== "") {
|
|
3131
3330
|
let parsed;
|
|
3132
3331
|
try {
|
|
@@ -3153,9 +3352,9 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
3153
3352
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
3154
3353
|
const merged = { ...existing, permissions: mergedPerms };
|
|
3155
3354
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
3156
|
-
await
|
|
3157
|
-
await
|
|
3158
|
-
await
|
|
3355
|
+
await mkdir3(dirname(target), { recursive: true });
|
|
3356
|
+
await writeFile3(backup, existingText, "utf8");
|
|
3357
|
+
await writeFile3(target, mergedText, "utf8");
|
|
3159
3358
|
return [
|
|
3160
3359
|
`Merged the derived permission allowlist into ${target}`,
|
|
3161
3360
|
`Backed up the previous file to ${backup}`,
|
|
@@ -3170,17 +3369,18 @@ async function runOptimize(opts) {
|
|
|
3170
3369
|
const report = analyzeUploads(logs);
|
|
3171
3370
|
const cmd = analyzeClaudeMd(claudeMd);
|
|
3172
3371
|
const { pillars } = scorePillars(report, cmd, {});
|
|
3173
|
-
const {
|
|
3372
|
+
const { plan } = await resolvePlan(join6(opts.home ?? homedir4(), ".costclaw"), opts.plan);
|
|
3373
|
+
const { fixes } = synthesize(report, pillars, cmd, plan);
|
|
3174
3374
|
const projectDir = opts.projectDir || process.cwd();
|
|
3175
3375
|
const project = await scanProject(projectDir);
|
|
3176
3376
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
3177
3377
|
const recoverable = cacheMissExposureUsd(report);
|
|
3178
|
-
const outDir = opts.out ||
|
|
3179
|
-
await
|
|
3180
|
-
const playbookPath =
|
|
3181
|
-
await
|
|
3182
|
-
const settingsPath =
|
|
3183
|
-
await
|
|
3378
|
+
const outDir = opts.out || join6(process.cwd(), "costclaw-out");
|
|
3379
|
+
await mkdir3(outDir, { recursive: true });
|
|
3380
|
+
const playbookPath = join6(outDir, PLAYBOOK_NAME);
|
|
3381
|
+
await writeFile3(playbookPath, result.playbook, "utf8");
|
|
3382
|
+
const settingsPath = join6(outDir, SETTINGS_NAME);
|
|
3383
|
+
await writeFile3(settingsPath, result.settingsJson, "utf8");
|
|
3184
3384
|
const lines = [];
|
|
3185
3385
|
lines.push("CostClaw optimize");
|
|
3186
3386
|
lines.push("");
|
|
@@ -3194,10 +3394,10 @@ async function runOptimize(opts) {
|
|
|
3194
3394
|
}
|
|
3195
3395
|
let original = "";
|
|
3196
3396
|
if (await pathExists(target)) {
|
|
3197
|
-
original = await
|
|
3397
|
+
original = await readFile5(target, "utf8");
|
|
3198
3398
|
}
|
|
3199
|
-
await
|
|
3200
|
-
await
|
|
3399
|
+
await writeFile3(backup, original, "utf8");
|
|
3400
|
+
await writeFile3(target, result.optimizedClaudeMd, "utf8");
|
|
3201
3401
|
lines.push(`Backed up the original to ${backup}`);
|
|
3202
3402
|
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
3203
3403
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -3209,15 +3409,23 @@ async function runOptimize(opts) {
|
|
|
3209
3409
|
lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
|
|
3210
3410
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
3211
3411
|
} else {
|
|
3212
|
-
const optimizedPath =
|
|
3213
|
-
await
|
|
3412
|
+
const optimizedPath = join6(outDir, OPTIMIZED_NAME);
|
|
3413
|
+
await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
3214
3414
|
lines.push("Dry run (no files of yours were changed).");
|
|
3215
3415
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
3216
3416
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
3217
3417
|
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
3218
3418
|
lines.push("");
|
|
3219
3419
|
lines.push(describeDetection(project));
|
|
3220
|
-
|
|
3420
|
+
if (plan === "api") {
|
|
3421
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
|
|
3422
|
+
} else {
|
|
3423
|
+
const spend = report.summary.cost_usd;
|
|
3424
|
+
const share = spend > 0 ? recoverable / spend * 100 : 0;
|
|
3425
|
+
lines.push(
|
|
3426
|
+
`Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd5(recoverable)} at API rates)`
|
|
3427
|
+
);
|
|
3428
|
+
}
|
|
3221
3429
|
lines.push("");
|
|
3222
3430
|
lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
|
|
3223
3431
|
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
@@ -3226,7 +3434,7 @@ async function runOptimize(opts) {
|
|
|
3226
3434
|
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.");
|
|
3227
3435
|
}
|
|
3228
3436
|
if (opts.applySettings) {
|
|
3229
|
-
const target = opts.applySettingsPath ||
|
|
3437
|
+
const target = opts.applySettingsPath || join6(projectDir, ".claude", "settings.json");
|
|
3230
3438
|
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
3231
3439
|
lines.push("");
|
|
3232
3440
|
lines.push(...applyLines);
|
|
@@ -3242,7 +3450,7 @@ async function runOptimize(opts) {
|
|
|
3242
3450
|
}
|
|
3243
3451
|
|
|
3244
3452
|
// src/badge-command.ts
|
|
3245
|
-
import { writeFile as
|
|
3453
|
+
import { writeFile as writeFile4 } from "fs/promises";
|
|
3246
3454
|
import { resolve as resolve2 } from "path";
|
|
3247
3455
|
|
|
3248
3456
|
// src/badge.ts
|
|
@@ -3265,17 +3473,17 @@ function renderBadge(record) {
|
|
|
3265
3473
|
// src/badge-command.ts
|
|
3266
3474
|
var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
3267
3475
|
async function runBadge(opts) {
|
|
3268
|
-
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
3476
|
+
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
3269
3477
|
const svg = renderBadge(record);
|
|
3270
3478
|
const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
|
|
3271
|
-
await
|
|
3479
|
+
await writeFile4(target, svg, "utf8");
|
|
3272
3480
|
return { output: `Badge written to ${target}`, record, target };
|
|
3273
3481
|
}
|
|
3274
3482
|
|
|
3275
3483
|
// src/diff-command.ts
|
|
3276
|
-
import { readdir as
|
|
3277
|
-
import { join as
|
|
3278
|
-
import { homedir as
|
|
3484
|
+
import { readdir as readdir4, readFile as readFile6 } from "fs/promises";
|
|
3485
|
+
import { join as join7 } from "path";
|
|
3486
|
+
import { homedir as homedir5 } from "os";
|
|
3279
3487
|
|
|
3280
3488
|
// src/format-diff.ts
|
|
3281
3489
|
function usd6(n) {
|
|
@@ -3332,6 +3540,12 @@ function formatDiff(d) {
|
|
|
3332
3540
|
const delta = p.delta === null ? "" : ` (${signedInt(p.delta)})`;
|
|
3333
3541
|
lines.push(` ${p.name.padEnd(22)} ${before.padStart(3)} -> ${after.padStart(3)}${delta}`);
|
|
3334
3542
|
}
|
|
3543
|
+
if (d.current.plan && d.current.plan !== "api") {
|
|
3544
|
+
lines.push("");
|
|
3545
|
+
lines.push(
|
|
3546
|
+
`Plan: ${d.current.plan}. Dollar figures are API-equivalent token value on your subscription; recovering them buys rate-limit headroom, not money back.`
|
|
3547
|
+
);
|
|
3548
|
+
}
|
|
3335
3549
|
const { resolved, appeared, changed } = d.fixes;
|
|
3336
3550
|
if (resolved.length > 0) {
|
|
3337
3551
|
lines.push("");
|
|
@@ -3357,7 +3571,7 @@ function formatDiff(d) {
|
|
|
3357
3571
|
async function readRecord(path) {
|
|
3358
3572
|
let text2;
|
|
3359
3573
|
try {
|
|
3360
|
-
text2 = await
|
|
3574
|
+
text2 = await readFile6(path, "utf8");
|
|
3361
3575
|
} catch {
|
|
3362
3576
|
throw new Error(`Could not read ${path}.`);
|
|
3363
3577
|
}
|
|
@@ -3373,10 +3587,10 @@ async function runDiff(opts) {
|
|
|
3373
3587
|
let pathA = opts.fileA;
|
|
3374
3588
|
let pathB = opts.fileB;
|
|
3375
3589
|
if (!pathA || !pathB) {
|
|
3376
|
-
const dir =
|
|
3590
|
+
const dir = join7(opts.home ?? homedir5(), ".costclaw", "history");
|
|
3377
3591
|
let files = [];
|
|
3378
3592
|
try {
|
|
3379
|
-
files = (await
|
|
3593
|
+
files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
3380
3594
|
} catch {
|
|
3381
3595
|
}
|
|
3382
3596
|
if (files.length < 2) {
|
|
@@ -3384,8 +3598,8 @@ async function runDiff(opts) {
|
|
|
3384
3598
|
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
3385
3599
|
);
|
|
3386
3600
|
}
|
|
3387
|
-
pathA =
|
|
3388
|
-
pathB =
|
|
3601
|
+
pathA = join7(dir, files[files.length - 2]);
|
|
3602
|
+
pathB = join7(dir, files[files.length - 1]);
|
|
3389
3603
|
}
|
|
3390
3604
|
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
3391
3605
|
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
@@ -3393,9 +3607,9 @@ async function runDiff(opts) {
|
|
|
3393
3607
|
}
|
|
3394
3608
|
|
|
3395
3609
|
// src/license.ts
|
|
3396
|
-
import { mkdir as
|
|
3397
|
-
import { join as
|
|
3398
|
-
import { homedir as
|
|
3610
|
+
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
|
|
3611
|
+
import { join as join8 } from "path";
|
|
3612
|
+
import { homedir as homedir6, hostname } from "os";
|
|
3399
3613
|
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
3400
3614
|
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
3401
3615
|
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
@@ -3420,10 +3634,10 @@ var INVALID_MESSAGE = [
|
|
|
3420
3634
|
"costclaw audit stays free."
|
|
3421
3635
|
].join("\n");
|
|
3422
3636
|
function defaultConfigDir() {
|
|
3423
|
-
return
|
|
3637
|
+
return join8(homedir6(), ".costclaw");
|
|
3424
3638
|
}
|
|
3425
3639
|
function licenseFile(dir) {
|
|
3426
|
-
return
|
|
3640
|
+
return join8(dir, "license.json");
|
|
3427
3641
|
}
|
|
3428
3642
|
function base64UrlDecode(part) {
|
|
3429
3643
|
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
@@ -3447,7 +3661,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
|
3447
3661
|
}
|
|
3448
3662
|
async function readStoredLicense(dir) {
|
|
3449
3663
|
try {
|
|
3450
|
-
const data = JSON.parse(await
|
|
3664
|
+
const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
|
|
3451
3665
|
if (!data || typeof data.licenseKey !== "string") return null;
|
|
3452
3666
|
return data;
|
|
3453
3667
|
} catch {
|
|
@@ -3455,11 +3669,11 @@ async function readStoredLicense(dir) {
|
|
|
3455
3669
|
}
|
|
3456
3670
|
}
|
|
3457
3671
|
async function writeStoredLicense(dir, lic) {
|
|
3458
|
-
await
|
|
3459
|
-
await
|
|
3672
|
+
await mkdir4(dir, { recursive: true });
|
|
3673
|
+
await writeFile5(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
3460
3674
|
}
|
|
3461
3675
|
async function clearStoredLicense(dir) {
|
|
3462
|
-
await
|
|
3676
|
+
await rm2(licenseFile(dir), { force: true });
|
|
3463
3677
|
}
|
|
3464
3678
|
async function activateLicense(licenseKey, opts = {}) {
|
|
3465
3679
|
const key = licenseKey.trim();
|
|
@@ -3514,6 +3728,14 @@ function optionalPathAfter(args, flag) {
|
|
|
3514
3728
|
const next = args[i + 1];
|
|
3515
3729
|
return next !== void 0 && !next.startsWith("-") ? next : void 0;
|
|
3516
3730
|
}
|
|
3731
|
+
function planFlag(args) {
|
|
3732
|
+
if (!args.includes("--plan")) return void 0;
|
|
3733
|
+
const value = getFlag(args, "--plan");
|
|
3734
|
+
if (value === void 0 || !isPlan(value)) {
|
|
3735
|
+
throw new Error(`--plan must be one of: ${PLANS.join(", ")}`);
|
|
3736
|
+
}
|
|
3737
|
+
return value;
|
|
3738
|
+
}
|
|
3517
3739
|
function parseAuditFlags(args) {
|
|
3518
3740
|
const html = args.includes("--html");
|
|
3519
3741
|
const card = args.includes("--card");
|
|
@@ -3524,7 +3746,8 @@ function parseAuditFlags(args) {
|
|
|
3524
3746
|
html,
|
|
3525
3747
|
htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
|
|
3526
3748
|
card,
|
|
3527
|
-
cardPath: card ? optionalPathAfter(args, "--card") : void 0
|
|
3749
|
+
cardPath: card ? optionalPathAfter(args, "--card") : void 0,
|
|
3750
|
+
plan: planFlag(args)
|
|
3528
3751
|
};
|
|
3529
3752
|
}
|
|
3530
3753
|
function parseBadgeFlags(args) {
|
|
@@ -3535,14 +3758,14 @@ function parseBadgeFlags(args) {
|
|
|
3535
3758
|
};
|
|
3536
3759
|
}
|
|
3537
3760
|
function cliVersion() {
|
|
3538
|
-
return true ? "0.
|
|
3761
|
+
return true ? "0.4.0" : "0.0.0-dev";
|
|
3539
3762
|
}
|
|
3540
3763
|
function helpText() {
|
|
3541
3764
|
return [
|
|
3542
3765
|
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
3543
3766
|
"",
|
|
3544
3767
|
"Usage:",
|
|
3545
|
-
" costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
|
|
3768
|
+
" costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]",
|
|
3546
3769
|
" costclaw diff [<baseline.json> <current.json>] [--json]",
|
|
3547
3770
|
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
3548
3771
|
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
@@ -3556,6 +3779,12 @@ function helpText() {
|
|
|
3556
3779
|
"it in your browser; the terminal report still prints.",
|
|
3557
3780
|
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
3558
3781
|
"score, band, recoverable spend, cache hit rate, and your strongest pillar.",
|
|
3782
|
+
"--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
|
|
3783
|
+
"subscription (Pro/Max) the dollar figures are API-equivalent token value, not",
|
|
3784
|
+
"money back, so the audit reframes the headline as recoverable usage: the share",
|
|
3785
|
+
"of your token consumption (and rate-limit headroom) you could win back. The",
|
|
3786
|
+
"value is saved to ~/.costclaw/config.json so later runs remember it;",
|
|
3787
|
+
"--plan api switches back.",
|
|
3559
3788
|
"",
|
|
3560
3789
|
"diff compares two audits and shows the movement: new spend since the baseline,",
|
|
3561
3790
|
"the marginal cache hit rate for just that period, score changes per pillar, and",
|
|
@@ -3640,6 +3869,7 @@ Run: costclaw optimize
|
|
|
3640
3869
|
const { output } = await runOptimize({
|
|
3641
3870
|
path: getFlag(args, "--path"),
|
|
3642
3871
|
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3872
|
+
plan: planFlag(args),
|
|
3643
3873
|
projectDir: getFlag(args, "--project") || process.cwd(),
|
|
3644
3874
|
out: getFlag(args, "--out"),
|
|
3645
3875
|
write: getFlag(args, "--write"),
|
|
@@ -3664,5 +3894,6 @@ export {
|
|
|
3664
3894
|
cliVersion,
|
|
3665
3895
|
helpText,
|
|
3666
3896
|
parseAuditFlags,
|
|
3667
|
-
parseBadgeFlags
|
|
3897
|
+
parseBadgeFlags,
|
|
3898
|
+
planFlag
|
|
3668
3899
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
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": {
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
],
|
|
32
32
|
"scripts": {
|
|
33
33
|
"audit": "tsx src/index.ts audit",
|
|
34
|
+
"diff": "tsx src/index.ts diff",
|
|
34
35
|
"optimize": "tsx src/index.ts optimize",
|
|
35
36
|
"dev": "tsx src/index.ts",
|
|
36
37
|
"build": "tsup",
|