costclaw 0.2.4 → 0.3.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 +32 -2
- package/dist/index.js +201 -86
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -44,15 +44,44 @@ 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
|
+
```
|
|
69
|
+
|
|
70
|
+
The value is saved to `~/.costclaw/config.json`, so later runs (and `optimize`)
|
|
71
|
+
remember it. The findings and their ranking are identical either way; only the
|
|
72
|
+
unit is framed to match how you actually pay.
|
|
73
|
+
|
|
47
74
|
## Options
|
|
48
75
|
|
|
49
76
|
```
|
|
50
|
-
costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]
|
|
77
|
+
costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]
|
|
51
78
|
```
|
|
52
79
|
|
|
53
80
|
- `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
|
|
54
81
|
- `--claude-md <file>` score a specific CLAUDE.md file's quality (by default the
|
|
55
82
|
audit scores `~/.claude/CLAUDE.md` when it exists).
|
|
83
|
+
- `--plan <api|pro|max5x|max20x>` declare how you pay for Claude (see above);
|
|
84
|
+
persisted for later runs.
|
|
56
85
|
- `--json` print the raw, derived `AuditRecord` instead of the human report.
|
|
57
86
|
- `--html [file]` also write a self-contained HTML report (default
|
|
58
87
|
`costclaw-report.html` in the current directory) and open it in your browser.
|
|
@@ -97,7 +126,8 @@ Fixes resolved since the baseline:
|
|
|
97
126
|
The marginal cache hit rate covers only the period between the two audits, which
|
|
98
127
|
a lifetime average hides. You can also diff two explicit records saved with
|
|
99
128
|
`costclaw audit --json`: `costclaw diff baseline.json current.json`. Add `--json`
|
|
100
|
-
for the machine-readable diff. Free, like the audit.
|
|
129
|
+
for the machine-readable diff. Free, like the audit. The history keeps the newest
|
|
130
|
+
50 snapshots and prunes older ones automatically.
|
|
101
131
|
|
|
102
132
|
## Badge
|
|
103
133
|
|
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";
|
|
@@ -1212,10 +1210,11 @@ function sizeFix(cmd) {
|
|
|
1212
1210
|
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
1211
|
};
|
|
1214
1212
|
}
|
|
1215
|
-
function synthesize(report, pillars, cmd) {
|
|
1213
|
+
function synthesize(report, pillars, cmd, plan = "api") {
|
|
1216
1214
|
const headlineWasteUsd = cacheMissExposureUsd(report);
|
|
1217
|
-
const headlineWasteLabel = "Recoverable spend (cache-miss exposure)";
|
|
1215
|
+
const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
|
|
1218
1216
|
const spend = report.summary.cost_usd;
|
|
1217
|
+
const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
|
|
1219
1218
|
const exposure = headlineWasteUsd;
|
|
1220
1219
|
const fixes = [];
|
|
1221
1220
|
const covered = /* @__PURE__ */ new Set();
|
|
@@ -1388,6 +1387,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1388
1387
|
return {
|
|
1389
1388
|
headlineWasteUsd,
|
|
1390
1389
|
headlineWasteLabel,
|
|
1390
|
+
headlineWasteShare,
|
|
1391
1391
|
fixes
|
|
1392
1392
|
};
|
|
1393
1393
|
}
|
|
@@ -1913,7 +1913,8 @@ function buildAudit(input, opts = {}) {
|
|
|
1913
1913
|
const report = analyzeUploads(input.logs);
|
|
1914
1914
|
const cmd = analyzeClaudeMd(input.claudeMd);
|
|
1915
1915
|
const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire, input.setup);
|
|
1916
|
-
const
|
|
1916
|
+
const plan = input.plan ?? "api";
|
|
1917
|
+
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd, plan);
|
|
1917
1918
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
1918
1919
|
return {
|
|
1919
1920
|
schemaVersion: "1",
|
|
@@ -1932,6 +1933,8 @@ function buildAudit(input, opts = {}) {
|
|
|
1932
1933
|
band: { ...band, description: sanitizeText(band.description) },
|
|
1933
1934
|
headlineWasteUsd: round2(headlineWasteUsd),
|
|
1934
1935
|
headlineWasteLabel: sanitizeText(headlineWasteLabel),
|
|
1936
|
+
plan,
|
|
1937
|
+
headlineWasteShare: round4(headlineWasteShare),
|
|
1935
1938
|
fixes: fixes.map(cleanFix),
|
|
1936
1939
|
writer: opts.writer ?? "template",
|
|
1937
1940
|
paid: false
|
|
@@ -1960,7 +1963,8 @@ function side(r) {
|
|
|
1960
1963
|
cacheHitRate: round42(m.cacheHitRate),
|
|
1961
1964
|
overallScore: r.overallScore,
|
|
1962
1965
|
band: r.band.label,
|
|
1963
|
-
sessionsCount: m.sessionsCount
|
|
1966
|
+
sessionsCount: m.sessionsCount,
|
|
1967
|
+
plan: r.plan
|
|
1964
1968
|
};
|
|
1965
1969
|
}
|
|
1966
1970
|
function diffAudits(a, b) {
|
|
@@ -2029,6 +2033,12 @@ var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
|
2029
2033
|
var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
2030
2034
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
2031
2035
|
|
|
2036
|
+
// src/audit-command.ts
|
|
2037
|
+
import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
2038
|
+
import { join as join4, resolve } from "path";
|
|
2039
|
+
import { homedir as homedir3 } from "os";
|
|
2040
|
+
import { spawn } from "child_process";
|
|
2041
|
+
|
|
2032
2042
|
// src/read-sessions.ts
|
|
2033
2043
|
import { readdir } from "fs/promises";
|
|
2034
2044
|
import { readFileSync, openSync, closeSync } from "fs";
|
|
@@ -2145,17 +2155,33 @@ function unassessedLine(pillars) {
|
|
|
2145
2155
|
}
|
|
2146
2156
|
function formatAudit(record, meta) {
|
|
2147
2157
|
const m = record.usageMetrics;
|
|
2158
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2159
|
+
const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
|
|
2160
|
+
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2148
2161
|
const lines = [];
|
|
2149
2162
|
lines.push("CostClaw audit");
|
|
2150
2163
|
lines.push(`Source: ${meta.root} (${meta.sessionCount} sessions across ${m.projectsCount} projects)`);
|
|
2151
2164
|
if (meta.claudeMdSource) lines.push(`CLAUDE.md: ${meta.claudeMdSource}`);
|
|
2152
2165
|
lines.push("");
|
|
2153
|
-
lines.push(
|
|
2166
|
+
lines.push(
|
|
2167
|
+
subscription ? `${record.headlineWasteLabel}: ${shareText} of analyzed usage (${usd2(record.headlineWasteUsd)} at API rates)` : `${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`
|
|
2168
|
+
);
|
|
2154
2169
|
lines.push("");
|
|
2155
|
-
lines.push(
|
|
2170
|
+
lines.push(
|
|
2171
|
+
`${subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed"}: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`
|
|
2172
|
+
);
|
|
2156
2173
|
lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
|
|
2157
2174
|
const mix = modelMix(m.modelBreakdown);
|
|
2158
2175
|
if (mix) lines.push(`Model spend: ${mix}`);
|
|
2176
|
+
if (subscription) {
|
|
2177
|
+
lines.push(
|
|
2178
|
+
`Plan: ${record.plan}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).`
|
|
2179
|
+
);
|
|
2180
|
+
} else if (meta.planSource === "default") {
|
|
2181
|
+
lines.push(
|
|
2182
|
+
"Dollar figures are API-equivalent rates. On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency."
|
|
2183
|
+
);
|
|
2184
|
+
}
|
|
2159
2185
|
if (m.topProjects.length > 0) {
|
|
2160
2186
|
lines.push("");
|
|
2161
2187
|
lines.push("Top projects by spend:");
|
|
@@ -2297,6 +2323,7 @@ h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
|
|
|
2297
2323
|
}
|
|
2298
2324
|
.banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
|
|
2299
2325
|
.banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
|
|
2326
|
+
.banner .amount-sub { font-size: 15px; font-weight: 500; margin-top: 2px; opacity: 0.9; }
|
|
2300
2327
|
.stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
|
|
2301
2328
|
.stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
|
|
2302
2329
|
.stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
@@ -2330,6 +2357,12 @@ ul.fixes { list-style: none; margin: 0; padding: 0; }
|
|
|
2330
2357
|
function renderHtml(record, meta) {
|
|
2331
2358
|
const m = record.usageMetrics;
|
|
2332
2359
|
const mix = modelMix(m.modelBreakdown);
|
|
2360
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2361
|
+
const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
|
|
2362
|
+
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2363
|
+
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>`;
|
|
2364
|
+
const spendLabel = subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed";
|
|
2365
|
+
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).</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates. On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
|
|
2333
2366
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
2334
2367
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
2335
2368
|
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,11 +2385,11 @@ ${meta.claudeMdSource ? `<p class="sub">CLAUDE.md: ${esc(meta.claudeMdSource)}</
|
|
|
2352
2385
|
|
|
2353
2386
|
<div class="banner">
|
|
2354
2387
|
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
2355
|
-
|
|
2388
|
+
${bannerAmount}
|
|
2356
2389
|
</div>
|
|
2357
|
-
|
|
2390
|
+
${planNote}
|
|
2358
2391
|
<div class="stats">
|
|
2359
|
-
<div class="stat"><div class="k"
|
|
2392
|
+
<div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
|
|
2360
2393
|
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
2361
2394
|
<div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
2362
2395
|
${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${esc(mix)}</div></div>` : ""}
|
|
@@ -2408,7 +2441,10 @@ function renderCard(record) {
|
|
|
2408
2441
|
const strongest = strongestPillar(record.pillarScores);
|
|
2409
2442
|
const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
|
|
2410
2443
|
const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
|
|
2411
|
-
const
|
|
2444
|
+
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
2445
|
+
const spend = record.usageMetrics.spendUsd;
|
|
2446
|
+
const share = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
|
|
2447
|
+
const wasteLine = subscription ? `Recoverable usage: ${(share * 100).toFixed(1)}%` : `Recoverable spend: ${usd4(record.headlineWasteUsd)}`;
|
|
2412
2448
|
const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
|
|
2413
2449
|
const scoreText = String(record.overallScore);
|
|
2414
2450
|
const scoreX = 32;
|
|
@@ -2421,7 +2457,7 @@ function renderCard(record) {
|
|
|
2421
2457
|
const statX = 32;
|
|
2422
2458
|
const statY = 224;
|
|
2423
2459
|
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,
|
|
2460
|
+
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
2461
|
}
|
|
2426
2462
|
|
|
2427
2463
|
// src/read-setup.ts
|
|
@@ -2469,9 +2505,49 @@ async function readSetup(home = homedir2()) {
|
|
|
2469
2505
|
};
|
|
2470
2506
|
}
|
|
2471
2507
|
|
|
2508
|
+
// src/config.ts
|
|
2509
|
+
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
2510
|
+
import { join as join3 } from "path";
|
|
2511
|
+
function configFile(dir) {
|
|
2512
|
+
return join3(dir, "config.json");
|
|
2513
|
+
}
|
|
2514
|
+
async function readRaw(dir) {
|
|
2515
|
+
try {
|
|
2516
|
+
const parsed = JSON.parse(await readFile2(configFile(dir), "utf8"));
|
|
2517
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
2518
|
+
} catch {
|
|
2519
|
+
return {};
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
async function readCliConfig(dir) {
|
|
2523
|
+
const raw = await readRaw(dir);
|
|
2524
|
+
const cfg = {};
|
|
2525
|
+
if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
|
|
2526
|
+
return cfg;
|
|
2527
|
+
}
|
|
2528
|
+
async function saveCliConfig(dir, patch) {
|
|
2529
|
+
const merged = { ...await readRaw(dir), ...patch };
|
|
2530
|
+
await mkdir(dir, { recursive: true });
|
|
2531
|
+
await writeFile(configFile(dir), JSON.stringify(merged, null, 2), "utf8");
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2472
2534
|
// src/audit-command.ts
|
|
2535
|
+
async function resolvePlan(configDir, flag) {
|
|
2536
|
+
if (flag) {
|
|
2537
|
+
try {
|
|
2538
|
+
await saveCliConfig(configDir, { plan: flag });
|
|
2539
|
+
} catch (err) {
|
|
2540
|
+
process.stderr.write(`Could not save the plan setting: ${err instanceof Error ? err.message : String(err)}
|
|
2541
|
+
`);
|
|
2542
|
+
}
|
|
2543
|
+
return { plan: flag, planSource: "flag" };
|
|
2544
|
+
}
|
|
2545
|
+
const saved = (await readCliConfig(configDir)).plan;
|
|
2546
|
+
return saved ? { plan: saved, planSource: "config" } : { plan: "api", planSource: "default" };
|
|
2547
|
+
}
|
|
2473
2548
|
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
2474
2549
|
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
2550
|
+
var SNAPSHOT_KEEP = 50;
|
|
2475
2551
|
function openInBrowser(target) {
|
|
2476
2552
|
try {
|
|
2477
2553
|
const platform = process.platform;
|
|
@@ -2492,12 +2568,12 @@ async function loadAuditInputs(opts) {
|
|
|
2492
2568
|
let claudeMd;
|
|
2493
2569
|
let claudeMdSource = null;
|
|
2494
2570
|
if (opts.claudeMdPath) {
|
|
2495
|
-
claudeMd = await
|
|
2571
|
+
claudeMd = await readFile3(opts.claudeMdPath, "utf8");
|
|
2496
2572
|
claudeMdSource = resolve(opts.claudeMdPath);
|
|
2497
2573
|
} else {
|
|
2498
|
-
const fallback =
|
|
2574
|
+
const fallback = join4(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
|
|
2499
2575
|
try {
|
|
2500
|
-
claudeMd = await
|
|
2576
|
+
claudeMd = await readFile3(fallback, "utf8");
|
|
2501
2577
|
claudeMdSource = fallback;
|
|
2502
2578
|
} catch {
|
|
2503
2579
|
}
|
|
@@ -2511,32 +2587,38 @@ async function runAudit(opts) {
|
|
|
2511
2587
|
home: opts.home
|
|
2512
2588
|
});
|
|
2513
2589
|
const setup = await readSetup();
|
|
2514
|
-
const
|
|
2590
|
+
const configDir = join4(opts.home ?? homedir3(), ".costclaw");
|
|
2591
|
+
const { plan, planSource } = await resolvePlan(configDir, opts.plan);
|
|
2592
|
+
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
|
|
2515
2593
|
let snapshotNotice = null;
|
|
2516
2594
|
try {
|
|
2517
|
-
const historyDir =
|
|
2518
|
-
await
|
|
2595
|
+
const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
|
|
2596
|
+
await mkdir2(historyDir, { recursive: true });
|
|
2519
2597
|
const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
|
|
2520
|
-
await
|
|
2598
|
+
await writeFile2(join4(historyDir, name), JSON.stringify(record, null, 2), "utf8");
|
|
2599
|
+
const snapshots = (await readdir2(historyDir)).filter((f) => f.endsWith(".json")).sort();
|
|
2600
|
+
for (const stale of snapshots.slice(0, Math.max(0, snapshots.length - SNAPSHOT_KEEP))) {
|
|
2601
|
+
await rm(join4(historyDir, stale), { force: true });
|
|
2602
|
+
}
|
|
2521
2603
|
snapshotNotice = "Snapshot saved for costclaw diff.";
|
|
2522
2604
|
} catch (err) {
|
|
2523
2605
|
process.stderr.write(`Could not save the audit snapshot: ${err instanceof Error ? err.message : String(err)}
|
|
2524
2606
|
`);
|
|
2525
2607
|
}
|
|
2526
|
-
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
2608
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
2527
2609
|
const notices = [];
|
|
2528
2610
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
2529
2611
|
if (opts.html) {
|
|
2530
2612
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
2531
|
-
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
2532
|
-
await
|
|
2613
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
2614
|
+
await writeFile2(target, doc, "utf8");
|
|
2533
2615
|
openInBrowser(target);
|
|
2534
2616
|
notices.push(`HTML report written to ${target}`);
|
|
2535
2617
|
}
|
|
2536
2618
|
if (opts.card) {
|
|
2537
2619
|
const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
|
|
2538
2620
|
const svg = renderCard(record);
|
|
2539
|
-
await
|
|
2621
|
+
await writeFile2(target, svg, "utf8");
|
|
2540
2622
|
notices.push(`Score card written to ${target}`);
|
|
2541
2623
|
}
|
|
2542
2624
|
if (opts.json) {
|
|
@@ -2548,12 +2630,13 @@ async function runAudit(opts) {
|
|
|
2548
2630
|
}
|
|
2549
2631
|
|
|
2550
2632
|
// src/optimize-command.ts
|
|
2551
|
-
import { mkdir as
|
|
2552
|
-
import { join as
|
|
2633
|
+
import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat as stat2 } from "fs/promises";
|
|
2634
|
+
import { join as join6, dirname } from "path";
|
|
2635
|
+
import { homedir as homedir4 } from "os";
|
|
2553
2636
|
|
|
2554
2637
|
// src/project-scan.ts
|
|
2555
|
-
import { readdir as
|
|
2556
|
-
import { join as
|
|
2638
|
+
import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
|
|
2639
|
+
import { join as join5, basename } from "path";
|
|
2557
2640
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
2558
2641
|
"node_modules",
|
|
2559
2642
|
".git",
|
|
@@ -2582,7 +2665,7 @@ var DIR_NOTES = {
|
|
|
2582
2665
|
};
|
|
2583
2666
|
async function readText(p) {
|
|
2584
2667
|
try {
|
|
2585
|
-
return await
|
|
2668
|
+
return await readFile4(p, "utf8");
|
|
2586
2669
|
} catch {
|
|
2587
2670
|
return null;
|
|
2588
2671
|
}
|
|
@@ -2592,7 +2675,7 @@ async function listEntries(dir) {
|
|
|
2592
2675
|
const dirs = [];
|
|
2593
2676
|
let entries;
|
|
2594
2677
|
try {
|
|
2595
|
-
entries = await
|
|
2678
|
+
entries = await readdir3(dir, { withFileTypes: true });
|
|
2596
2679
|
} catch {
|
|
2597
2680
|
return { files, dirs };
|
|
2598
2681
|
}
|
|
@@ -2693,7 +2776,7 @@ async function detectTestsLocation(dir, files, dirs) {
|
|
|
2693
2776
|
if (dirs.includes("__tests__")) return "tests in __tests__/";
|
|
2694
2777
|
if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
2695
2778
|
if (dirs.includes("src")) {
|
|
2696
|
-
const sub = await listEntries(
|
|
2779
|
+
const sub = await listEntries(join5(dir, "src"));
|
|
2697
2780
|
if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
|
|
2698
2781
|
return "tests alongside source (*.test.* / *.spec.*)";
|
|
2699
2782
|
}
|
|
@@ -2776,7 +2859,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
2776
2859
|
if (oneFileCmd !== null && "test" in scripts) {
|
|
2777
2860
|
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
2778
2861
|
}
|
|
2779
|
-
const tsconfig = parseJson(await readText(
|
|
2862
|
+
const tsconfig = parseJson(await readText(join5(dir, "tsconfig.json")));
|
|
2780
2863
|
if (tsconfig) {
|
|
2781
2864
|
const co = tsconfig.compilerOptions;
|
|
2782
2865
|
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
@@ -2879,7 +2962,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2879
2962
|
const deps = [];
|
|
2880
2963
|
const tables = /* @__PURE__ */ new Set();
|
|
2881
2964
|
let hasPoetry = false;
|
|
2882
|
-
const pyprojectText = await readText(
|
|
2965
|
+
const pyprojectText = await readText(join5(dir, "pyproject.toml"));
|
|
2883
2966
|
if (pyprojectText !== null) {
|
|
2884
2967
|
const parsed = parsePyproject(pyprojectText);
|
|
2885
2968
|
name = parsed.name;
|
|
@@ -2889,7 +2972,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2889
2972
|
hasPoetry = parsed.hasPoetry;
|
|
2890
2973
|
}
|
|
2891
2974
|
if (files.includes("requirements.txt")) {
|
|
2892
|
-
const reqText = await readText(
|
|
2975
|
+
const reqText = await readText(join5(dir, "requirements.txt"));
|
|
2893
2976
|
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
2894
2977
|
}
|
|
2895
2978
|
if (name !== null && name.trim() !== "") profile.name = name;
|
|
@@ -2923,7 +3006,7 @@ async function scanPython(dir, files, profile) {
|
|
|
2923
3006
|
}
|
|
2924
3007
|
}
|
|
2925
3008
|
async function scanRust(dir, profile) {
|
|
2926
|
-
const text2 = await readText(
|
|
3009
|
+
const text2 = await readText(join5(dir, "Cargo.toml"));
|
|
2927
3010
|
pushUnique(profile.stack, "Rust");
|
|
2928
3011
|
profile.packageManager = "cargo";
|
|
2929
3012
|
if (text2 !== null) {
|
|
@@ -2949,7 +3032,7 @@ async function scanRust(dir, profile) {
|
|
|
2949
3032
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
2950
3033
|
}
|
|
2951
3034
|
async function scanGo(dir, profile) {
|
|
2952
|
-
const text2 = await readText(
|
|
3035
|
+
const text2 = await readText(join5(dir, "go.mod"));
|
|
2953
3036
|
pushUnique(profile.stack, "Go");
|
|
2954
3037
|
profile.packageManager = "go";
|
|
2955
3038
|
if (text2 !== null) {
|
|
@@ -3014,7 +3097,7 @@ async function scanProject(dir) {
|
|
|
3014
3097
|
const profile = emptyProfile(basename(dir));
|
|
3015
3098
|
const { files, dirs } = await listEntries(dir);
|
|
3016
3099
|
if (files.includes("package.json")) {
|
|
3017
|
-
const pkg = parseJson(await readText(
|
|
3100
|
+
const pkg = parseJson(await readText(join5(dir, "package.json")));
|
|
3018
3101
|
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
3019
3102
|
}
|
|
3020
3103
|
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
@@ -3027,7 +3110,7 @@ async function scanProject(dir) {
|
|
|
3027
3110
|
await scanGo(dir, profile);
|
|
3028
3111
|
}
|
|
3029
3112
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
3030
|
-
const text2 = await readText(
|
|
3113
|
+
const text2 = await readText(join5(dir, "Makefile"));
|
|
3031
3114
|
if (text2 !== null) {
|
|
3032
3115
|
for (const t of parseMakefile(text2)) {
|
|
3033
3116
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
@@ -3037,7 +3120,7 @@ async function scanProject(dir) {
|
|
|
3037
3120
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
3038
3121
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
3039
3122
|
if (readmeName) {
|
|
3040
|
-
const text2 = await readText(
|
|
3123
|
+
const text2 = await readText(join5(dir, readmeName));
|
|
3041
3124
|
if (text2 !== null) {
|
|
3042
3125
|
const parsed = parseReadme(text2);
|
|
3043
3126
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
@@ -3050,7 +3133,7 @@ async function scanProject(dir) {
|
|
|
3050
3133
|
profile.structure = await detectStructure(dir, dirs);
|
|
3051
3134
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
3052
3135
|
if (envFile) {
|
|
3053
|
-
const text2 = await readText(
|
|
3136
|
+
const text2 = await readText(join5(dir, envFile));
|
|
3054
3137
|
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
3055
3138
|
}
|
|
3056
3139
|
return profile;
|
|
@@ -3126,7 +3209,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
3126
3209
|
let existingText = "";
|
|
3127
3210
|
let existing = {};
|
|
3128
3211
|
if (await pathExists(target)) {
|
|
3129
|
-
existingText = await
|
|
3212
|
+
existingText = await readFile5(target, "utf8");
|
|
3130
3213
|
if (existingText.trim() !== "") {
|
|
3131
3214
|
let parsed;
|
|
3132
3215
|
try {
|
|
@@ -3153,9 +3236,9 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
3153
3236
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
3154
3237
|
const merged = { ...existing, permissions: mergedPerms };
|
|
3155
3238
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
3156
|
-
await
|
|
3157
|
-
await
|
|
3158
|
-
await
|
|
3239
|
+
await mkdir3(dirname(target), { recursive: true });
|
|
3240
|
+
await writeFile3(backup, existingText, "utf8");
|
|
3241
|
+
await writeFile3(target, mergedText, "utf8");
|
|
3159
3242
|
return [
|
|
3160
3243
|
`Merged the derived permission allowlist into ${target}`,
|
|
3161
3244
|
`Backed up the previous file to ${backup}`,
|
|
@@ -3170,17 +3253,18 @@ async function runOptimize(opts) {
|
|
|
3170
3253
|
const report = analyzeUploads(logs);
|
|
3171
3254
|
const cmd = analyzeClaudeMd(claudeMd);
|
|
3172
3255
|
const { pillars } = scorePillars(report, cmd, {});
|
|
3173
|
-
const {
|
|
3256
|
+
const { plan } = await resolvePlan(join6(opts.home ?? homedir4(), ".costclaw"), opts.plan);
|
|
3257
|
+
const { fixes } = synthesize(report, pillars, cmd, plan);
|
|
3174
3258
|
const projectDir = opts.projectDir || process.cwd();
|
|
3175
3259
|
const project = await scanProject(projectDir);
|
|
3176
3260
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
3177
3261
|
const recoverable = cacheMissExposureUsd(report);
|
|
3178
|
-
const outDir = opts.out ||
|
|
3179
|
-
await
|
|
3180
|
-
const playbookPath =
|
|
3181
|
-
await
|
|
3182
|
-
const settingsPath =
|
|
3183
|
-
await
|
|
3262
|
+
const outDir = opts.out || join6(process.cwd(), "costclaw-out");
|
|
3263
|
+
await mkdir3(outDir, { recursive: true });
|
|
3264
|
+
const playbookPath = join6(outDir, PLAYBOOK_NAME);
|
|
3265
|
+
await writeFile3(playbookPath, result.playbook, "utf8");
|
|
3266
|
+
const settingsPath = join6(outDir, SETTINGS_NAME);
|
|
3267
|
+
await writeFile3(settingsPath, result.settingsJson, "utf8");
|
|
3184
3268
|
const lines = [];
|
|
3185
3269
|
lines.push("CostClaw optimize");
|
|
3186
3270
|
lines.push("");
|
|
@@ -3194,10 +3278,10 @@ async function runOptimize(opts) {
|
|
|
3194
3278
|
}
|
|
3195
3279
|
let original = "";
|
|
3196
3280
|
if (await pathExists(target)) {
|
|
3197
|
-
original = await
|
|
3281
|
+
original = await readFile5(target, "utf8");
|
|
3198
3282
|
}
|
|
3199
|
-
await
|
|
3200
|
-
await
|
|
3283
|
+
await writeFile3(backup, original, "utf8");
|
|
3284
|
+
await writeFile3(target, result.optimizedClaudeMd, "utf8");
|
|
3201
3285
|
lines.push(`Backed up the original to ${backup}`);
|
|
3202
3286
|
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
3203
3287
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -3209,15 +3293,23 @@ async function runOptimize(opts) {
|
|
|
3209
3293
|
lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
|
|
3210
3294
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
3211
3295
|
} else {
|
|
3212
|
-
const optimizedPath =
|
|
3213
|
-
await
|
|
3296
|
+
const optimizedPath = join6(outDir, OPTIMIZED_NAME);
|
|
3297
|
+
await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
3214
3298
|
lines.push("Dry run (no files of yours were changed).");
|
|
3215
3299
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
3216
3300
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
3217
3301
|
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
3218
3302
|
lines.push("");
|
|
3219
3303
|
lines.push(describeDetection(project));
|
|
3220
|
-
|
|
3304
|
+
if (plan === "api") {
|
|
3305
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
|
|
3306
|
+
} else {
|
|
3307
|
+
const spend = report.summary.cost_usd;
|
|
3308
|
+
const share = spend > 0 ? recoverable / spend * 100 : 0;
|
|
3309
|
+
lines.push(
|
|
3310
|
+
`Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd5(recoverable)} at API rates)`
|
|
3311
|
+
);
|
|
3312
|
+
}
|
|
3221
3313
|
lines.push("");
|
|
3222
3314
|
lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
|
|
3223
3315
|
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
@@ -3226,7 +3318,7 @@ async function runOptimize(opts) {
|
|
|
3226
3318
|
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
3319
|
}
|
|
3228
3320
|
if (opts.applySettings) {
|
|
3229
|
-
const target = opts.applySettingsPath ||
|
|
3321
|
+
const target = opts.applySettingsPath || join6(projectDir, ".claude", "settings.json");
|
|
3230
3322
|
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
3231
3323
|
lines.push("");
|
|
3232
3324
|
lines.push(...applyLines);
|
|
@@ -3242,7 +3334,7 @@ async function runOptimize(opts) {
|
|
|
3242
3334
|
}
|
|
3243
3335
|
|
|
3244
3336
|
// src/badge-command.ts
|
|
3245
|
-
import { writeFile as
|
|
3337
|
+
import { writeFile as writeFile4 } from "fs/promises";
|
|
3246
3338
|
import { resolve as resolve2 } from "path";
|
|
3247
3339
|
|
|
3248
3340
|
// src/badge.ts
|
|
@@ -3265,17 +3357,17 @@ function renderBadge(record) {
|
|
|
3265
3357
|
// src/badge-command.ts
|
|
3266
3358
|
var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
3267
3359
|
async function runBadge(opts) {
|
|
3268
|
-
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
3360
|
+
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
3269
3361
|
const svg = renderBadge(record);
|
|
3270
3362
|
const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
|
|
3271
|
-
await
|
|
3363
|
+
await writeFile4(target, svg, "utf8");
|
|
3272
3364
|
return { output: `Badge written to ${target}`, record, target };
|
|
3273
3365
|
}
|
|
3274
3366
|
|
|
3275
3367
|
// src/diff-command.ts
|
|
3276
|
-
import { readdir as
|
|
3277
|
-
import { join as
|
|
3278
|
-
import { homedir as
|
|
3368
|
+
import { readdir as readdir4, readFile as readFile6 } from "fs/promises";
|
|
3369
|
+
import { join as join7 } from "path";
|
|
3370
|
+
import { homedir as homedir5 } from "os";
|
|
3279
3371
|
|
|
3280
3372
|
// src/format-diff.ts
|
|
3281
3373
|
function usd6(n) {
|
|
@@ -3332,6 +3424,12 @@ function formatDiff(d) {
|
|
|
3332
3424
|
const delta = p.delta === null ? "" : ` (${signedInt(p.delta)})`;
|
|
3333
3425
|
lines.push(` ${p.name.padEnd(22)} ${before.padStart(3)} -> ${after.padStart(3)}${delta}`);
|
|
3334
3426
|
}
|
|
3427
|
+
if (d.current.plan && d.current.plan !== "api") {
|
|
3428
|
+
lines.push("");
|
|
3429
|
+
lines.push(
|
|
3430
|
+
`Plan: ${d.current.plan}. Dollar figures are API-equivalent token value on your subscription; recovering them buys rate-limit headroom, not money back.`
|
|
3431
|
+
);
|
|
3432
|
+
}
|
|
3335
3433
|
const { resolved, appeared, changed } = d.fixes;
|
|
3336
3434
|
if (resolved.length > 0) {
|
|
3337
3435
|
lines.push("");
|
|
@@ -3357,7 +3455,7 @@ function formatDiff(d) {
|
|
|
3357
3455
|
async function readRecord(path) {
|
|
3358
3456
|
let text2;
|
|
3359
3457
|
try {
|
|
3360
|
-
text2 = await
|
|
3458
|
+
text2 = await readFile6(path, "utf8");
|
|
3361
3459
|
} catch {
|
|
3362
3460
|
throw new Error(`Could not read ${path}.`);
|
|
3363
3461
|
}
|
|
@@ -3373,10 +3471,10 @@ async function runDiff(opts) {
|
|
|
3373
3471
|
let pathA = opts.fileA;
|
|
3374
3472
|
let pathB = opts.fileB;
|
|
3375
3473
|
if (!pathA || !pathB) {
|
|
3376
|
-
const dir =
|
|
3474
|
+
const dir = join7(opts.home ?? homedir5(), ".costclaw", "history");
|
|
3377
3475
|
let files = [];
|
|
3378
3476
|
try {
|
|
3379
|
-
files = (await
|
|
3477
|
+
files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
3380
3478
|
} catch {
|
|
3381
3479
|
}
|
|
3382
3480
|
if (files.length < 2) {
|
|
@@ -3384,8 +3482,8 @@ async function runDiff(opts) {
|
|
|
3384
3482
|
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
3385
3483
|
);
|
|
3386
3484
|
}
|
|
3387
|
-
pathA =
|
|
3388
|
-
pathB =
|
|
3485
|
+
pathA = join7(dir, files[files.length - 2]);
|
|
3486
|
+
pathB = join7(dir, files[files.length - 1]);
|
|
3389
3487
|
}
|
|
3390
3488
|
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
3391
3489
|
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
@@ -3393,9 +3491,9 @@ async function runDiff(opts) {
|
|
|
3393
3491
|
}
|
|
3394
3492
|
|
|
3395
3493
|
// src/license.ts
|
|
3396
|
-
import { mkdir as
|
|
3397
|
-
import { join as
|
|
3398
|
-
import { homedir as
|
|
3494
|
+
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
|
|
3495
|
+
import { join as join8 } from "path";
|
|
3496
|
+
import { homedir as homedir6, hostname } from "os";
|
|
3399
3497
|
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
3400
3498
|
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
3401
3499
|
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
@@ -3420,10 +3518,10 @@ var INVALID_MESSAGE = [
|
|
|
3420
3518
|
"costclaw audit stays free."
|
|
3421
3519
|
].join("\n");
|
|
3422
3520
|
function defaultConfigDir() {
|
|
3423
|
-
return
|
|
3521
|
+
return join8(homedir6(), ".costclaw");
|
|
3424
3522
|
}
|
|
3425
3523
|
function licenseFile(dir) {
|
|
3426
|
-
return
|
|
3524
|
+
return join8(dir, "license.json");
|
|
3427
3525
|
}
|
|
3428
3526
|
function base64UrlDecode(part) {
|
|
3429
3527
|
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
@@ -3447,7 +3545,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
|
3447
3545
|
}
|
|
3448
3546
|
async function readStoredLicense(dir) {
|
|
3449
3547
|
try {
|
|
3450
|
-
const data = JSON.parse(await
|
|
3548
|
+
const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
|
|
3451
3549
|
if (!data || typeof data.licenseKey !== "string") return null;
|
|
3452
3550
|
return data;
|
|
3453
3551
|
} catch {
|
|
@@ -3455,11 +3553,11 @@ async function readStoredLicense(dir) {
|
|
|
3455
3553
|
}
|
|
3456
3554
|
}
|
|
3457
3555
|
async function writeStoredLicense(dir, lic) {
|
|
3458
|
-
await
|
|
3459
|
-
await
|
|
3556
|
+
await mkdir4(dir, { recursive: true });
|
|
3557
|
+
await writeFile5(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
3460
3558
|
}
|
|
3461
3559
|
async function clearStoredLicense(dir) {
|
|
3462
|
-
await
|
|
3560
|
+
await rm2(licenseFile(dir), { force: true });
|
|
3463
3561
|
}
|
|
3464
3562
|
async function activateLicense(licenseKey, opts = {}) {
|
|
3465
3563
|
const key = licenseKey.trim();
|
|
@@ -3514,6 +3612,14 @@ function optionalPathAfter(args, flag) {
|
|
|
3514
3612
|
const next = args[i + 1];
|
|
3515
3613
|
return next !== void 0 && !next.startsWith("-") ? next : void 0;
|
|
3516
3614
|
}
|
|
3615
|
+
function planFlag(args) {
|
|
3616
|
+
if (!args.includes("--plan")) return void 0;
|
|
3617
|
+
const value = getFlag(args, "--plan");
|
|
3618
|
+
if (value === void 0 || !isPlan(value)) {
|
|
3619
|
+
throw new Error(`--plan must be one of: ${PLANS.join(", ")}`);
|
|
3620
|
+
}
|
|
3621
|
+
return value;
|
|
3622
|
+
}
|
|
3517
3623
|
function parseAuditFlags(args) {
|
|
3518
3624
|
const html = args.includes("--html");
|
|
3519
3625
|
const card = args.includes("--card");
|
|
@@ -3524,7 +3630,8 @@ function parseAuditFlags(args) {
|
|
|
3524
3630
|
html,
|
|
3525
3631
|
htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
|
|
3526
3632
|
card,
|
|
3527
|
-
cardPath: card ? optionalPathAfter(args, "--card") : void 0
|
|
3633
|
+
cardPath: card ? optionalPathAfter(args, "--card") : void 0,
|
|
3634
|
+
plan: planFlag(args)
|
|
3528
3635
|
};
|
|
3529
3636
|
}
|
|
3530
3637
|
function parseBadgeFlags(args) {
|
|
@@ -3535,14 +3642,14 @@ function parseBadgeFlags(args) {
|
|
|
3535
3642
|
};
|
|
3536
3643
|
}
|
|
3537
3644
|
function cliVersion() {
|
|
3538
|
-
return true ? "0.
|
|
3645
|
+
return true ? "0.3.0" : "0.0.0-dev";
|
|
3539
3646
|
}
|
|
3540
3647
|
function helpText() {
|
|
3541
3648
|
return [
|
|
3542
3649
|
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
3543
3650
|
"",
|
|
3544
3651
|
"Usage:",
|
|
3545
|
-
" costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
|
|
3652
|
+
" costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]",
|
|
3546
3653
|
" costclaw diff [<baseline.json> <current.json>] [--json]",
|
|
3547
3654
|
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
3548
3655
|
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
@@ -3556,6 +3663,12 @@ function helpText() {
|
|
|
3556
3663
|
"it in your browser; the terminal report still prints.",
|
|
3557
3664
|
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
3558
3665
|
"score, band, recoverable spend, cache hit rate, and your strongest pillar.",
|
|
3666
|
+
"--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
|
|
3667
|
+
"subscription (Pro/Max) the dollar figures are API-equivalent token value, not",
|
|
3668
|
+
"money back, so the audit reframes the headline as recoverable usage: the share",
|
|
3669
|
+
"of your token consumption (and rate-limit headroom) you could win back. The",
|
|
3670
|
+
"value is saved to ~/.costclaw/config.json so later runs remember it;",
|
|
3671
|
+
"--plan api switches back.",
|
|
3559
3672
|
"",
|
|
3560
3673
|
"diff compares two audits and shows the movement: new spend since the baseline,",
|
|
3561
3674
|
"the marginal cache hit rate for just that period, score changes per pillar, and",
|
|
@@ -3640,6 +3753,7 @@ Run: costclaw optimize
|
|
|
3640
3753
|
const { output } = await runOptimize({
|
|
3641
3754
|
path: getFlag(args, "--path"),
|
|
3642
3755
|
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3756
|
+
plan: planFlag(args),
|
|
3643
3757
|
projectDir: getFlag(args, "--project") || process.cwd(),
|
|
3644
3758
|
out: getFlag(args, "--out"),
|
|
3645
3759
|
write: getFlag(args, "--write"),
|
|
@@ -3664,5 +3778,6 @@ export {
|
|
|
3664
3778
|
cliVersion,
|
|
3665
3779
|
helpText,
|
|
3666
3780
|
parseAuditFlags,
|
|
3667
|
-
parseBadgeFlags
|
|
3781
|
+
parseBadgeFlags,
|
|
3782
|
+
planFlag
|
|
3668
3783
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|