costclaw 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -54
- package/dist/index.js +673 -171
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { pathToFileURL } from "url";
|
|
5
|
+
|
|
3
6
|
// src/audit-command.ts
|
|
4
|
-
import { readFile as
|
|
7
|
+
import { readFile as readFile2, writeFile } from "fs/promises";
|
|
8
|
+
import { resolve } from "path";
|
|
9
|
+
import { spawn } from "child_process";
|
|
5
10
|
|
|
6
11
|
// ../../packages/engine/src/types.ts
|
|
7
12
|
function emptyTotals() {
|
|
@@ -60,8 +65,8 @@ function isOpus(model) {
|
|
|
60
65
|
|
|
61
66
|
// ../../packages/engine/src/sanitize.ts
|
|
62
67
|
var EM_OR_EN = /[—–]/;
|
|
63
|
-
function hasEmDash(
|
|
64
|
-
return EM_OR_EN.test(
|
|
68
|
+
function hasEmDash(text2) {
|
|
69
|
+
return EM_OR_EN.test(text2);
|
|
65
70
|
}
|
|
66
71
|
function sanitizeText(input) {
|
|
67
72
|
let out = input;
|
|
@@ -127,7 +132,7 @@ function extractTools(content) {
|
|
|
127
132
|
}
|
|
128
133
|
return { names, events };
|
|
129
134
|
}
|
|
130
|
-
function parseSession(
|
|
135
|
+
function parseSession(text2, opts = {}) {
|
|
131
136
|
const s = {
|
|
132
137
|
sessionUuid: null,
|
|
133
138
|
projectSlug: null,
|
|
@@ -155,7 +160,7 @@ function parseSession(text, opts = {}) {
|
|
|
155
160
|
const modelCounts = /* @__PURE__ */ new Map();
|
|
156
161
|
let cwd = null;
|
|
157
162
|
let seq = 0;
|
|
158
|
-
for (const line of
|
|
163
|
+
for (const line of text2.split("\n")) {
|
|
159
164
|
if (!line.trim()) continue;
|
|
160
165
|
const rec = safeParse(line);
|
|
161
166
|
if (!rec) {
|
|
@@ -325,6 +330,7 @@ var MISROUTE_MIN_EXPOSURE = 0.5;
|
|
|
325
330
|
var MISROUTE_BASELINE = "claude-sonnet-4-6";
|
|
326
331
|
var WORKFLOW_MIN_COST = 5;
|
|
327
332
|
var WORKFLOW_WARN_SHARE = 0.5;
|
|
333
|
+
var REDUNDANT_TARGET_MIN_FIRES = 10;
|
|
328
334
|
function thirdHit(turns, lo, hi) {
|
|
329
335
|
let read = 0;
|
|
330
336
|
let total = 0;
|
|
@@ -390,22 +396,82 @@ function ruleHotProject(ctx) {
|
|
|
390
396
|
function ruleHeavyToolLoops(ctx) {
|
|
391
397
|
const out = [];
|
|
392
398
|
for (const proj of ctx.projects) {
|
|
399
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
393
400
|
for (const s of proj.sessions) {
|
|
394
401
|
if (s.kind !== "main") continue;
|
|
395
402
|
for (const [tool, fires] of Object.entries(s.toolUsage)) {
|
|
396
403
|
if (fires < HEAVY_TOOL_FIRES) continue;
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
description: `${tool} fired ${fires} times in a single session, a sign of a stuck loop or unscoped search.`,
|
|
403
|
-
suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
|
|
404
|
-
estimatedMonthlySavingsUsd: 0,
|
|
405
|
-
evidence: { tool, fires, sessionUuid: s.sessionUuid }
|
|
406
|
-
});
|
|
404
|
+
const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
|
|
405
|
+
entry.sessionsAffected += 1;
|
|
406
|
+
entry.maxFires = Math.max(entry.maxFires, fires);
|
|
407
|
+
if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
|
|
408
|
+
byTool.set(tool, entry);
|
|
407
409
|
}
|
|
408
410
|
}
|
|
411
|
+
for (const [tool, e] of byTool) {
|
|
412
|
+
const n = e.sessionsAffected;
|
|
413
|
+
out.push({
|
|
414
|
+
ruleId: "HEAVY_TOOL_LOOPS",
|
|
415
|
+
severity: "warn",
|
|
416
|
+
project: proj.slug,
|
|
417
|
+
title: `Heavy ${tool} usage in ${n} session${n === 1 ? "" : "s"}`,
|
|
418
|
+
description: `${tool} fired up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of a stuck loop or unscoped search.`,
|
|
419
|
+
suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
|
|
420
|
+
estimatedMonthlySavingsUsd: 0,
|
|
421
|
+
evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
}
|
|
427
|
+
function targetNounFor(tool) {
|
|
428
|
+
if (["Bash", "PowerShell"].includes(tool)) return "command";
|
|
429
|
+
if (["WebFetch", "WebSearch"].includes(tool)) return "query";
|
|
430
|
+
if (tool === "Agent" || tool.startsWith("Task")) return "subagent";
|
|
431
|
+
return "file";
|
|
432
|
+
}
|
|
433
|
+
function ruleRedundantTargetThrash(ctx) {
|
|
434
|
+
const out = [];
|
|
435
|
+
for (const proj of ctx.projects) {
|
|
436
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
437
|
+
for (const s of proj.sessions) {
|
|
438
|
+
if (s.kind !== "main") continue;
|
|
439
|
+
const counts = /* @__PURE__ */ new Map();
|
|
440
|
+
for (const e of s.toolEvents) {
|
|
441
|
+
if (e.target == null) continue;
|
|
442
|
+
const byTarget = counts.get(e.name) ?? /* @__PURE__ */ new Map();
|
|
443
|
+
byTarget.set(e.target, (byTarget.get(e.target) ?? 0) + 1);
|
|
444
|
+
counts.set(e.name, byTarget);
|
|
445
|
+
}
|
|
446
|
+
const perToolMax = /* @__PURE__ */ new Map();
|
|
447
|
+
for (const [tool, byTarget] of counts) {
|
|
448
|
+
for (const n of byTarget.values()) {
|
|
449
|
+
if (n < REDUNDANT_TARGET_MIN_FIRES) continue;
|
|
450
|
+
perToolMax.set(tool, Math.max(perToolMax.get(tool) ?? 0, n));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
for (const [tool, n] of perToolMax) {
|
|
454
|
+
const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
|
|
455
|
+
entry.sessionsAffected += 1;
|
|
456
|
+
entry.maxFires = Math.max(entry.maxFires, n);
|
|
457
|
+
if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
|
|
458
|
+
byTool.set(tool, entry);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
for (const [tool, e] of byTool) {
|
|
462
|
+
const n = e.sessionsAffected;
|
|
463
|
+
const noun = targetNounFor(tool);
|
|
464
|
+
out.push({
|
|
465
|
+
ruleId: "REDUNDANT_TARGET_THRASH",
|
|
466
|
+
severity: "warn",
|
|
467
|
+
project: proj.slug,
|
|
468
|
+
title: `Repeated ${tool} calls on the same ${noun} in ${n} session${n === 1 ? "" : "s"}`,
|
|
469
|
+
description: `${tool} hit the same ${noun} up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of redundant repeated calls instead of new progress.`,
|
|
470
|
+
suggestedAction: `Cache or reuse the result instead of calling ${tool} again on the same ${noun}.`,
|
|
471
|
+
estimatedMonthlySavingsUsd: 0,
|
|
472
|
+
evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
|
|
473
|
+
});
|
|
474
|
+
}
|
|
409
475
|
}
|
|
410
476
|
return out;
|
|
411
477
|
}
|
|
@@ -526,6 +592,7 @@ var RULES = [
|
|
|
526
592
|
{ id: "BAD_CACHE_HIT", run: ruleBadCacheHit },
|
|
527
593
|
{ id: "HOT_PROJECT", run: ruleHotProject },
|
|
528
594
|
{ id: "HEAVY_TOOL_LOOPS", run: ruleHeavyToolLoops },
|
|
595
|
+
{ id: "REDUNDANT_TARGET_THRASH", run: ruleRedundantTargetThrash },
|
|
529
596
|
{ id: "SHORT_SESSION_BLOAT", run: ruleShortSessionBloat },
|
|
530
597
|
{ id: "MARATHON_SESSION", run: ruleMarathonSession },
|
|
531
598
|
{ id: "MODEL_MISROUTE", run: ruleModelMisroute },
|
|
@@ -610,8 +677,8 @@ function scoreStability(chars, volatileMarkers) {
|
|
|
610
677
|
const per1k = volatileMarkers / chars * 1e3;
|
|
611
678
|
return clamp(100 - per1k * 28);
|
|
612
679
|
}
|
|
613
|
-
function analyzeClaudeMd(
|
|
614
|
-
const raw = (
|
|
680
|
+
function analyzeClaudeMd(text2) {
|
|
681
|
+
const raw = (text2 ?? "").trim();
|
|
615
682
|
if (!raw) {
|
|
616
683
|
return {
|
|
617
684
|
present: false,
|
|
@@ -926,9 +993,12 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
926
993
|
checks.push(questionnaireCheck("clear_between", "Clearing between tasks", answers));
|
|
927
994
|
checks.push(questionnaireCheck("plan_first", "Planning first", answers));
|
|
928
995
|
checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
|
|
929
|
-
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
|
|
996
|
+
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS" || f.ruleId === "REDUNDANT_TARGET_THRASH");
|
|
930
997
|
const thrashSessions = new Set(
|
|
931
|
-
heavyLoops.
|
|
998
|
+
heavyLoops.flatMap((f) => {
|
|
999
|
+
const uuids = f.evidence?.["sessionUuids"];
|
|
1000
|
+
return Array.isArray(uuids) ? uuids.filter((v) => typeof v === "string") : [];
|
|
1001
|
+
})
|
|
932
1002
|
).size;
|
|
933
1003
|
const thrashShare = s.sessionsCount > 0 ? thrashSessions / s.sessionsCount : 0;
|
|
934
1004
|
const thrashPct = Math.round(thrashShare * 100);
|
|
@@ -938,7 +1008,7 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
938
1008
|
"prompting",
|
|
939
1009
|
"Tool looping",
|
|
940
1010
|
s.sessionsCount > 0 ? clamp2(100 - thrashShare * 180) : null,
|
|
941
|
-
s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No
|
|
1011
|
+
s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No sign of a stuck tool loop." : `${thrashSessions} of ${s.sessionsCount} sessions (${thrashPct}%) showed heavy tool repetition: one tool firing 100 or more times, or the same file, command, or target hit 10 or more times.`,
|
|
942
1012
|
"metrics"
|
|
943
1013
|
)
|
|
944
1014
|
);
|
|
@@ -1149,7 +1219,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1149
1219
|
const fixes = [];
|
|
1150
1220
|
const covered = /* @__PURE__ */ new Set();
|
|
1151
1221
|
const round22 = (n) => Math.round(n * 100) / 100;
|
|
1152
|
-
const
|
|
1222
|
+
const usd6 = (n) => {
|
|
1153
1223
|
const fixed = round22(n).toFixed(2);
|
|
1154
1224
|
const dot = fixed.indexOf(".");
|
|
1155
1225
|
const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
@@ -1177,7 +1247,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1177
1247
|
severity: sevForUsd(exposure),
|
|
1178
1248
|
wasteUsd: round22(exposure),
|
|
1179
1249
|
problem: sanitizeText(
|
|
1180
|
-
`Up to ${
|
|
1250
|
+
`Up to ${usd6(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
1181
1251
|
),
|
|
1182
1252
|
action: sanitizeText(
|
|
1183
1253
|
"Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
|
|
@@ -1198,9 +1268,8 @@ function synthesize(report, pillars, cmd) {
|
|
|
1198
1268
|
for (const f of report.findings) {
|
|
1199
1269
|
if (f.ruleId === "HEAVY_TOOL_LOOPS" && f.evidence) {
|
|
1200
1270
|
const tool = String(f.evidence["tool"] ?? "a tool");
|
|
1201
|
-
const entry = heavyByTool.get(tool) ?? {
|
|
1202
|
-
|
|
1203
|
-
if (typeof sid === "string") entry.sessions.add(sid);
|
|
1271
|
+
const entry = heavyByTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0 };
|
|
1272
|
+
entry.sessionsAffected += Number(f.evidence["sessionsAffected"]) || 0;
|
|
1204
1273
|
entry.maxFires = Math.max(entry.maxFires, Number(f.evidence["fires"]) || 0);
|
|
1205
1274
|
heavyByTool.set(tool, entry);
|
|
1206
1275
|
covered.add("tool_thrash");
|
|
@@ -1224,7 +1293,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1224
1293
|
}
|
|
1225
1294
|
}
|
|
1226
1295
|
for (const [tool, e] of heavyByTool) {
|
|
1227
|
-
const n = Math.max(e.
|
|
1296
|
+
const n = Math.max(e.sessionsAffected, 1);
|
|
1228
1297
|
fixes.push({
|
|
1229
1298
|
id: `heavy_tool_${tool}`,
|
|
1230
1299
|
title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
|
|
@@ -1259,7 +1328,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1259
1328
|
pillarName: PILLARS.cost_discipline.name,
|
|
1260
1329
|
severity: sevForUsd(misrouteUsd),
|
|
1261
1330
|
wasteUsd: round22(misrouteUsd),
|
|
1262
|
-
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${
|
|
1331
|
+
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd6(misrouteUsd)} more than a cheaper model would have.`),
|
|
1263
1332
|
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
|
|
1264
1333
|
basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1265
1334
|
});
|
|
@@ -1273,7 +1342,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1273
1342
|
pillarName: PILLARS.session_mgmt.name,
|
|
1274
1343
|
severity: sevForUsd(marathonUsd),
|
|
1275
1344
|
wasteUsd: round22(marathonUsd),
|
|
1276
|
-
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${
|
|
1345
|
+
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd6(marathonUsd)} for context in the later turns.`),
|
|
1277
1346
|
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1278
1347
|
basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
|
|
1279
1348
|
});
|
|
@@ -1286,7 +1355,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
1286
1355
|
pillarName: PILLARS.cost_discipline.name,
|
|
1287
1356
|
severity: "info",
|
|
1288
1357
|
wasteUsd: 0,
|
|
1289
|
-
problem: sanitizeText(`Workflow and subagent runs cost about ${
|
|
1358
|
+
problem: sanitizeText(`Workflow and subagent runs cost about ${usd6(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
|
|
1290
1359
|
action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
|
|
1291
1360
|
basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
|
|
1292
1361
|
});
|
|
@@ -1333,8 +1402,8 @@ function usd(n) {
|
|
|
1333
1402
|
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1334
1403
|
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
1335
1404
|
}
|
|
1336
|
-
function clean(
|
|
1337
|
-
return sanitizeText(
|
|
1405
|
+
function clean(text2) {
|
|
1406
|
+
return sanitizeText(text2);
|
|
1338
1407
|
}
|
|
1339
1408
|
function weakCostDiscipline(scores) {
|
|
1340
1409
|
const p = scores.find((s) => s.id === "cost_discipline");
|
|
@@ -1808,7 +1877,7 @@ function toUsageMetrics(report) {
|
|
|
1808
1877
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
1809
1878
|
}));
|
|
1810
1879
|
const modelBreakdown = {};
|
|
1811
|
-
for (const [model,
|
|
1880
|
+
for (const [model, usd6] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd6);
|
|
1812
1881
|
return {
|
|
1813
1882
|
spendUsd: round2(s.cost_usd),
|
|
1814
1883
|
cacheSavingsUsd: round2(s.cache_savings_usd),
|
|
@@ -1846,6 +1915,7 @@ function buildAudit(input, opts = {}) {
|
|
|
1846
1915
|
const { headlineWasteUsd, headlineWasteLabel, fixes } = synthesize(report, pillars, cmd);
|
|
1847
1916
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
1848
1917
|
return {
|
|
1918
|
+
schemaVersion: "1",
|
|
1849
1919
|
id: randomUUID(),
|
|
1850
1920
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1851
1921
|
contactEmail: input.contactEmail?.trim() || null,
|
|
@@ -1873,7 +1943,8 @@ var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
|
1873
1943
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
1874
1944
|
|
|
1875
1945
|
// src/read-sessions.ts
|
|
1876
|
-
import { readdir
|
|
1946
|
+
import { readdir } from "fs/promises";
|
|
1947
|
+
import { readFileSync, openSync, closeSync } from "fs";
|
|
1877
1948
|
import { join, relative, sep } from "path";
|
|
1878
1949
|
import { homedir } from "os";
|
|
1879
1950
|
function defaultProjectsPath() {
|
|
@@ -1901,6 +1972,21 @@ function classify(rel) {
|
|
|
1901
1972
|
if (parts.includes("workflows")) return { kind: "workflow", parentSessionId: parent };
|
|
1902
1973
|
return { kind: "subagent", parentSessionId: parent };
|
|
1903
1974
|
}
|
|
1975
|
+
function lazyLog(full, meta) {
|
|
1976
|
+
return {
|
|
1977
|
+
name: meta.name,
|
|
1978
|
+
kind: meta.kind,
|
|
1979
|
+
parentSessionId: meta.parentSessionId,
|
|
1980
|
+
projectSlug: meta.projectSlug,
|
|
1981
|
+
get text() {
|
|
1982
|
+
try {
|
|
1983
|
+
return readFileSync(full, "utf8");
|
|
1984
|
+
} catch {
|
|
1985
|
+
return "";
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1904
1990
|
async function readSessions(rootPath) {
|
|
1905
1991
|
const logs = [];
|
|
1906
1992
|
const skipped = [];
|
|
@@ -1925,8 +2011,8 @@ async function readSessions(rootPath) {
|
|
|
1925
2011
|
const name = `${dir.name}/${rel}`;
|
|
1926
2012
|
const { kind, parentSessionId } = classify(rel);
|
|
1927
2013
|
try {
|
|
1928
|
-
|
|
1929
|
-
logs.push({ name,
|
|
2014
|
+
closeSync(openSync(full, "r"));
|
|
2015
|
+
logs.push(lazyLog(full, { name, kind, parentSessionId, projectSlug: dir.name }));
|
|
1930
2016
|
} catch {
|
|
1931
2017
|
skipped.push(name);
|
|
1932
2018
|
}
|
|
@@ -1944,6 +2030,15 @@ function bar(score, width = 20) {
|
|
|
1944
2030
|
const filled = Math.round(score / 100 * width);
|
|
1945
2031
|
return `[${"#".repeat(filled)}${".".repeat(width - filled)}] ${score}`;
|
|
1946
2032
|
}
|
|
2033
|
+
function unassessedLine(pillars) {
|
|
2034
|
+
const gaps = pillars.filter((p) => !p.assessed);
|
|
2035
|
+
if (gaps.length === 0) return null;
|
|
2036
|
+
const parts = gaps.map((p) => {
|
|
2037
|
+
const reason = p.checks[0]?.basis;
|
|
2038
|
+
return reason ? `${p.name} (${reason})` : p.name;
|
|
2039
|
+
});
|
|
2040
|
+
return `Not yet scored: ${parts.join(" ")}`;
|
|
2041
|
+
}
|
|
1947
2042
|
function formatAudit(record, meta) {
|
|
1948
2043
|
const m = record.usageMetrics;
|
|
1949
2044
|
const lines = [];
|
|
@@ -1985,18 +2080,235 @@ function formatAudit(record, meta) {
|
|
|
1985
2080
|
lines.push("");
|
|
1986
2081
|
lines.push(`Note: ${meta.skipped.length} file(s) could not be read and were skipped.`);
|
|
1987
2082
|
}
|
|
1988
|
-
|
|
1989
|
-
|
|
2083
|
+
const gapLine = unassessedLine(record.pillarScores);
|
|
2084
|
+
if (gapLine) {
|
|
2085
|
+
lines.push("");
|
|
2086
|
+
lines.push(gapLine);
|
|
2087
|
+
}
|
|
1990
2088
|
return lines.join("\n");
|
|
1991
2089
|
}
|
|
1992
2090
|
|
|
2091
|
+
// src/svg.ts
|
|
2092
|
+
var SYSTEM_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
|
2093
|
+
function esc(s) {
|
|
2094
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2095
|
+
}
|
|
2096
|
+
function bandColorForScore(score) {
|
|
2097
|
+
if (score < 40) return "#c0392b";
|
|
2098
|
+
if (score < 60) return "#e07a5f";
|
|
2099
|
+
if (score < 75) return "#d99a2b";
|
|
2100
|
+
if (score < 90) return "#5f8f4f";
|
|
2101
|
+
return "#3f7d4e";
|
|
2102
|
+
}
|
|
2103
|
+
function rect(x, y, w, h, fill, rx = 0) {
|
|
2104
|
+
return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}" fill="${fill}"></rect>`;
|
|
2105
|
+
}
|
|
2106
|
+
function text(x, y, s, opts = {}) {
|
|
2107
|
+
const size = opts.size ?? 13;
|
|
2108
|
+
const weight = opts.weight ?? 400;
|
|
2109
|
+
const fill = opts.fill ?? "#251d1a";
|
|
2110
|
+
const anchor = opts.anchor ?? "start";
|
|
2111
|
+
return `<text x="${x}" y="${y}" font-family="${SYSTEM_FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${esc(s)}</text>`;
|
|
2112
|
+
}
|
|
2113
|
+
function estimateTextWidth(s, size) {
|
|
2114
|
+
return Math.round(s.length * size * 0.62);
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// src/html-report.ts
|
|
2118
|
+
function usd3(n) {
|
|
2119
|
+
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2120
|
+
}
|
|
2121
|
+
function truncate(s, max) {
|
|
2122
|
+
return s.length > max ? s.slice(0, max - 3) + "..." : s;
|
|
2123
|
+
}
|
|
2124
|
+
function projectChart(projects) {
|
|
2125
|
+
if (projects.length === 0) {
|
|
2126
|
+
return `<p class="muted">No project spend to chart.</p>`;
|
|
2127
|
+
}
|
|
2128
|
+
const rowH = 30;
|
|
2129
|
+
const gap = 10;
|
|
2130
|
+
const labelW = 220;
|
|
2131
|
+
const barMax = 340;
|
|
2132
|
+
const valW = 96;
|
|
2133
|
+
const width = labelW + barMax + valW;
|
|
2134
|
+
const height = projects.length * (rowH + gap) - gap;
|
|
2135
|
+
const maxCost = Math.max(...projects.map((p) => p.costUsd), 0.01);
|
|
2136
|
+
const rows = projects.map((p, i) => {
|
|
2137
|
+
const y = i * (rowH + gap);
|
|
2138
|
+
const w = Math.max(3, Math.round(p.costUsd / maxCost * barMax));
|
|
2139
|
+
const mid = y + rowH / 2;
|
|
2140
|
+
const label = esc(truncate(p.slug, 32));
|
|
2141
|
+
return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${y + 3}" width="${w}" height="${rowH - 6}" rx="4" fill="#e07a5f"></rect><text x="${labelW + w + 8}" y="${mid}" class="c-val" dominant-baseline="middle">${esc(usd3(p.costUsd))}</text>`;
|
|
2142
|
+
}).join("");
|
|
2143
|
+
return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
|
|
2144
|
+
}
|
|
2145
|
+
function pillarBars(pillars) {
|
|
2146
|
+
return pillars.map((p) => {
|
|
2147
|
+
const name = esc(p.name);
|
|
2148
|
+
if (!p.assessed || p.score === null) {
|
|
2149
|
+
return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill p-na" style="width:100%"></span></span><span class="p-score muted">n/a</span></div>`;
|
|
2150
|
+
}
|
|
2151
|
+
const score = p.score;
|
|
2152
|
+
const color = bandColorForScore(score);
|
|
2153
|
+
return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill" style="width:${score}%;background:${color}"></span></span><span class="p-score">${score}</span></div>`;
|
|
2154
|
+
}).join("");
|
|
2155
|
+
}
|
|
2156
|
+
function dollarFixCard(f) {
|
|
2157
|
+
return `<li class="fix"><div class="fix-head"><span class="fix-amt">${esc(usd3(f.wasteUsd))}</span><span class="fix-title">${esc(f.title)}</span></div><p class="fix-problem">${esc(f.problem)}</p><p class="fix-action">${esc(f.action)}</p></li>`;
|
|
2158
|
+
}
|
|
2159
|
+
function otherFixCard(f) {
|
|
2160
|
+
return `<li class="fix other"><div class="fix-head"><span class="fix-title">${esc(f.title)}</span></div><p class="fix-action">${esc(f.action)}</p></li>`;
|
|
2161
|
+
}
|
|
2162
|
+
var STYLE = `
|
|
2163
|
+
:root { color-scheme: light; }
|
|
2164
|
+
* { box-sizing: border-box; }
|
|
2165
|
+
body {
|
|
2166
|
+
margin: 0;
|
|
2167
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
2168
|
+
color: #251d1a;
|
|
2169
|
+
background: #fefaf7;
|
|
2170
|
+
line-height: 1.5;
|
|
2171
|
+
}
|
|
2172
|
+
.wrap { max-width: 860px; margin: 0 auto; padding: 40px 24px 64px; }
|
|
2173
|
+
h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; }
|
|
2174
|
+
h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
|
|
2175
|
+
.sub { color: #7a6a63; font-size: 14px; margin: 0 0 8px; }
|
|
2176
|
+
.banner {
|
|
2177
|
+
margin: 28px 0 8px; padding: 22px 26px; border-radius: 14px;
|
|
2178
|
+
background: linear-gradient(135deg, #822d1d, #e07a5f); color: #fefaf7;
|
|
2179
|
+
box-shadow: 0 8px 24px rgba(130, 45, 29, 0.18);
|
|
2180
|
+
}
|
|
2181
|
+
.banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
|
|
2182
|
+
.banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
|
|
2183
|
+
.stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
|
|
2184
|
+
.stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
|
|
2185
|
+
.stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
2186
|
+
.stat .v { font-size: 20px; font-weight: 600; margin-top: 2px; }
|
|
2187
|
+
.score-head { display: flex; align-items: baseline; gap: 12px; }
|
|
2188
|
+
.score-head .big { font-size: 30px; font-weight: 700; }
|
|
2189
|
+
.score-head .band { font-size: 15px; color: #822d1d; font-weight: 600; }
|
|
2190
|
+
.pillar { display: flex; align-items: center; gap: 12px; margin: 8px 0; }
|
|
2191
|
+
.p-name { flex: 0 0 190px; font-size: 14px; }
|
|
2192
|
+
.p-track { flex: 1; height: 14px; background: #f0e2da; border-radius: 7px; overflow: hidden; }
|
|
2193
|
+
.p-fill { display: block; height: 100%; border-radius: 7px; }
|
|
2194
|
+
.p-fill.p-na { background: repeating-linear-gradient(45deg, #ece0d8, #ece0d8 6px, #f5ece6 6px, #f5ece6 12px); }
|
|
2195
|
+
.p-score { flex: 0 0 40px; text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; font-size: 14px; }
|
|
2196
|
+
.muted { color: #9a8a82; font-weight: 500; }
|
|
2197
|
+
.chart { background: #fff; border: 1px solid #f0e2da; border-radius: 12px; padding: 18px; overflow-x: auto; }
|
|
2198
|
+
.c-lbl { font-size: 13px; fill: #251d1a; }
|
|
2199
|
+
.c-val { font-size: 13px; fill: #822d1d; font-weight: 600; }
|
|
2200
|
+
ul.fixes { list-style: none; margin: 0; padding: 0; }
|
|
2201
|
+
.fix { background: #fff; border: 1px solid #f0e2da; border-left: 4px solid #e07a5f; border-radius: 10px; padding: 14px 18px; margin: 10px 0; }
|
|
2202
|
+
.fix.other { border-left-color: #cbb8ae; }
|
|
2203
|
+
.fix-head { display: flex; align-items: baseline; gap: 12px; }
|
|
2204
|
+
.fix-amt { font-size: 18px; font-weight: 700; color: #822d1d; font-variant-numeric: tabular-nums; }
|
|
2205
|
+
.fix-title { font-size: 15px; font-weight: 600; }
|
|
2206
|
+
.fix-problem { margin: 8px 0 4px; color: #5a4a43; font-size: 14px; }
|
|
2207
|
+
.fix-action { margin: 4px 0 0; font-size: 14px; }
|
|
2208
|
+
.footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid #f0e2da; color: #7a6a63; font-size: 13px; }
|
|
2209
|
+
.footer strong { color: #251d1a; }
|
|
2210
|
+
`;
|
|
2211
|
+
function renderHtml(record, meta) {
|
|
2212
|
+
const m = record.usageMetrics;
|
|
2213
|
+
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
2214
|
+
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
2215
|
+
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No directly recoverable dollars found. See issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
|
|
2216
|
+
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
2217
|
+
const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
|
|
2218
|
+
return `<!doctype html>
|
|
2219
|
+
<html lang="en">
|
|
2220
|
+
<head>
|
|
2221
|
+
<meta charset="utf-8" />
|
|
2222
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2223
|
+
<title>CostClaw audit report</title>
|
|
2224
|
+
<style>${STYLE}</style>
|
|
2225
|
+
</head>
|
|
2226
|
+
<body>
|
|
2227
|
+
<div class="wrap">
|
|
2228
|
+
<h1>CostClaw audit</h1>
|
|
2229
|
+
<p class="sub">Source: ${esc(meta.root)} (${meta.sessionCount} sessions across ${m.projectsCount} projects)</p>
|
|
2230
|
+
<p class="sub">Pricing snapshot: ${esc(m.pricingSnapshotDate)}</p>
|
|
2231
|
+
|
|
2232
|
+
<div class="banner">
|
|
2233
|
+
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
2234
|
+
<div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>
|
|
2235
|
+
</div>
|
|
2236
|
+
|
|
2237
|
+
<div class="stats">
|
|
2238
|
+
<div class="stat"><div class="k">Spend analyzed</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
|
|
2239
|
+
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
2240
|
+
<div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
2241
|
+
</div>
|
|
2242
|
+
|
|
2243
|
+
<h2>Spend by project</h2>
|
|
2244
|
+
<div class="chart">${projectChart(m.topProjects)}</div>
|
|
2245
|
+
|
|
2246
|
+
<h2>Setup score</h2>
|
|
2247
|
+
<div class="score-head">
|
|
2248
|
+
<span class="big">${record.overallScore} / 100</span>
|
|
2249
|
+
<span class="band">${esc(record.band.label)}</span>
|
|
2250
|
+
</div>
|
|
2251
|
+
${pillarBars(record.pillarScores)}
|
|
2252
|
+
|
|
2253
|
+
<h2>Top fixes by recoverable spend</h2>
|
|
2254
|
+
${dollarSection}
|
|
2255
|
+
${otherSection}
|
|
2256
|
+
${skippedNote}
|
|
2257
|
+
|
|
2258
|
+
<div class="footer">
|
|
2259
|
+
<strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
|
|
2260
|
+
your prompts, file contents, and paths never left this computer. Generated ${esc(record.createdAt)}.
|
|
2261
|
+
</div>
|
|
2262
|
+
</div>
|
|
2263
|
+
</body>
|
|
2264
|
+
</html>
|
|
2265
|
+
`;
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
// src/card.ts
|
|
2269
|
+
var WIDTH = 600;
|
|
2270
|
+
var HEIGHT = 315;
|
|
2271
|
+
var INK = "#251d1a";
|
|
2272
|
+
var UMBER = "#822d1d";
|
|
2273
|
+
var PAPER = "#fefaf7";
|
|
2274
|
+
var BORDER = "#f0e2da";
|
|
2275
|
+
var MUTED = "#7a6a63";
|
|
2276
|
+
function usd4(n) {
|
|
2277
|
+
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2278
|
+
}
|
|
2279
|
+
function strongestPillar(pillars) {
|
|
2280
|
+
const assessed = pillars.filter((p) => p.assessed && p.score !== null);
|
|
2281
|
+
if (assessed.length === 0) return null;
|
|
2282
|
+
return assessed.reduce((best, p) => p.score > best.score ? p : best);
|
|
2283
|
+
}
|
|
2284
|
+
function renderCard(record) {
|
|
2285
|
+
const scoreColor = bandColorForScore(record.overallScore);
|
|
2286
|
+
const strongest = strongestPillar(record.pillarScores);
|
|
2287
|
+
const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
|
|
2288
|
+
const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
|
|
2289
|
+
const wasteText = usd4(record.headlineWasteUsd);
|
|
2290
|
+
const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
|
|
2291
|
+
const scoreText = String(record.overallScore);
|
|
2292
|
+
const scoreX = 32;
|
|
2293
|
+
const scoreW = estimateTextWidth(scoreText, 72);
|
|
2294
|
+
const outOf100X = scoreX + scoreW + 8;
|
|
2295
|
+
const pillLabel = record.band.label;
|
|
2296
|
+
const pillW = estimateTextWidth(pillLabel, 14) + 32;
|
|
2297
|
+
const pillY = 168;
|
|
2298
|
+
const pillH = 30;
|
|
2299
|
+
const statX = 32;
|
|
2300
|
+
const statY = 224;
|
|
2301
|
+
const statGap = 30;
|
|
2302
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="img" aria-label="${esc(ariaLabel)}">` + rect(0, 0, WIDTH, HEIGHT, PAPER, 16) + `<rect x="0.5" y="0.5" width="${WIDTH - 1}" height="${HEIGHT - 1}" rx="16" fill="none" stroke="${BORDER}"></rect>` + text(32, 48, "CostClaw", { size: 22, weight: 700, fill: UMBER }) + text(scoreX, 150, scoreText, { size: 72, weight: 700, fill: INK }) + text(outOf100X, 150, "/ 100", { size: 22, weight: 600, fill: MUTED }) + rect(32, pillY, pillW, pillH, scoreColor, 15) + text(32 + pillW / 2, pillY + pillH / 2 + 5, pillLabel, { size: 14, weight: 700, fill: "#ffffff", anchor: "middle" }) + text(statX, statY, `Recoverable spend: ${wasteText}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap, `Cache hit rate: ${cacheHitPct}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap * 2, `Strongest pillar: ${strongestText}`, { size: 15, weight: 600, fill: INK }) + `</svg>`;
|
|
2303
|
+
}
|
|
2304
|
+
|
|
1993
2305
|
// src/read-setup.ts
|
|
1994
|
-
import { readFile
|
|
2306
|
+
import { readFile } from "fs/promises";
|
|
1995
2307
|
import { join as join2 } from "path";
|
|
1996
2308
|
import { homedir as homedir2 } from "os";
|
|
1997
2309
|
async function readJson(path) {
|
|
1998
2310
|
try {
|
|
1999
|
-
const parsed = JSON.parse(await
|
|
2311
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
2000
2312
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
2001
2313
|
} catch {
|
|
2002
2314
|
return null;
|
|
@@ -2036,6 +2348,19 @@ async function readSetup(home = homedir2()) {
|
|
|
2036
2348
|
}
|
|
2037
2349
|
|
|
2038
2350
|
// src/audit-command.ts
|
|
2351
|
+
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
2352
|
+
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
2353
|
+
function openInBrowser(target) {
|
|
2354
|
+
try {
|
|
2355
|
+
const platform = process.platform;
|
|
2356
|
+
const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
2357
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
2358
|
+
child.on("error", () => {
|
|
2359
|
+
});
|
|
2360
|
+
child.unref();
|
|
2361
|
+
} catch {
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2039
2364
|
async function loadAuditInputs(opts) {
|
|
2040
2365
|
const root = opts.path || defaultProjectsPath();
|
|
2041
2366
|
const { logs, skipped } = await readSessions(root);
|
|
@@ -2044,7 +2369,7 @@ async function loadAuditInputs(opts) {
|
|
|
2044
2369
|
}
|
|
2045
2370
|
let claudeMd;
|
|
2046
2371
|
if (opts.claudeMdPath) {
|
|
2047
|
-
claudeMd = await
|
|
2372
|
+
claudeMd = await readFile2(opts.claudeMdPath, "utf8");
|
|
2048
2373
|
}
|
|
2049
2374
|
return { logs, claudeMd, root, skipped };
|
|
2050
2375
|
}
|
|
@@ -2052,16 +2377,35 @@ async function runAudit(opts) {
|
|
|
2052
2377
|
const { logs, claudeMd, root, skipped } = await loadAuditInputs(opts);
|
|
2053
2378
|
const setup = await readSetup();
|
|
2054
2379
|
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
|
|
2055
|
-
|
|
2380
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped });
|
|
2381
|
+
const notices = [];
|
|
2382
|
+
if (opts.html) {
|
|
2383
|
+
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
2384
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped });
|
|
2385
|
+
await writeFile(target, doc, "utf8");
|
|
2386
|
+
openInBrowser(target);
|
|
2387
|
+
notices.push(`HTML report written to ${target}`);
|
|
2388
|
+
}
|
|
2389
|
+
if (opts.card) {
|
|
2390
|
+
const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
|
|
2391
|
+
const svg = renderCard(record);
|
|
2392
|
+
await writeFile(target, svg, "utf8");
|
|
2393
|
+
notices.push(`Score card written to ${target}`);
|
|
2394
|
+
}
|
|
2395
|
+
if (opts.json) {
|
|
2396
|
+
for (const notice of notices) process.stderr.write(notice + "\n");
|
|
2397
|
+
} else if (notices.length > 0) {
|
|
2398
|
+
output += "\n\n" + notices.join("\n\n");
|
|
2399
|
+
}
|
|
2056
2400
|
return { output, record };
|
|
2057
2401
|
}
|
|
2058
2402
|
|
|
2059
2403
|
// src/optimize-command.ts
|
|
2060
|
-
import { mkdir, writeFile, readFile as
|
|
2061
|
-
import { join as join4 } from "path";
|
|
2404
|
+
import { mkdir, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
|
|
2405
|
+
import { join as join4, dirname } from "path";
|
|
2062
2406
|
|
|
2063
2407
|
// src/project-scan.ts
|
|
2064
|
-
import { readdir as readdir2, readFile as
|
|
2408
|
+
import { readdir as readdir2, readFile as readFile3, stat } from "fs/promises";
|
|
2065
2409
|
import { join as join3, basename } from "path";
|
|
2066
2410
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
2067
2411
|
"node_modules",
|
|
@@ -2091,7 +2435,7 @@ var DIR_NOTES = {
|
|
|
2091
2435
|
};
|
|
2092
2436
|
async function readText(p) {
|
|
2093
2437
|
try {
|
|
2094
|
-
return await
|
|
2438
|
+
return await readFile3(p, "utf8");
|
|
2095
2439
|
} catch {
|
|
2096
2440
|
return null;
|
|
2097
2441
|
}
|
|
@@ -2117,18 +2461,18 @@ async function listEntries(dir) {
|
|
|
2117
2461
|
function pushUnique(arr, value) {
|
|
2118
2462
|
if (!arr.includes(value)) arr.push(value);
|
|
2119
2463
|
}
|
|
2120
|
-
function parseJson(
|
|
2121
|
-
if (
|
|
2464
|
+
function parseJson(text2) {
|
|
2465
|
+
if (text2 === null) return null;
|
|
2122
2466
|
try {
|
|
2123
|
-
const parsed = JSON.parse(
|
|
2467
|
+
const parsed = JSON.parse(text2);
|
|
2124
2468
|
return parsed && typeof parsed === "object" ? parsed : null;
|
|
2125
2469
|
} catch {
|
|
2126
2470
|
return null;
|
|
2127
2471
|
}
|
|
2128
2472
|
}
|
|
2129
|
-
function parseEnvNames(
|
|
2473
|
+
function parseEnvNames(text2) {
|
|
2130
2474
|
const names = [];
|
|
2131
|
-
for (const raw of
|
|
2475
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2132
2476
|
const line = raw.trim();
|
|
2133
2477
|
if (line === "" || line.startsWith("#")) continue;
|
|
2134
2478
|
const eq = line.indexOf("=");
|
|
@@ -2307,7 +2651,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
2307
2651
|
profile.preCommit = `run ${lintCmd} and ${typecheckCmd} before committing`;
|
|
2308
2652
|
}
|
|
2309
2653
|
}
|
|
2310
|
-
function parsePyproject(
|
|
2654
|
+
function parsePyproject(text2) {
|
|
2311
2655
|
const tables = /* @__PURE__ */ new Set();
|
|
2312
2656
|
let name = null;
|
|
2313
2657
|
let description = null;
|
|
@@ -2320,7 +2664,7 @@ function parsePyproject(text) {
|
|
|
2320
2664
|
const m = cleaned.match(/^[A-Za-z0-9_.\-]+/);
|
|
2321
2665
|
if (m) pushUnique(deps, m[0].toLowerCase());
|
|
2322
2666
|
};
|
|
2323
|
-
for (const raw of
|
|
2667
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2324
2668
|
const line = raw.trim();
|
|
2325
2669
|
if (line === "" || line.startsWith("#")) continue;
|
|
2326
2670
|
const header = line.match(/^\[([^\]]+)\]$/);
|
|
@@ -2372,9 +2716,9 @@ var PY_STACK = {
|
|
|
2372
2716
|
sqlalchemy: "SQLAlchemy",
|
|
2373
2717
|
pydantic: "Pydantic"
|
|
2374
2718
|
};
|
|
2375
|
-
function pyDepsFromRequirements(
|
|
2719
|
+
function pyDepsFromRequirements(text2) {
|
|
2376
2720
|
const deps = [];
|
|
2377
|
-
for (const raw of
|
|
2721
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2378
2722
|
const line = raw.trim();
|
|
2379
2723
|
if (line === "" || line.startsWith("#") || line.startsWith("-")) continue;
|
|
2380
2724
|
const m = line.match(/^[A-Za-z0-9_.\-]+/);
|
|
@@ -2432,12 +2776,12 @@ async function scanPython(dir, files, profile) {
|
|
|
2432
2776
|
}
|
|
2433
2777
|
}
|
|
2434
2778
|
async function scanRust(dir, profile) {
|
|
2435
|
-
const
|
|
2779
|
+
const text2 = await readText(join3(dir, "Cargo.toml"));
|
|
2436
2780
|
pushUnique(profile.stack, "Rust");
|
|
2437
2781
|
profile.packageManager = "cargo";
|
|
2438
|
-
if (
|
|
2782
|
+
if (text2 !== null) {
|
|
2439
2783
|
let section = "";
|
|
2440
|
-
for (const raw of
|
|
2784
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2441
2785
|
const line = raw.trim();
|
|
2442
2786
|
const header = line.match(/^\[([^\]]+)\]$/);
|
|
2443
2787
|
if (header) {
|
|
@@ -2458,11 +2802,11 @@ async function scanRust(dir, profile) {
|
|
|
2458
2802
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
2459
2803
|
}
|
|
2460
2804
|
async function scanGo(dir, profile) {
|
|
2461
|
-
const
|
|
2805
|
+
const text2 = await readText(join3(dir, "go.mod"));
|
|
2462
2806
|
pushUnique(profile.stack, "Go");
|
|
2463
2807
|
profile.packageManager = "go";
|
|
2464
|
-
if (
|
|
2465
|
-
const m =
|
|
2808
|
+
if (text2 !== null) {
|
|
2809
|
+
const m = text2.match(/^module\s+(\S+)/m);
|
|
2466
2810
|
if (m) {
|
|
2467
2811
|
const mod = m[1];
|
|
2468
2812
|
profile.name = mod.includes("/") ? mod.slice(mod.lastIndexOf("/") + 1) : mod;
|
|
@@ -2472,9 +2816,9 @@ async function scanGo(dir, profile) {
|
|
|
2472
2816
|
profile.commands.push({ label: "test", command: "go test ./..." });
|
|
2473
2817
|
profile.commands.push({ label: "lint", command: "go vet ./..." });
|
|
2474
2818
|
}
|
|
2475
|
-
function parseMakefile(
|
|
2819
|
+
function parseMakefile(text2) {
|
|
2476
2820
|
const targets = [];
|
|
2477
|
-
for (const raw of
|
|
2821
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
2478
2822
|
if (/^\t/.test(raw)) continue;
|
|
2479
2823
|
const m = raw.match(/^([A-Za-z0-9_.\-]+)\s*:(?!=)/);
|
|
2480
2824
|
if (m) {
|
|
@@ -2484,8 +2828,8 @@ function parseMakefile(text) {
|
|
|
2484
2828
|
}
|
|
2485
2829
|
return targets;
|
|
2486
2830
|
}
|
|
2487
|
-
function parseReadme(
|
|
2488
|
-
const lines =
|
|
2831
|
+
function parseReadme(text2) {
|
|
2832
|
+
const lines = text2.split(/\r?\n/);
|
|
2489
2833
|
let name = null;
|
|
2490
2834
|
let i = 0;
|
|
2491
2835
|
for (; i < lines.length; i++) {
|
|
@@ -2536,9 +2880,9 @@ async function scanProject(dir) {
|
|
|
2536
2880
|
await scanGo(dir, profile);
|
|
2537
2881
|
}
|
|
2538
2882
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
2539
|
-
const
|
|
2540
|
-
if (
|
|
2541
|
-
for (const t of parseMakefile(
|
|
2883
|
+
const text2 = await readText(join3(dir, "Makefile"));
|
|
2884
|
+
if (text2 !== null) {
|
|
2885
|
+
for (const t of parseMakefile(text2)) {
|
|
2542
2886
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
2543
2887
|
}
|
|
2544
2888
|
}
|
|
@@ -2546,9 +2890,9 @@ async function scanProject(dir) {
|
|
|
2546
2890
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
2547
2891
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
2548
2892
|
if (readmeName) {
|
|
2549
|
-
const
|
|
2550
|
-
if (
|
|
2551
|
-
const parsed = parseReadme(
|
|
2893
|
+
const text2 = await readText(join3(dir, readmeName));
|
|
2894
|
+
if (text2 !== null) {
|
|
2895
|
+
const parsed = parseReadme(text2);
|
|
2552
2896
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
2553
2897
|
if (profile.description === null && parsed.description !== null) {
|
|
2554
2898
|
profile.description = parsed.description;
|
|
@@ -2559,8 +2903,8 @@ async function scanProject(dir) {
|
|
|
2559
2903
|
profile.structure = await detectStructure(dir, dirs);
|
|
2560
2904
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
2561
2905
|
if (envFile) {
|
|
2562
|
-
const
|
|
2563
|
-
if (
|
|
2906
|
+
const text2 = await readText(join3(dir, envFile));
|
|
2907
|
+
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
2564
2908
|
}
|
|
2565
2909
|
return profile;
|
|
2566
2910
|
}
|
|
@@ -2569,7 +2913,7 @@ async function scanProject(dir) {
|
|
|
2569
2913
|
var OPTIMIZED_NAME = "CLAUDE.optimized.md";
|
|
2570
2914
|
var PLAYBOOK_NAME = "PLAYBOOK.md";
|
|
2571
2915
|
var SETTINGS_NAME = "settings.suggested.json";
|
|
2572
|
-
function
|
|
2916
|
+
function usd5(n) {
|
|
2573
2917
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2574
2918
|
}
|
|
2575
2919
|
function describeDetection(project) {
|
|
@@ -2602,6 +2946,78 @@ function lineDiff(oldText, newText) {
|
|
|
2602
2946
|
if (lines.length === 0) lines.push(" (no line-level changes)");
|
|
2603
2947
|
return lines.join("\n");
|
|
2604
2948
|
}
|
|
2949
|
+
function asStringArray(value) {
|
|
2950
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
2951
|
+
}
|
|
2952
|
+
function unionStrings(existing, additions) {
|
|
2953
|
+
const out = [];
|
|
2954
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2955
|
+
for (const v of existing) {
|
|
2956
|
+
if (!seen.has(v)) {
|
|
2957
|
+
seen.add(v);
|
|
2958
|
+
out.push(v);
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
for (const v of additions) {
|
|
2962
|
+
if (!seen.has(v)) {
|
|
2963
|
+
seen.add(v);
|
|
2964
|
+
out.push(v);
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
return out;
|
|
2968
|
+
}
|
|
2969
|
+
function isPlainObject(value) {
|
|
2970
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2971
|
+
}
|
|
2972
|
+
async function applyDerivedSettings(target, suggestedJson, force) {
|
|
2973
|
+
const backup = `${target}.bak`;
|
|
2974
|
+
if (await pathExists(backup) && !force) {
|
|
2975
|
+
throw new Error(
|
|
2976
|
+
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
let existingText = "";
|
|
2980
|
+
let existing = {};
|
|
2981
|
+
if (await pathExists(target)) {
|
|
2982
|
+
existingText = await readFile4(target, "utf8");
|
|
2983
|
+
if (existingText.trim() !== "") {
|
|
2984
|
+
let parsed;
|
|
2985
|
+
try {
|
|
2986
|
+
parsed = JSON.parse(existingText);
|
|
2987
|
+
} catch {
|
|
2988
|
+
throw new Error(
|
|
2989
|
+
`Could not parse ${target} as JSON, so it was left untouched. If it contains comments or trailing commas (JSONC), remove them, or point --apply-settings at a plain JSON file.`
|
|
2990
|
+
);
|
|
2991
|
+
}
|
|
2992
|
+
if (!isPlainObject(parsed)) {
|
|
2993
|
+
throw new Error(
|
|
2994
|
+
`Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
|
|
2995
|
+
);
|
|
2996
|
+
}
|
|
2997
|
+
existing = parsed;
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
const suggested = JSON.parse(suggestedJson);
|
|
3001
|
+
const suggestedAllow = asStringArray(suggested.permissions?.allow);
|
|
3002
|
+
const suggestedDeny = asStringArray(suggested.permissions?.deny);
|
|
3003
|
+
const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
|
|
3004
|
+
const mergedPerms = { ...existingPerms };
|
|
3005
|
+
mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
|
|
3006
|
+
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
3007
|
+
const merged = { ...existing, permissions: mergedPerms };
|
|
3008
|
+
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
3009
|
+
await mkdir(dirname(target), { recursive: true });
|
|
3010
|
+
await writeFile2(backup, existingText, "utf8");
|
|
3011
|
+
await writeFile2(target, mergedText, "utf8");
|
|
3012
|
+
return [
|
|
3013
|
+
`Merged the derived permission allowlist into ${target}`,
|
|
3014
|
+
`Backed up the previous file to ${backup}`,
|
|
3015
|
+
"Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
|
|
3016
|
+
"",
|
|
3017
|
+
"Diff (previous vs merged):",
|
|
3018
|
+
lineDiff(existingText, mergedText)
|
|
3019
|
+
];
|
|
3020
|
+
}
|
|
2605
3021
|
async function runOptimize(opts) {
|
|
2606
3022
|
const { logs, claudeMd } = await loadAuditInputs({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
2607
3023
|
const report = analyzeUploads(logs);
|
|
@@ -2615,9 +3031,9 @@ async function runOptimize(opts) {
|
|
|
2615
3031
|
const outDir = opts.out || join4(process.cwd(), "costclaw-out");
|
|
2616
3032
|
await mkdir(outDir, { recursive: true });
|
|
2617
3033
|
const playbookPath = join4(outDir, PLAYBOOK_NAME);
|
|
2618
|
-
await
|
|
3034
|
+
await writeFile2(playbookPath, result.playbook, "utf8");
|
|
2619
3035
|
const settingsPath = join4(outDir, SETTINGS_NAME);
|
|
2620
|
-
await
|
|
3036
|
+
await writeFile2(settingsPath, result.settingsJson, "utf8");
|
|
2621
3037
|
const lines = [];
|
|
2622
3038
|
lines.push("CostClaw optimize");
|
|
2623
3039
|
lines.push("");
|
|
@@ -2631,10 +3047,10 @@ async function runOptimize(opts) {
|
|
|
2631
3047
|
}
|
|
2632
3048
|
let original = "";
|
|
2633
3049
|
if (await pathExists(target)) {
|
|
2634
|
-
original = await
|
|
3050
|
+
original = await readFile4(target, "utf8");
|
|
2635
3051
|
}
|
|
2636
|
-
await
|
|
2637
|
-
await
|
|
3052
|
+
await writeFile2(backup, original, "utf8");
|
|
3053
|
+
await writeFile2(target, result.optimizedClaudeMd, "utf8");
|
|
2638
3054
|
lines.push(`Backed up the original to ${backup}`);
|
|
2639
3055
|
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
2640
3056
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -2647,19 +3063,26 @@ async function runOptimize(opts) {
|
|
|
2647
3063
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
2648
3064
|
} else {
|
|
2649
3065
|
const optimizedPath = join4(outDir, OPTIMIZED_NAME);
|
|
2650
|
-
await
|
|
3066
|
+
await writeFile2(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
2651
3067
|
lines.push("Dry run (no files of yours were changed).");
|
|
2652
3068
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
2653
3069
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
2654
3070
|
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
2655
3071
|
lines.push("");
|
|
2656
3072
|
lines.push(describeDetection(project));
|
|
2657
|
-
lines.push(`Recoverable spend (cache-miss exposure): ${
|
|
3073
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
|
|
2658
3074
|
lines.push("");
|
|
2659
3075
|
lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
|
|
2660
3076
|
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
2661
3077
|
lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
|
|
2662
|
-
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied
|
|
3078
|
+
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied unless you ask.");
|
|
3079
|
+
lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
|
|
3080
|
+
}
|
|
3081
|
+
if (opts.applySettings) {
|
|
3082
|
+
const target = opts.applySettingsPath || join4(projectDir, ".claude", "settings.json");
|
|
3083
|
+
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
3084
|
+
lines.push("");
|
|
3085
|
+
lines.push(...applyLines);
|
|
2663
3086
|
}
|
|
2664
3087
|
if (result.notes.length > 0) {
|
|
2665
3088
|
lines.push("");
|
|
@@ -2671,14 +3094,47 @@ async function runOptimize(opts) {
|
|
|
2671
3094
|
return { output: lines.join("\n") };
|
|
2672
3095
|
}
|
|
2673
3096
|
|
|
3097
|
+
// src/badge-command.ts
|
|
3098
|
+
import { writeFile as writeFile3 } from "fs/promises";
|
|
3099
|
+
import { resolve as resolve2 } from "path";
|
|
3100
|
+
|
|
3101
|
+
// src/badge.ts
|
|
3102
|
+
var HEIGHT2 = 20;
|
|
3103
|
+
var FONT_SIZE = 11;
|
|
3104
|
+
var PAD_X = 8;
|
|
3105
|
+
var LEFT_LABEL = "costclaw";
|
|
3106
|
+
var LEFT_COLOR = "#822d1d";
|
|
3107
|
+
var CLIP_ID = "costclaw-badge-round";
|
|
3108
|
+
function renderBadge(record) {
|
|
3109
|
+
const scoreLabel = `${record.overallScore}/100`;
|
|
3110
|
+
const leftW = estimateTextWidth(LEFT_LABEL, FONT_SIZE) + PAD_X * 2;
|
|
3111
|
+
const rightW = estimateTextWidth(scoreLabel, FONT_SIZE) + PAD_X * 2;
|
|
3112
|
+
const width = leftW + rightW;
|
|
3113
|
+
const rightColor = bandColorForScore(record.overallScore);
|
|
3114
|
+
const ariaLabel = `costclaw score: ${scoreLabel} (${record.band.label})`;
|
|
3115
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT2}" viewBox="0 0 ${width} ${HEIGHT2}" role="img" aria-label="${esc(ariaLabel)}"><clipPath id="${CLIP_ID}">${rect(0, 0, width, HEIGHT2, "#ffffff", 3)}</clipPath><g clip-path="url(#${CLIP_ID})">` + rect(0, 0, leftW, HEIGHT2, LEFT_COLOR) + rect(leftW, 0, rightW, HEIGHT2, rightColor) + `</g>` + text(leftW / 2, 14, LEFT_LABEL, { size: FONT_SIZE, weight: 600, fill: "#fefaf7", anchor: "middle" }) + text(leftW + rightW / 2, 14, scoreLabel, { size: FONT_SIZE, weight: 700, fill: "#ffffff", anchor: "middle" }) + `</svg>`;
|
|
3116
|
+
}
|
|
3117
|
+
|
|
3118
|
+
// src/badge-command.ts
|
|
3119
|
+
var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
3120
|
+
async function runBadge(opts) {
|
|
3121
|
+
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
3122
|
+
const svg = renderBadge(record);
|
|
3123
|
+
const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
|
|
3124
|
+
await writeFile3(target, svg, "utf8");
|
|
3125
|
+
return { output: `Badge written to ${target}`, record, target };
|
|
3126
|
+
}
|
|
3127
|
+
|
|
2674
3128
|
// src/license.ts
|
|
2675
|
-
import { mkdir as mkdir2, readFile as
|
|
3129
|
+
import { mkdir as mkdir2, readFile as readFile5, writeFile as writeFile4, rm } from "fs/promises";
|
|
2676
3130
|
import { join as join5 } from "path";
|
|
2677
3131
|
import { homedir as homedir3, hostname } from "os";
|
|
2678
|
-
|
|
2679
|
-
var
|
|
2680
|
-
var
|
|
2681
|
-
|
|
3132
|
+
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
3133
|
+
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
3134
|
+
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
3135
|
+
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
3136
|
+
-----END PUBLIC KEY-----`;
|
|
3137
|
+
var KEY_PREFIX = "CC1";
|
|
2682
3138
|
var NOT_ACTIVATED_MESSAGE = [
|
|
2683
3139
|
"costclaw optimize needs a license.",
|
|
2684
3140
|
"",
|
|
@@ -2688,11 +3144,12 @@ var NOT_ACTIVATED_MESSAGE = [
|
|
|
2688
3144
|
"costclaw audit is free and does not need a license."
|
|
2689
3145
|
].join("\n");
|
|
2690
3146
|
var INVALID_MESSAGE = [
|
|
2691
|
-
"
|
|
3147
|
+
"The saved CostClaw license is not valid for this version.",
|
|
2692
3148
|
"",
|
|
2693
|
-
"
|
|
3149
|
+
"Re-activate with the key from your purchase email:",
|
|
2694
3150
|
" costclaw activate <your-license-key>",
|
|
2695
3151
|
"",
|
|
3152
|
+
"Key missing or not working? Email wes@dashclaw.io with your order number.",
|
|
2696
3153
|
"costclaw audit stays free."
|
|
2697
3154
|
].join("\n");
|
|
2698
3155
|
function defaultConfigDir() {
|
|
@@ -2701,13 +3158,30 @@ function defaultConfigDir() {
|
|
|
2701
3158
|
function licenseFile(dir) {
|
|
2702
3159
|
return join5(dir, "license.json");
|
|
2703
3160
|
}
|
|
2704
|
-
function
|
|
2705
|
-
return
|
|
3161
|
+
function base64UrlDecode(part) {
|
|
3162
|
+
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
3163
|
+
}
|
|
3164
|
+
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
3165
|
+
const parts = licenseKey.trim().split(".");
|
|
3166
|
+
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
3167
|
+
const [prefix, payloadPart, signaturePart] = parts;
|
|
3168
|
+
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
3169
|
+
try {
|
|
3170
|
+
const publicKey = createPublicKey(publicKeyPem);
|
|
3171
|
+
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
3172
|
+
const signature = base64UrlDecode(signaturePart);
|
|
3173
|
+
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
3174
|
+
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
3175
|
+
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
3176
|
+
return payload;
|
|
3177
|
+
} catch {
|
|
3178
|
+
return null;
|
|
3179
|
+
}
|
|
2706
3180
|
}
|
|
2707
3181
|
async function readStoredLicense(dir) {
|
|
2708
3182
|
try {
|
|
2709
|
-
const data = JSON.parse(await
|
|
2710
|
-
if (!data || typeof data.licenseKey !== "string"
|
|
3183
|
+
const data = JSON.parse(await readFile5(licenseFile(dir), "utf8"));
|
|
3184
|
+
if (!data || typeof data.licenseKey !== "string") return null;
|
|
2711
3185
|
return data;
|
|
2712
3186
|
} catch {
|
|
2713
3187
|
return null;
|
|
@@ -2715,43 +3189,26 @@ async function readStoredLicense(dir) {
|
|
|
2715
3189
|
}
|
|
2716
3190
|
async function writeStoredLicense(dir, lic) {
|
|
2717
3191
|
await mkdir2(dir, { recursive: true });
|
|
2718
|
-
await
|
|
3192
|
+
await writeFile4(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
2719
3193
|
}
|
|
2720
3194
|
async function clearStoredLicense(dir) {
|
|
2721
3195
|
await rm(licenseFile(dir), { force: true });
|
|
2722
3196
|
}
|
|
2723
|
-
async function post(endpoint, fields, fetchImpl) {
|
|
2724
|
-
const res = await fetchImpl(`${API_BASE}/${endpoint}`, {
|
|
2725
|
-
method: "POST",
|
|
2726
|
-
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
|
|
2727
|
-
body: new URLSearchParams(fields).toString()
|
|
2728
|
-
});
|
|
2729
|
-
return res.json();
|
|
2730
|
-
}
|
|
2731
3197
|
async function activateLicense(licenseKey, opts = {}) {
|
|
2732
3198
|
const key = licenseKey.trim();
|
|
2733
3199
|
if (!key) throw new Error("Provide your license key: costclaw activate <key>");
|
|
2734
|
-
const fetchImpl = opts.fetchImpl ?? defaultFetch;
|
|
2735
3200
|
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2736
|
-
const
|
|
2737
|
-
|
|
2738
|
-
if (json.activated !== true) {
|
|
2739
|
-
const detail = typeof json.error === "string" && json.error ? json.error : "the key could not be activated";
|
|
3201
|
+
const payload = verifyLicenseKey(key, opts.publicKeyPem);
|
|
3202
|
+
if (!payload) {
|
|
2740
3203
|
throw new Error(
|
|
2741
|
-
|
|
2742
|
-
Check the key from your CostClaw purchase email, or buy one at https://costclaw.io.`
|
|
3204
|
+
"Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
|
|
2743
3205
|
);
|
|
2744
3206
|
}
|
|
2745
|
-
if (!metaMatches(json.meta)) {
|
|
2746
|
-
throw new Error("That key is valid but it is not a CostClaw optimize license. Use the key from your CostClaw purchase.");
|
|
2747
|
-
}
|
|
2748
|
-
const instanceId = json.instance?.id;
|
|
2749
|
-
if (!instanceId) throw new Error("Lemon Squeezy did not return an activation id. Try again in a moment.");
|
|
2750
3207
|
const stored = {
|
|
2751
3208
|
licenseKey: key,
|
|
2752
|
-
instanceId,
|
|
2753
|
-
instanceName,
|
|
2754
|
-
email:
|
|
3209
|
+
instanceId: "local",
|
|
3210
|
+
instanceName: opts.instanceName?.trim() || hostname(),
|
|
3211
|
+
email: payload.e,
|
|
2755
3212
|
activatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2756
3213
|
};
|
|
2757
3214
|
await writeStoredLicense(configDir, stored);
|
|
@@ -2761,15 +3218,9 @@ async function checkLicense(opts = {}) {
|
|
|
2761
3218
|
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2762
3219
|
const stored = await readStoredLicense(configDir);
|
|
2763
3220
|
if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
|
|
2764
|
-
const
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
json = await post("validate", { license_key: stored.licenseKey }, fetchImpl);
|
|
2768
|
-
} catch {
|
|
2769
|
-
return { ok: true, email: stored.email, offline: true };
|
|
2770
|
-
}
|
|
2771
|
-
if (json.valid === true && metaMatches(json.meta)) {
|
|
2772
|
-
return { ok: true, email: json.meta?.customer_email ?? stored.email };
|
|
3221
|
+
const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
|
|
3222
|
+
if (payload) {
|
|
3223
|
+
return { ok: true, email: payload.e ?? stored.email };
|
|
2773
3224
|
}
|
|
2774
3225
|
await clearStoredLicense(configDir);
|
|
2775
3226
|
return { ok: false, message: INVALID_MESSAGE };
|
|
@@ -2778,11 +3229,6 @@ async function deactivateLicense(opts = {}) {
|
|
|
2778
3229
|
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2779
3230
|
const stored = await readStoredLicense(configDir);
|
|
2780
3231
|
if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
|
|
2781
|
-
const fetchImpl = opts.fetchImpl ?? defaultFetch;
|
|
2782
|
-
try {
|
|
2783
|
-
await post("deactivate", { license_key: stored.licenseKey, instance_id: stored.instanceId }, fetchImpl);
|
|
2784
|
-
} catch {
|
|
2785
|
-
}
|
|
2786
3232
|
await clearStoredLicense(configDir);
|
|
2787
3233
|
}
|
|
2788
3234
|
|
|
@@ -2795,14 +3241,89 @@ function getFlag(args, name) {
|
|
|
2795
3241
|
const i = args.indexOf(name);
|
|
2796
3242
|
return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
|
|
2797
3243
|
}
|
|
3244
|
+
function optionalPathAfter(args, flag) {
|
|
3245
|
+
const i = args.indexOf(flag);
|
|
3246
|
+
if (i < 0) return void 0;
|
|
3247
|
+
const next = args[i + 1];
|
|
3248
|
+
return next !== void 0 && !next.startsWith("-") ? next : void 0;
|
|
3249
|
+
}
|
|
3250
|
+
function parseAuditFlags(args) {
|
|
3251
|
+
const html = args.includes("--html");
|
|
3252
|
+
const card = args.includes("--card");
|
|
3253
|
+
return {
|
|
3254
|
+
path: getFlag(args, "--path"),
|
|
3255
|
+
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3256
|
+
json: args.includes("--json"),
|
|
3257
|
+
html,
|
|
3258
|
+
htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
|
|
3259
|
+
card,
|
|
3260
|
+
cardPath: card ? optionalPathAfter(args, "--card") : void 0
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
function parseBadgeFlags(args) {
|
|
3264
|
+
return {
|
|
3265
|
+
path: getFlag(args, "--path"),
|
|
3266
|
+
claudeMdPath: getFlag(args, "--claude-md"),
|
|
3267
|
+
out: getFlag(args, "--out")
|
|
3268
|
+
};
|
|
3269
|
+
}
|
|
3270
|
+
function cliVersion() {
|
|
3271
|
+
return true ? "0.2.1" : "0.0.0-dev";
|
|
3272
|
+
}
|
|
3273
|
+
function helpText() {
|
|
3274
|
+
return [
|
|
3275
|
+
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
3276
|
+
"",
|
|
3277
|
+
"Usage:",
|
|
3278
|
+
" costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
|
|
3279
|
+
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
3280
|
+
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
3281
|
+
" costclaw activate <license-key> [--name <machine-name>]",
|
|
3282
|
+
" costclaw deactivate",
|
|
3283
|
+
" costclaw --version",
|
|
3284
|
+
"",
|
|
3285
|
+
"audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
|
|
3286
|
+
"machine and prints a cost report plus a six-pillar setup score. It is free.",
|
|
3287
|
+
"--html writes a self-contained report (default: costclaw-report.html) and opens",
|
|
3288
|
+
"it in your browser; the terminal report still prints.",
|
|
3289
|
+
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
3290
|
+
"score, band, recoverable spend, cache hit rate, and your strongest pillar.",
|
|
3291
|
+
"",
|
|
3292
|
+
"badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
|
|
3293
|
+
"costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
|
|
3294
|
+
"in a README with an <img> tag; it is a static, self-contained file.",
|
|
3295
|
+
"",
|
|
3296
|
+
"optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
|
|
3297
|
+
"scaffold and a prioritized fix playbook. It also scans --project <dir>",
|
|
3298
|
+
"(default: the current directory) to auto-fill the scaffold's name, commands,",
|
|
3299
|
+
"structure, and other facts from your real project files. By default it",
|
|
3300
|
+
"dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
|
|
3301
|
+
"optimized CLAUDE.md in place after backing up the original and printing a diff.",
|
|
3302
|
+
"--apply-settings [file] additively merges the derived permission allowlist into",
|
|
3303
|
+
"the project's .claude/settings.json (or [file]); it only touches",
|
|
3304
|
+
"permissions.allow and permissions.deny, backs up the original, and prints a diff.",
|
|
3305
|
+
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
3306
|
+
"costclaw activate <key>. activate and deactivate move that license between",
|
|
3307
|
+
"machines. audit never needs a license.",
|
|
3308
|
+
"",
|
|
3309
|
+
"Everything runs locally. Nothing is uploaded. Activation is a signed license",
|
|
3310
|
+
"key verified on this machine: there is no license server and no network call.",
|
|
3311
|
+
""
|
|
3312
|
+
].join("\n");
|
|
3313
|
+
}
|
|
2798
3314
|
async function main() {
|
|
2799
3315
|
const [command, ...args] = process.argv.slice(2);
|
|
3316
|
+
if (command === "--version" || command === "-v" || command === "version") {
|
|
3317
|
+
process.stdout.write(cliVersion() + "\n");
|
|
3318
|
+
return;
|
|
3319
|
+
}
|
|
2800
3320
|
if (command === "audit") {
|
|
2801
|
-
const { output } = await runAudit(
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
3321
|
+
const { output } = await runAudit(parseAuditFlags(args));
|
|
3322
|
+
process.stdout.write(output + "\n");
|
|
3323
|
+
return;
|
|
3324
|
+
}
|
|
3325
|
+
if (command === "badge") {
|
|
3326
|
+
const { output } = await runBadge(parseBadgeFlags(args));
|
|
2806
3327
|
process.stdout.write(output + "\n");
|
|
2807
3328
|
return;
|
|
2808
3329
|
}
|
|
@@ -2832,51 +3353,32 @@ Run: costclaw optimize
|
|
|
2832
3353
|
process.stderr.write(gate.message + "\n");
|
|
2833
3354
|
process.exit(1);
|
|
2834
3355
|
}
|
|
2835
|
-
if (gate.offline) {
|
|
2836
|
-
process.stderr.write("Could not reach the license server; running on your saved activation.\n");
|
|
2837
|
-
}
|
|
2838
3356
|
const { output } = await runOptimize({
|
|
2839
3357
|
path: getFlag(args, "--path"),
|
|
2840
3358
|
claudeMdPath: getFlag(args, "--claude-md"),
|
|
2841
3359
|
projectDir: getFlag(args, "--project") || process.cwd(),
|
|
2842
3360
|
out: getFlag(args, "--out"),
|
|
2843
3361
|
write: getFlag(args, "--write"),
|
|
2844
|
-
force: args.includes("--force")
|
|
3362
|
+
force: args.includes("--force"),
|
|
3363
|
+
applySettings: args.includes("--apply-settings"),
|
|
3364
|
+
applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
|
|
2845
3365
|
});
|
|
2846
3366
|
process.stdout.write(output + "\n");
|
|
2847
3367
|
return;
|
|
2848
3368
|
}
|
|
2849
|
-
process.stderr.write(
|
|
2850
|
-
[
|
|
2851
|
-
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
2852
|
-
"",
|
|
2853
|
-
"Usage:",
|
|
2854
|
-
" costclaw audit [--path <dir>] [--claude-md <file>] [--json]",
|
|
2855
|
-
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--force]",
|
|
2856
|
-
" costclaw activate <license-key> [--name <machine-name>]",
|
|
2857
|
-
" costclaw deactivate",
|
|
2858
|
-
"",
|
|
2859
|
-
"audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
|
|
2860
|
-
"machine and prints a cost report plus a six-pillar setup score. It is free.",
|
|
2861
|
-
"",
|
|
2862
|
-
"optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
|
|
2863
|
-
"scaffold and a prioritized fix playbook. It also scans --project <dir>",
|
|
2864
|
-
"(default: the current directory) to auto-fill the scaffold's name, commands,",
|
|
2865
|
-
"structure, and other facts from your real project files. By default it",
|
|
2866
|
-
"dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
|
|
2867
|
-
"optimized CLAUDE.md in place after backing up the original and printing a diff.",
|
|
2868
|
-
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
2869
|
-
"costclaw activate <key>. activate and deactivate move that license between",
|
|
2870
|
-
"machines. audit never needs a license.",
|
|
2871
|
-
"",
|
|
2872
|
-
"Everything runs locally. Nothing is uploaded. The only network call is the",
|
|
2873
|
-
"license check to Lemon Squeezy, which sends just the key, never your logs.",
|
|
2874
|
-
""
|
|
2875
|
-
].join("\n") + "\n"
|
|
2876
|
-
);
|
|
3369
|
+
process.stderr.write(helpText() + "\n");
|
|
2877
3370
|
process.exit(command ? 1 : 0);
|
|
2878
3371
|
}
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
3372
|
+
var isEntryPoint = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
3373
|
+
if (isEntryPoint) {
|
|
3374
|
+
main().catch((err) => {
|
|
3375
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
3376
|
+
process.exit(1);
|
|
3377
|
+
});
|
|
3378
|
+
}
|
|
3379
|
+
export {
|
|
3380
|
+
cliVersion,
|
|
3381
|
+
helpText,
|
|
3382
|
+
parseAuditFlags,
|
|
3383
|
+
parseBadgeFlags
|
|
3384
|
+
};
|