costclaw 0.2.2 → 0.2.4
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 +34 -0
- package/dist/index.js +261 -29
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,6 +65,40 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--c
|
|
|
65
65
|
Run `costclaw --version` (or `-v` / `costclaw version`) to print the installed
|
|
66
66
|
CLI version.
|
|
67
67
|
|
|
68
|
+
## Diff
|
|
69
|
+
|
|
70
|
+
Every audit run saves a snapshot of the derived record to `~/.costclaw/history`
|
|
71
|
+
(local, nothing uploaded). Run the audit again after you have made changes, then:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
npx costclaw diff
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
That compares your latest two audits and shows the movement, so you can verify
|
|
78
|
+
the fixes actually recovered dollars:
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
CostClaw diff
|
|
82
|
+
Baseline: 2026-06-09 Current: 2026-07-09 (30 days)
|
|
83
|
+
|
|
84
|
+
Since the baseline:
|
|
85
|
+
New spend $842.10 across 210 new sessions
|
|
86
|
+
Marginal cache hit 97.1% (lifetime 96.2%)
|
|
87
|
+
Recoverable exposure +$96.40 (now $1131.61)
|
|
88
|
+
|
|
89
|
+
Overall setup score: 83 -> 86 (+3, Tight)
|
|
90
|
+
CLAUDE.md quality 69 -> 78 (+9)
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
Fixes resolved since the baseline:
|
|
94
|
+
- [$52.40] Use a cheaper model for 61 small sessions
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The marginal cache hit rate covers only the period between the two audits, which
|
|
98
|
+
a lifetime average hides. You can also diff two explicit records saved with
|
|
99
|
+
`costclaw audit --json`: `costclaw diff baseline.json current.json`. Add `--json`
|
|
100
|
+
for the machine-readable diff. Free, like the audit.
|
|
101
|
+
|
|
68
102
|
## Badge
|
|
69
103
|
|
|
70
104
|
```bash
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
5
|
|
|
6
6
|
// src/audit-command.ts
|
|
7
|
-
import { readFile as readFile2, writeFile } from "fs/promises";
|
|
7
|
+
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
8
8
|
import { join as join3, resolve } from "path";
|
|
9
9
|
import { homedir as homedir3 } from "os";
|
|
10
10
|
import { spawn } from "child_process";
|
|
@@ -1219,9 +1219,9 @@ function synthesize(report, pillars, cmd) {
|
|
|
1219
1219
|
const exposure = headlineWasteUsd;
|
|
1220
1220
|
const fixes = [];
|
|
1221
1221
|
const covered = /* @__PURE__ */ new Set();
|
|
1222
|
-
const
|
|
1223
|
-
const
|
|
1224
|
-
const fixed =
|
|
1222
|
+
const round23 = (n) => Math.round(n * 100) / 100;
|
|
1223
|
+
const usd7 = (n) => {
|
|
1224
|
+
const fixed = round23(n).toFixed(2);
|
|
1225
1225
|
const dot = fixed.indexOf(".");
|
|
1226
1226
|
const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1227
1227
|
return `$${whole}${fixed.slice(dot)}`;
|
|
@@ -1246,9 +1246,9 @@ function synthesize(report, pillars, cmd) {
|
|
|
1246
1246
|
pillar: "context_hygiene",
|
|
1247
1247
|
pillarName: PILLARS.context_hygiene.name,
|
|
1248
1248
|
severity: sevForUsd(exposure),
|
|
1249
|
-
wasteUsd:
|
|
1249
|
+
wasteUsd: round23(exposure),
|
|
1250
1250
|
problem: sanitizeText(
|
|
1251
|
-
`Up to ${
|
|
1251
|
+
`Up to ${usd7(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
1252
1252
|
),
|
|
1253
1253
|
action: sanitizeText(
|
|
1254
1254
|
"Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
|
|
@@ -1328,8 +1328,8 @@ function synthesize(report, pillars, cmd) {
|
|
|
1328
1328
|
pillar: "cost_discipline",
|
|
1329
1329
|
pillarName: PILLARS.cost_discipline.name,
|
|
1330
1330
|
severity: sevForUsd(misrouteUsd),
|
|
1331
|
-
wasteUsd:
|
|
1332
|
-
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${
|
|
1331
|
+
wasteUsd: round23(misrouteUsd),
|
|
1332
|
+
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd7(misrouteUsd)} more than a cheaper model would have.`),
|
|
1333
1333
|
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
|
|
1334
1334
|
basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1335
1335
|
});
|
|
@@ -1342,8 +1342,8 @@ function synthesize(report, pillars, cmd) {
|
|
|
1342
1342
|
pillar: "session_mgmt",
|
|
1343
1343
|
pillarName: PILLARS.session_mgmt.name,
|
|
1344
1344
|
severity: sevForUsd(marathonUsd),
|
|
1345
|
-
wasteUsd:
|
|
1346
|
-
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${
|
|
1345
|
+
wasteUsd: round23(marathonUsd),
|
|
1346
|
+
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd7(marathonUsd)} for context in the later turns.`),
|
|
1347
1347
|
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1348
1348
|
basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
|
|
1349
1349
|
});
|
|
@@ -1356,7 +1356,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1356
1356
|
pillarName: PILLARS.cost_discipline.name,
|
|
1357
1357
|
severity: "info",
|
|
1358
1358
|
wasteUsd: 0,
|
|
1359
|
-
problem: sanitizeText(`Workflow and subagent runs cost about ${
|
|
1359
|
+
problem: sanitizeText(`Workflow and subagent runs cost about ${usd7(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
|
|
1360
1360
|
action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
|
|
1361
1361
|
basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
|
|
1362
1362
|
});
|
|
@@ -1878,7 +1878,7 @@ function toUsageMetrics(report) {
|
|
|
1878
1878
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
1879
1879
|
}));
|
|
1880
1880
|
const modelBreakdown = {};
|
|
1881
|
-
for (const [model,
|
|
1881
|
+
for (const [model, usd7] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd7);
|
|
1882
1882
|
return {
|
|
1883
1883
|
spendUsd: round2(s.cost_usd),
|
|
1884
1884
|
cacheSavingsUsd: round2(s.cache_savings_usd),
|
|
@@ -1938,6 +1938,92 @@ function buildAudit(input, opts = {}) {
|
|
|
1938
1938
|
};
|
|
1939
1939
|
}
|
|
1940
1940
|
|
|
1941
|
+
// ../../packages/engine/src/diff.ts
|
|
1942
|
+
var DIFF_SCHEMA_VERSION = "1";
|
|
1943
|
+
function round22(n) {
|
|
1944
|
+
return Math.round(n * 100) / 100;
|
|
1945
|
+
}
|
|
1946
|
+
function round42(n) {
|
|
1947
|
+
return Math.round(n * 1e4) / 1e4;
|
|
1948
|
+
}
|
|
1949
|
+
function assertRecord(r) {
|
|
1950
|
+
if (!r || typeof r !== "object" || !r.usageMetrics || !Array.isArray(r.pillarScores) || typeof r.overallScore !== "number" || typeof r.createdAt !== "string") {
|
|
1951
|
+
throw new Error("Not a costclaw audit record (run costclaw audit --json to produce one).");
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
function side(r) {
|
|
1955
|
+
const m = r.usageMetrics;
|
|
1956
|
+
return {
|
|
1957
|
+
createdAt: r.createdAt,
|
|
1958
|
+
spendUsd: round22(m.spendUsd),
|
|
1959
|
+
recoverableUsd: round22(r.headlineWasteUsd),
|
|
1960
|
+
cacheHitRate: round42(m.cacheHitRate),
|
|
1961
|
+
overallScore: r.overallScore,
|
|
1962
|
+
band: r.band.label,
|
|
1963
|
+
sessionsCount: m.sessionsCount
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
function diffAudits(a, b) {
|
|
1967
|
+
assertRecord(a);
|
|
1968
|
+
assertRecord(b);
|
|
1969
|
+
const [base, cur] = Date.parse(a.createdAt) <= Date.parse(b.createdAt) ? [a, b] : [b, a];
|
|
1970
|
+
const bm = base.usageMetrics;
|
|
1971
|
+
const cm = cur.usageMetrics;
|
|
1972
|
+
const newTokens = {
|
|
1973
|
+
input_tokens: cm.totalTokens.input_tokens - bm.totalTokens.input_tokens,
|
|
1974
|
+
output_tokens: cm.totalTokens.output_tokens - bm.totalTokens.output_tokens,
|
|
1975
|
+
cache_creation_tokens: cm.totalTokens.cache_creation_tokens - bm.totalTokens.cache_creation_tokens,
|
|
1976
|
+
cache_read_tokens: cm.totalTokens.cache_read_tokens - bm.totalTokens.cache_read_tokens
|
|
1977
|
+
};
|
|
1978
|
+
const newSpendUsd = cm.spendUsd - bm.spendUsd;
|
|
1979
|
+
const newSessions = cm.sessionsCount - bm.sessionsCount;
|
|
1980
|
+
const comparable = newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
|
|
1981
|
+
const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
|
|
1982
|
+
const periodDays = round22(Math.max(0, periodMs) / 864e5);
|
|
1983
|
+
const pillars = base.pillarScores.map((bp) => {
|
|
1984
|
+
const cp = cur.pillarScores.find((p) => p.id === bp.id);
|
|
1985
|
+
const before = bp.assessed ? bp.score : null;
|
|
1986
|
+
const after = cp && cp.assessed ? cp.score : null;
|
|
1987
|
+
return {
|
|
1988
|
+
id: bp.id,
|
|
1989
|
+
name: bp.name,
|
|
1990
|
+
before,
|
|
1991
|
+
after,
|
|
1992
|
+
delta: before !== null && after !== null ? after - before : null
|
|
1993
|
+
};
|
|
1994
|
+
});
|
|
1995
|
+
const baseFixes = new Map(base.fixes.map((f) => [f.id, f]));
|
|
1996
|
+
const curFixes = new Map(cur.fixes.map((f) => [f.id, f]));
|
|
1997
|
+
const resolved = base.fixes.filter((f) => !curFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
|
|
1998
|
+
const appeared = cur.fixes.filter((f) => !baseFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
|
|
1999
|
+
const changed = cur.fixes.filter((f) => baseFixes.has(f.id)).map((f) => {
|
|
2000
|
+
const beforeUsd = round22(baseFixes.get(f.id).wasteUsd);
|
|
2001
|
+
const afterUsd = round22(f.wasteUsd);
|
|
2002
|
+
return { id: f.id, title: f.title, beforeUsd, afterUsd, deltaUsd: round22(afterUsd - beforeUsd) };
|
|
2003
|
+
}).filter((c) => Math.abs(c.deltaUsd) >= 0.01);
|
|
2004
|
+
return {
|
|
2005
|
+
schemaVersion: DIFF_SCHEMA_VERSION,
|
|
2006
|
+
baseline: side(base),
|
|
2007
|
+
current: side(cur),
|
|
2008
|
+
periodDays,
|
|
2009
|
+
comparable,
|
|
2010
|
+
marginal: comparable ? {
|
|
2011
|
+
newSpendUsd: round22(newSpendUsd),
|
|
2012
|
+
newSessions,
|
|
2013
|
+
marginalCacheHitRate: round42(cacheHitRate(newTokens)),
|
|
2014
|
+
newTokens
|
|
2015
|
+
} : null,
|
|
2016
|
+
deltas: {
|
|
2017
|
+
spendUsd: round22(cm.spendUsd - bm.spendUsd),
|
|
2018
|
+
recoverableUsd: round22(cur.headlineWasteUsd - base.headlineWasteUsd),
|
|
2019
|
+
overallScore: cur.overallScore - base.overallScore,
|
|
2020
|
+
cacheHitRatePoints: round42(cm.cacheHitRate - bm.cacheHitRate)
|
|
2021
|
+
},
|
|
2022
|
+
pillars,
|
|
2023
|
+
fixes: { resolved, appeared, changed }
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
|
|
1941
2027
|
// ../../packages/engine/src/validate.ts
|
|
1942
2028
|
var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
1943
2029
|
var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
@@ -2044,7 +2130,7 @@ function modelMix(breakdown) {
|
|
|
2044
2130
|
}
|
|
2045
2131
|
const total = [...merged.values()].reduce((a, b) => a + b, 0);
|
|
2046
2132
|
if (total <= 0) return null;
|
|
2047
|
-
const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([,
|
|
2133
|
+
const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct2]) => pct2 >= 1).map(([name, pct2]) => `${name} ${pct2}%`);
|
|
2048
2134
|
return parts.length > 0 ? parts.join(" / ") : null;
|
|
2049
2135
|
}
|
|
2050
2136
|
function unassessedLine(pillars) {
|
|
@@ -2093,7 +2179,7 @@ function formatAudit(record, meta) {
|
|
|
2093
2179
|
if (dollarFixes.length === 0) {
|
|
2094
2180
|
lines.push(" No directly recoverable dollars found. See issues below.");
|
|
2095
2181
|
} else {
|
|
2096
|
-
for (const f of dollarFixes
|
|
2182
|
+
for (const f of dollarFixes) {
|
|
2097
2183
|
lines.push(` - [${usd2(f.wasteUsd)}] ${f.title}`);
|
|
2098
2184
|
lines.push(` ${f.action}`);
|
|
2099
2185
|
if (f.basis) lines.push(` Evidence: ${f.basis}`);
|
|
@@ -2102,13 +2188,10 @@ function formatAudit(record, meta) {
|
|
|
2102
2188
|
if (otherIssues.length > 0) {
|
|
2103
2189
|
lines.push("");
|
|
2104
2190
|
lines.push("Other issues to tighten:");
|
|
2105
|
-
for (const f of otherIssues
|
|
2191
|
+
for (const f of otherIssues) {
|
|
2106
2192
|
lines.push(` - ${f.title}`);
|
|
2107
2193
|
if (f.basis) lines.push(` ${f.basis}`);
|
|
2108
2194
|
}
|
|
2109
|
-
if (otherIssues.length > 6) {
|
|
2110
|
-
lines.push(` ... and ${otherIssues.length - 6} more`);
|
|
2111
|
-
}
|
|
2112
2195
|
}
|
|
2113
2196
|
if (meta.skipped.length > 0) {
|
|
2114
2197
|
lines.push("");
|
|
@@ -2429,8 +2512,20 @@ async function runAudit(opts) {
|
|
|
2429
2512
|
});
|
|
2430
2513
|
const setup = await readSetup();
|
|
2431
2514
|
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
|
|
2515
|
+
let snapshotNotice = null;
|
|
2516
|
+
try {
|
|
2517
|
+
const historyDir = join3(opts.home ?? homedir3(), ".costclaw", "history");
|
|
2518
|
+
await mkdir(historyDir, { recursive: true });
|
|
2519
|
+
const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
|
|
2520
|
+
await writeFile(join3(historyDir, name), JSON.stringify(record, null, 2), "utf8");
|
|
2521
|
+
snapshotNotice = "Snapshot saved for costclaw diff.";
|
|
2522
|
+
} catch (err) {
|
|
2523
|
+
process.stderr.write(`Could not save the audit snapshot: ${err instanceof Error ? err.message : String(err)}
|
|
2524
|
+
`);
|
|
2525
|
+
}
|
|
2432
2526
|
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
2433
2527
|
const notices = [];
|
|
2528
|
+
if (snapshotNotice) notices.push(snapshotNotice);
|
|
2434
2529
|
if (opts.html) {
|
|
2435
2530
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
2436
2531
|
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
|
|
@@ -2453,7 +2548,7 @@ async function runAudit(opts) {
|
|
|
2453
2548
|
}
|
|
2454
2549
|
|
|
2455
2550
|
// src/optimize-command.ts
|
|
2456
|
-
import { mkdir, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
|
|
2551
|
+
import { mkdir as mkdir2, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
|
|
2457
2552
|
import { join as join5, dirname } from "path";
|
|
2458
2553
|
|
|
2459
2554
|
// src/project-scan.ts
|
|
@@ -3058,7 +3153,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
3058
3153
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
3059
3154
|
const merged = { ...existing, permissions: mergedPerms };
|
|
3060
3155
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
3061
|
-
await
|
|
3156
|
+
await mkdir2(dirname(target), { recursive: true });
|
|
3062
3157
|
await writeFile2(backup, existingText, "utf8");
|
|
3063
3158
|
await writeFile2(target, mergedText, "utf8");
|
|
3064
3159
|
return [
|
|
@@ -3081,7 +3176,7 @@ async function runOptimize(opts) {
|
|
|
3081
3176
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
3082
3177
|
const recoverable = cacheMissExposureUsd(report);
|
|
3083
3178
|
const outDir = opts.out || join5(process.cwd(), "costclaw-out");
|
|
3084
|
-
await
|
|
3179
|
+
await mkdir2(outDir, { recursive: true });
|
|
3085
3180
|
const playbookPath = join5(outDir, PLAYBOOK_NAME);
|
|
3086
3181
|
await writeFile2(playbookPath, result.playbook, "utf8");
|
|
3087
3182
|
const settingsPath = join5(outDir, SETTINGS_NAME);
|
|
@@ -3177,10 +3272,130 @@ async function runBadge(opts) {
|
|
|
3177
3272
|
return { output: `Badge written to ${target}`, record, target };
|
|
3178
3273
|
}
|
|
3179
3274
|
|
|
3180
|
-
// src/
|
|
3181
|
-
import {
|
|
3275
|
+
// src/diff-command.ts
|
|
3276
|
+
import { readdir as readdir3, readFile as readFile5 } from "fs/promises";
|
|
3182
3277
|
import { join as join6 } from "path";
|
|
3183
|
-
import { homedir as homedir4
|
|
3278
|
+
import { homedir as homedir4 } from "os";
|
|
3279
|
+
|
|
3280
|
+
// src/format-diff.ts
|
|
3281
|
+
function usd6(n) {
|
|
3282
|
+
return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
|
|
3283
|
+
}
|
|
3284
|
+
function signedUsd(n) {
|
|
3285
|
+
return `${n < 0 ? "-" : "+"}${usd6(n)}`;
|
|
3286
|
+
}
|
|
3287
|
+
function signedInt(n) {
|
|
3288
|
+
return n > 0 ? `+${n}` : `${n}`;
|
|
3289
|
+
}
|
|
3290
|
+
function pct(rate) {
|
|
3291
|
+
return `${(rate * 100).toFixed(1)}%`;
|
|
3292
|
+
}
|
|
3293
|
+
function day(iso) {
|
|
3294
|
+
return iso.slice(0, 10);
|
|
3295
|
+
}
|
|
3296
|
+
function formatDiff(d) {
|
|
3297
|
+
const lines = [];
|
|
3298
|
+
lines.push("CostClaw diff");
|
|
3299
|
+
lines.push(
|
|
3300
|
+
`Baseline: ${day(d.baseline.createdAt)} Current: ${day(d.current.createdAt)} (${d.periodDays} days)`
|
|
3301
|
+
);
|
|
3302
|
+
lines.push("");
|
|
3303
|
+
if (d.comparable && d.marginal) {
|
|
3304
|
+
lines.push("Since the baseline:");
|
|
3305
|
+
lines.push(
|
|
3306
|
+
` New spend ${usd6(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
|
|
3307
|
+
);
|
|
3308
|
+
lines.push(
|
|
3309
|
+
` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
|
|
3310
|
+
);
|
|
3311
|
+
lines.push(
|
|
3312
|
+
` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd6(d.current.recoverableUsd)})`
|
|
3313
|
+
);
|
|
3314
|
+
} else {
|
|
3315
|
+
lines.push("Note: the current audit covers less history than the baseline (logs moved or");
|
|
3316
|
+
lines.push("pruned), so period metrics are omitted.");
|
|
3317
|
+
lines.push("");
|
|
3318
|
+
lines.push(
|
|
3319
|
+
`Baseline (${day(d.baseline.createdAt)}): spend ${usd6(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd6(d.baseline.recoverableUsd)}`
|
|
3320
|
+
);
|
|
3321
|
+
lines.push(
|
|
3322
|
+
`Current (${day(d.current.createdAt)}): spend ${usd6(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd6(d.current.recoverableUsd)}`
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
lines.push("");
|
|
3326
|
+
lines.push(
|
|
3327
|
+
`Overall setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band})`
|
|
3328
|
+
);
|
|
3329
|
+
for (const p of d.pillars) {
|
|
3330
|
+
const before = p.before === null ? "n/a" : String(p.before);
|
|
3331
|
+
const after = p.after === null ? "n/a" : String(p.after);
|
|
3332
|
+
const delta = p.delta === null ? "" : ` (${signedInt(p.delta)})`;
|
|
3333
|
+
lines.push(` ${p.name.padEnd(22)} ${before.padStart(3)} -> ${after.padStart(3)}${delta}`);
|
|
3334
|
+
}
|
|
3335
|
+
const { resolved, appeared, changed } = d.fixes;
|
|
3336
|
+
if (resolved.length > 0) {
|
|
3337
|
+
lines.push("");
|
|
3338
|
+
lines.push("Fixes resolved since the baseline:");
|
|
3339
|
+
for (const f of resolved) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
|
|
3340
|
+
}
|
|
3341
|
+
if (appeared.length > 0) {
|
|
3342
|
+
lines.push("");
|
|
3343
|
+
lines.push("New since the baseline:");
|
|
3344
|
+
for (const f of appeared) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
|
|
3345
|
+
}
|
|
3346
|
+
if (changed.length > 0) {
|
|
3347
|
+
lines.push("");
|
|
3348
|
+
lines.push("Fixes that moved:");
|
|
3349
|
+
for (const c of changed) {
|
|
3350
|
+
lines.push(` - ${c.title}: ${usd6(c.beforeUsd)} -> ${usd6(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
return lines.join("\n");
|
|
3354
|
+
}
|
|
3355
|
+
|
|
3356
|
+
// src/diff-command.ts
|
|
3357
|
+
async function readRecord(path) {
|
|
3358
|
+
let text2;
|
|
3359
|
+
try {
|
|
3360
|
+
text2 = await readFile5(path, "utf8");
|
|
3361
|
+
} catch {
|
|
3362
|
+
throw new Error(`Could not read ${path}.`);
|
|
3363
|
+
}
|
|
3364
|
+
try {
|
|
3365
|
+
return JSON.parse(text2);
|
|
3366
|
+
} catch {
|
|
3367
|
+
throw new Error(
|
|
3368
|
+
`${path} is not valid JSON. Pass a record from costclaw audit --json or ~/.costclaw/history.`
|
|
3369
|
+
);
|
|
3370
|
+
}
|
|
3371
|
+
}
|
|
3372
|
+
async function runDiff(opts) {
|
|
3373
|
+
let pathA = opts.fileA;
|
|
3374
|
+
let pathB = opts.fileB;
|
|
3375
|
+
if (!pathA || !pathB) {
|
|
3376
|
+
const dir = join6(opts.home ?? homedir4(), ".costclaw", "history");
|
|
3377
|
+
let files = [];
|
|
3378
|
+
try {
|
|
3379
|
+
files = (await readdir3(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
3380
|
+
} catch {
|
|
3381
|
+
}
|
|
3382
|
+
if (files.length < 2) {
|
|
3383
|
+
throw new Error(
|
|
3384
|
+
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
3385
|
+
);
|
|
3386
|
+
}
|
|
3387
|
+
pathA = join6(dir, files[files.length - 2]);
|
|
3388
|
+
pathB = join6(dir, files[files.length - 1]);
|
|
3389
|
+
}
|
|
3390
|
+
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
3391
|
+
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
3392
|
+
return { output, diff };
|
|
3393
|
+
}
|
|
3394
|
+
|
|
3395
|
+
// src/license.ts
|
|
3396
|
+
import { mkdir as mkdir3, readFile as readFile6, writeFile as writeFile4, rm } from "fs/promises";
|
|
3397
|
+
import { join as join7 } from "path";
|
|
3398
|
+
import { homedir as homedir5, hostname } from "os";
|
|
3184
3399
|
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
3185
3400
|
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
3186
3401
|
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
@@ -3205,10 +3420,10 @@ var INVALID_MESSAGE = [
|
|
|
3205
3420
|
"costclaw audit stays free."
|
|
3206
3421
|
].join("\n");
|
|
3207
3422
|
function defaultConfigDir() {
|
|
3208
|
-
return
|
|
3423
|
+
return join7(homedir5(), ".costclaw");
|
|
3209
3424
|
}
|
|
3210
3425
|
function licenseFile(dir) {
|
|
3211
|
-
return
|
|
3426
|
+
return join7(dir, "license.json");
|
|
3212
3427
|
}
|
|
3213
3428
|
function base64UrlDecode(part) {
|
|
3214
3429
|
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
@@ -3232,7 +3447,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
|
3232
3447
|
}
|
|
3233
3448
|
async function readStoredLicense(dir) {
|
|
3234
3449
|
try {
|
|
3235
|
-
const data = JSON.parse(await
|
|
3450
|
+
const data = JSON.parse(await readFile6(licenseFile(dir), "utf8"));
|
|
3236
3451
|
if (!data || typeof data.licenseKey !== "string") return null;
|
|
3237
3452
|
return data;
|
|
3238
3453
|
} catch {
|
|
@@ -3240,7 +3455,7 @@ async function readStoredLicense(dir) {
|
|
|
3240
3455
|
}
|
|
3241
3456
|
}
|
|
3242
3457
|
async function writeStoredLicense(dir, lic) {
|
|
3243
|
-
await
|
|
3458
|
+
await mkdir3(dir, { recursive: true });
|
|
3244
3459
|
await writeFile4(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
3245
3460
|
}
|
|
3246
3461
|
async function clearStoredLicense(dir) {
|
|
@@ -3320,7 +3535,7 @@ function parseBadgeFlags(args) {
|
|
|
3320
3535
|
};
|
|
3321
3536
|
}
|
|
3322
3537
|
function cliVersion() {
|
|
3323
|
-
return true ? "0.2.
|
|
3538
|
+
return true ? "0.2.4" : "0.0.0-dev";
|
|
3324
3539
|
}
|
|
3325
3540
|
function helpText() {
|
|
3326
3541
|
return [
|
|
@@ -3328,6 +3543,7 @@ function helpText() {
|
|
|
3328
3543
|
"",
|
|
3329
3544
|
"Usage:",
|
|
3330
3545
|
" costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
|
|
3546
|
+
" costclaw diff [<baseline.json> <current.json>] [--json]",
|
|
3331
3547
|
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
3332
3548
|
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
3333
3549
|
" costclaw activate <license-key> [--name <machine-name>]",
|
|
@@ -3341,6 +3557,12 @@ function helpText() {
|
|
|
3341
3557
|
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
3342
3558
|
"score, band, recoverable spend, cache hit rate, and your strongest pillar.",
|
|
3343
3559
|
"",
|
|
3560
|
+
"diff compares two audits and shows the movement: new spend since the baseline,",
|
|
3561
|
+
"the marginal cache hit rate for just that period, score changes per pillar, and",
|
|
3562
|
+
"which fixes were resolved. Every audit run saves a snapshot to",
|
|
3563
|
+
"~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",
|
|
3564
|
+
"or pass two record files from costclaw audit --json. It is free.",
|
|
3565
|
+
"",
|
|
3344
3566
|
"badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
|
|
3345
3567
|
"costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
|
|
3346
3568
|
"in a README with an <img> tag; it is a static, self-contained file.",
|
|
@@ -3374,6 +3596,16 @@ async function main() {
|
|
|
3374
3596
|
process.stdout.write(output + "\n");
|
|
3375
3597
|
return;
|
|
3376
3598
|
}
|
|
3599
|
+
if (command === "diff") {
|
|
3600
|
+
const files = args.filter((a) => !a.startsWith("-"));
|
|
3601
|
+
const { output } = await runDiff({
|
|
3602
|
+
fileA: files[0],
|
|
3603
|
+
fileB: files[1],
|
|
3604
|
+
json: args.includes("--json")
|
|
3605
|
+
});
|
|
3606
|
+
process.stdout.write(output + "\n");
|
|
3607
|
+
return;
|
|
3608
|
+
}
|
|
3377
3609
|
if (command === "badge") {
|
|
3378
3610
|
const { output } = await runBadge(parseBadgeFlags(args));
|
|
3379
3611
|
process.stdout.write(output + "\n");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
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": {
|