costclaw 0.5.4 → 0.5.5
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/dist/index.js +165 -41
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -71,6 +71,11 @@ function isOpus(model) {
|
|
|
71
71
|
if (!model) return false;
|
|
72
72
|
return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
|
|
73
73
|
}
|
|
74
|
+
function isPremiumModel(model) {
|
|
75
|
+
if (!model) return false;
|
|
76
|
+
const base = model.replace(/\[[^\]]*\]$/, "");
|
|
77
|
+
return base.startsWith("claude-opus") || base.startsWith("claude-fable");
|
|
78
|
+
}
|
|
74
79
|
|
|
75
80
|
// ../../packages/engine/src/sanitize.ts
|
|
76
81
|
var EM_OR_EN = /[—–]/;
|
|
@@ -569,7 +574,7 @@ function ruleModelMisroute(ctx) {
|
|
|
569
574
|
for (const proj of ctx.projects) {
|
|
570
575
|
for (const s of proj.sessions) {
|
|
571
576
|
if (s.kind !== "main") continue;
|
|
572
|
-
if (!
|
|
577
|
+
if (!isPremiumModel(s.modelPrimary)) continue;
|
|
573
578
|
if (s.turnCache.length > MISROUTE_MAX_TURNS) continue;
|
|
574
579
|
if (s.durationMinutes == null || s.durationMinutes > MISROUTE_MAX_MINUTES) continue;
|
|
575
580
|
const tu = s.toolUsage;
|
|
@@ -578,13 +583,14 @@ function ruleModelMisroute(ctx) {
|
|
|
578
583
|
if (s.totals.output_tokens > MISROUTE_MAX_OUTPUT) continue;
|
|
579
584
|
const exposure = s.cost_usd - costForTotals(MISROUTE_BASELINE, s.totals);
|
|
580
585
|
if (exposure < MISROUTE_MIN_EXPOSURE) continue;
|
|
586
|
+
const family = /fable/.test(s.modelPrimary ?? "") ? "Fable" : "Opus";
|
|
581
587
|
out.push({
|
|
582
588
|
ruleId: "MODEL_MISROUTE",
|
|
583
589
|
severity: severityForSavings(exposure),
|
|
584
590
|
project: proj.slug,
|
|
585
|
-
title:
|
|
586
|
-
description: `
|
|
587
|
-
suggestedAction: "Use a cheaper model such as Sonnet for short, simple sessions, and reserve
|
|
591
|
+
title: `${family} used for a small task`,
|
|
592
|
+
description: `A ${family} session ran ${s.turnCache.length} turns in ${s.durationMinutes.toFixed(1)} minutes with light tool use and a small output; a cheaper model would have served it.`,
|
|
593
|
+
suggestedAction: "Use a cheaper model such as Sonnet for short, simple sessions, and reserve premium models for hard problems.",
|
|
588
594
|
estimatedMonthlySavingsUsd: exposure,
|
|
589
595
|
evidence: { model: s.modelPrimary, turns: s.turnCache.length, minutes: s.durationMinutes, outputTokens: s.totals.output_tokens, exposureUsd: exposure, sessionUuid: s.sessionUuid }
|
|
590
596
|
});
|
|
@@ -1363,9 +1369,9 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1363
1369
|
pillarName: PILLARS.cost_discipline.name,
|
|
1364
1370
|
severity: sevForUsd(misrouteUsd),
|
|
1365
1371
|
wasteUsd: round23(misrouteUsd),
|
|
1366
|
-
problem: sanitizeText(`${n} short
|
|
1367
|
-
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve
|
|
1368
|
-
basis: sanitizeText("
|
|
1372
|
+
problem: sanitizeText(`${n} short premium-model ${sWord(n)} (Opus or Fable) with light tool use and small output cost about ${usd7(misrouteUsd)} more than a cheaper model would have.`),
|
|
1373
|
+
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve premium models for hard reasoning."),
|
|
1374
|
+
basis: sanitizeText("Premium session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1369
1375
|
});
|
|
1370
1376
|
}
|
|
1371
1377
|
if (marathonSet.size > 0) {
|
|
@@ -1573,13 +1579,23 @@ var VOLATILE_HEADING = /^(status|changelog|progress|history|roadmap|todos?|next
|
|
|
1573
1579
|
var WORKFLOW_HEADING = /workflow|etiquette|contributing|branch|commit/i;
|
|
1574
1580
|
var ARCH_HEADING = /architecture|gotcha|footgun|how it works|data flow|overview/i;
|
|
1575
1581
|
function carriedSections(currentClaudeMd) {
|
|
1576
|
-
const out = {
|
|
1582
|
+
const out = {
|
|
1583
|
+
workflow: null,
|
|
1584
|
+
architecture: null,
|
|
1585
|
+
other: [],
|
|
1586
|
+
droppedVolatile: [],
|
|
1587
|
+
replaced: [],
|
|
1588
|
+
commandsBody: null
|
|
1589
|
+
};
|
|
1577
1590
|
if (!currentClaudeMd) return out;
|
|
1578
1591
|
for (const section of parseSections(currentClaudeMd)) {
|
|
1579
1592
|
if (VOLATILE_HEADING.test(section.heading)) {
|
|
1580
1593
|
out.droppedVolatile.push(section.heading);
|
|
1581
1594
|
} else if (REGENERATED_HEADING.some((re) => re.test(section.heading))) {
|
|
1582
1595
|
out.replaced.push(section.heading);
|
|
1596
|
+
if (out.commandsBody === null && /^(commands?|scripts?)\b/i.test(section.heading)) {
|
|
1597
|
+
out.commandsBody = section.body;
|
|
1598
|
+
}
|
|
1583
1599
|
} else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
|
|
1584
1600
|
out.workflow = section.body;
|
|
1585
1601
|
} else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
|
|
@@ -1613,11 +1629,30 @@ function curateCommands(commands) {
|
|
|
1613
1629
|
const chosen = (kept.length >= 4 ? kept : commands).slice(0, MAX_COMMANDS);
|
|
1614
1630
|
return { kept: chosen, dropped: commands.length - chosen.length };
|
|
1615
1631
|
}
|
|
1616
|
-
function commandLine(c) {
|
|
1632
|
+
function commandLine(c, note) {
|
|
1633
|
+
if (note) return `- \`${c.command}\` ${note}`;
|
|
1617
1634
|
const tokens = c.command.toLowerCase().split(/[^a-z0-9:_-]+/);
|
|
1618
1635
|
const redundant = tokens.includes(c.label.toLowerCase());
|
|
1619
1636
|
return redundant ? `- \`${c.command}\`` : `- \`${c.command}\` ${c.label}`;
|
|
1620
1637
|
}
|
|
1638
|
+
var NOTE_MAX = 80;
|
|
1639
|
+
function extractCommandNotes(body) {
|
|
1640
|
+
const notes = /* @__PURE__ */ new Map();
|
|
1641
|
+
if (!body) return notes;
|
|
1642
|
+
const keyOf = (cmd) => cmd.trim().replace(/\s+/g, " ");
|
|
1643
|
+
for (const raw of body.split("\n")) {
|
|
1644
|
+
const line = raw.trim();
|
|
1645
|
+
if (!line || line.startsWith("```") || line.startsWith("#")) continue;
|
|
1646
|
+
const fence = line.match(/^([^#`]+?)\s+#\s*(.+)$/);
|
|
1647
|
+
if (fence) {
|
|
1648
|
+
notes.set(keyOf(fence[1]), fence[2].trim().slice(0, NOTE_MAX));
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
const bullet = line.match(/^[-*]\s+`([^`]+)`\s+(.+)$/);
|
|
1652
|
+
if (bullet) notes.set(keyOf(bullet[1]), bullet[2].trim().slice(0, NOTE_MAX));
|
|
1653
|
+
}
|
|
1654
|
+
return notes;
|
|
1655
|
+
}
|
|
1621
1656
|
function stackOneLiner(stack) {
|
|
1622
1657
|
const items = stack.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1623
1658
|
if (items.length === 0) return null;
|
|
@@ -1699,9 +1734,12 @@ function buildClaudeMd(input, recoverable, notes, stats) {
|
|
|
1699
1734
|
parts.push([`# ${titleText}`, "", descLine].join("\n"));
|
|
1700
1735
|
const allCommands = project?.commands ?? [];
|
|
1701
1736
|
const { kept: commands, dropped: droppedCommands } = curateCommands(allCommands);
|
|
1737
|
+
const commandNotes = extractCommandNotes(carried.commandsBody);
|
|
1702
1738
|
if (commands.length > 0) {
|
|
1703
1739
|
const lines = ["## Commands", ""];
|
|
1704
|
-
for (const c of commands)
|
|
1740
|
+
for (const c of commands) {
|
|
1741
|
+
lines.push(commandLine(c, commandNotes.get(c.command.trim().replace(/\s+/g, " "))));
|
|
1742
|
+
}
|
|
1705
1743
|
if (project?.preCommit) lines.push(`- IMPORTANT: ${project.preCommit}.`);
|
|
1706
1744
|
if (droppedCommands > 0) {
|
|
1707
1745
|
lines.push("");
|
|
@@ -1907,6 +1945,11 @@ function buildClaudeMd(input, recoverable, notes, stats) {
|
|
|
1907
1945
|
`Left out ${joinAnd(carried.droppedVolatile)}: status-style sections churn on every update and bust the prompt cache. Keep that content in docs or a scratch note the agent opens on demand.`
|
|
1908
1946
|
);
|
|
1909
1947
|
}
|
|
1948
|
+
if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
|
|
1949
|
+
notes.push(
|
|
1950
|
+
"Left out the YAML frontmatter: CLAUDE.md needs none, and metadata like last-verified dates churns the cache."
|
|
1951
|
+
);
|
|
1952
|
+
}
|
|
1910
1953
|
if (project) {
|
|
1911
1954
|
if (filled.length > 0) {
|
|
1912
1955
|
const growNote = carried.architecture ? "" : "; Architecture and gotchas is left as a placeholder for you to grow";
|
|
@@ -1987,7 +2030,7 @@ function countSessions(report, ruleId) {
|
|
|
1987
2030
|
function tokenDiscipline(report) {
|
|
1988
2031
|
const misroute = countSessions(report, "MODEL_MISROUTE");
|
|
1989
2032
|
const marathon = countSessions(report, "MARATHON_SESSION");
|
|
1990
|
-
const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short
|
|
2033
|
+
const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short premium-model session${misroute === 1 ? "" : "s"} a cheaper model would have served. ` : "";
|
|
1991
2034
|
const compactLead = marathon > 0 ? `Your audit found ${marathon} long session${marathon === 1 ? "" : "s"} whose cache decayed. ` : "";
|
|
1992
2035
|
return [
|
|
1993
2036
|
"## Token discipline",
|
|
@@ -1999,7 +2042,7 @@ function tokenDiscipline(report) {
|
|
|
1999
2042
|
"- Leaving everything on one high level pays for reasoning you do not need. Match the level to the task.",
|
|
2000
2043
|
"",
|
|
2001
2044
|
"### Match the model to the task",
|
|
2002
|
-
`- ${modelLead}Use a cheaper model such as Sonnet for routine edits, a fast model such as Haiku for throwaway questions, and reserve Opus for hard reasoning.`,
|
|
2045
|
+
`- ${modelLead}Use a cheaper model such as Sonnet for routine edits, a fast model such as Haiku for throwaway questions, and reserve premium models (Opus, Fable) for hard reasoning.`,
|
|
2003
2046
|
"",
|
|
2004
2047
|
"### Use fast mode for bulk work",
|
|
2005
2048
|
"- `/fast` pays off when the model already knows what to do: large refactors, documentation, and test generation.",
|
|
@@ -2122,6 +2165,7 @@ function toUsageMetrics(report) {
|
|
|
2122
2165
|
cacheHitRate: round4(s.cacheHitRate),
|
|
2123
2166
|
totalTokens: { ...s.totals },
|
|
2124
2167
|
sessionsCount: s.sessionsCount,
|
|
2168
|
+
delegatedSessionsCount: s.delegatedSessionsCount,
|
|
2125
2169
|
projectsCount: s.projectsCount,
|
|
2126
2170
|
durationHours: round2(s.durationHours),
|
|
2127
2171
|
modelBreakdown,
|
|
@@ -2276,6 +2320,34 @@ function diffAudits(a, b) {
|
|
|
2276
2320
|
fixes: { resolved, appeared, changed }
|
|
2277
2321
|
};
|
|
2278
2322
|
}
|
|
2323
|
+
var SINCE_BASELINE_MIN_TOKENS = 1e6;
|
|
2324
|
+
function sinceBaseline(baseline, current) {
|
|
2325
|
+
const cur = current.usageMetrics.totalTokens;
|
|
2326
|
+
const base = baseline.totals;
|
|
2327
|
+
const period = {
|
|
2328
|
+
input_tokens: cur.input_tokens - base.input_tokens,
|
|
2329
|
+
output_tokens: cur.output_tokens - base.output_tokens,
|
|
2330
|
+
cache_creation_tokens: cur.cache_creation_tokens - base.cache_creation_tokens,
|
|
2331
|
+
cache_read_tokens: cur.cache_read_tokens - base.cache_read_tokens
|
|
2332
|
+
};
|
|
2333
|
+
if (period.input_tokens < 0 || period.output_tokens < 0 || period.cache_creation_tokens < 0 || period.cache_read_tokens < 0) {
|
|
2334
|
+
return { comparable: false, reason: "history reset" };
|
|
2335
|
+
}
|
|
2336
|
+
const inputClass = period.input_tokens + period.cache_creation_tokens + period.cache_read_tokens;
|
|
2337
|
+
if (inputClass < SINCE_BASELINE_MIN_TOKENS) {
|
|
2338
|
+
return { comparable: false, reason: "not enough new usage yet" };
|
|
2339
|
+
}
|
|
2340
|
+
const periodCacheHitRate = cacheHitRate(period);
|
|
2341
|
+
const improvement = Math.max(0, periodCacheHitRate - baseline.cacheHitRate);
|
|
2342
|
+
const recoveredUsd = round22(improvement * inputClass * (FALLBACK.input - FALLBACK.cache_read) / 1e6);
|
|
2343
|
+
return {
|
|
2344
|
+
comparable: true,
|
|
2345
|
+
baselineCacheHitRate: round42(baseline.cacheHitRate),
|
|
2346
|
+
periodCacheHitRate: round42(periodCacheHitRate),
|
|
2347
|
+
recoveredUsd,
|
|
2348
|
+
newSpendUsd: round22(current.usageMetrics.spendUsd - baseline.spendUsd)
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2279
2351
|
|
|
2280
2352
|
// ../../packages/engine/src/validate.ts
|
|
2281
2353
|
var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
@@ -2423,6 +2495,15 @@ function ansi(enabled) {
|
|
|
2423
2495
|
}
|
|
2424
2496
|
|
|
2425
2497
|
// src/format.ts
|
|
2498
|
+
function sinceOptimizeLine(meta) {
|
|
2499
|
+
const so = meta.sinceOptimize;
|
|
2500
|
+
if (!so || !so.result.comparable) return null;
|
|
2501
|
+
const r = so.result;
|
|
2502
|
+
const date = so.at.slice(0, 10);
|
|
2503
|
+
const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
|
|
2504
|
+
const worth = r.recoveredUsd >= 0.01 ? `; worth about ${usd2(r.recoveredUsd)} at Sonnet rates` : "";
|
|
2505
|
+
return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
|
|
2506
|
+
}
|
|
2426
2507
|
function usd2(n) {
|
|
2427
2508
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2428
2509
|
}
|
|
@@ -2521,9 +2602,10 @@ function formatAudit(record, meta, color = false) {
|
|
|
2521
2602
|
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2522
2603
|
const lines = [];
|
|
2523
2604
|
lines.push(a.bold("CostClaw audit"));
|
|
2605
|
+
const delegated = m.delegatedSessionsCount ?? 0;
|
|
2524
2606
|
pushProse(
|
|
2525
2607
|
lines,
|
|
2526
|
-
`Source: ${meta.root} (${
|
|
2608
|
+
`Source: ${meta.root} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${delegated > 0 ? ` +${delegated} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
|
|
2527
2609
|
0,
|
|
2528
2610
|
a.dim
|
|
2529
2611
|
);
|
|
@@ -2533,6 +2615,8 @@ function formatAudit(record, meta, color = false) {
|
|
|
2533
2615
|
lines.push(
|
|
2534
2616
|
subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed usage")} (${usd2(record.headlineWasteUsd)} at API rates)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd))}`
|
|
2535
2617
|
);
|
|
2618
|
+
const receipt = sinceOptimizeLine(meta);
|
|
2619
|
+
if (receipt) pushProse(lines, receipt, 0, a.dim);
|
|
2536
2620
|
lines.push("");
|
|
2537
2621
|
const mix = modelMix(m.modelBreakdown);
|
|
2538
2622
|
const statBlock = [
|
|
@@ -2851,10 +2935,12 @@ function renderHtml(record, meta) {
|
|
|
2851
2935
|
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>`;
|
|
2852
2936
|
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
2853
2937
|
const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
|
|
2938
|
+
const receipt = sinceOptimizeLine(meta);
|
|
2854
2939
|
const metaBlock = [
|
|
2855
|
-
`Source: ${esc(meta.root)} (${
|
|
2940
|
+
`Source: ${esc(meta.root)} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${(m.delegatedSessionsCount ?? 0) > 0 ? ` +${m.delegatedSessionsCount} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
|
|
2856
2941
|
meta.claudeMdSource ? `CLAUDE.md: ${esc(meta.claudeMdSource)}` : "",
|
|
2857
|
-
`Pricing snapshot: ${esc(m.pricingSnapshotDate)}
|
|
2942
|
+
`Pricing snapshot: ${esc(m.pricingSnapshotDate)}`,
|
|
2943
|
+
receipt ? `<strong>${esc(receipt)}</strong>` : ""
|
|
2858
2944
|
].filter((line) => line.length > 0).map((line) => `<p class="meta">${line}</p>`).join("\n");
|
|
2859
2945
|
return `<!doctype html>
|
|
2860
2946
|
<html lang="en">
|
|
@@ -2998,6 +3084,16 @@ async function readSetup(home = homedir2()) {
|
|
|
2998
3084
|
// src/config.ts
|
|
2999
3085
|
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
3000
3086
|
import { join as join3 } from "path";
|
|
3087
|
+
var TOTAL_KEYS = ["input_tokens", "output_tokens", "cache_creation_tokens", "cache_read_tokens"];
|
|
3088
|
+
function asBaseline(value) {
|
|
3089
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
3090
|
+
const o = value;
|
|
3091
|
+
const totals = o["totals"];
|
|
3092
|
+
if (!totals || typeof totals !== "object" || Array.isArray(totals)) return void 0;
|
|
3093
|
+
const t = totals;
|
|
3094
|
+
const ok = typeof o["at"] === "string" && typeof o["cacheHitRate"] === "number" && typeof o["headlineWasteShare"] === "number" && typeof o["spendUsd"] === "number" && TOTAL_KEYS.every((k) => typeof t[k] === "number");
|
|
3095
|
+
return ok ? value : void 0;
|
|
3096
|
+
}
|
|
3001
3097
|
function configFile(dir) {
|
|
3002
3098
|
return join3(dir, "config.json");
|
|
3003
3099
|
}
|
|
@@ -3013,6 +3109,8 @@ async function readCliConfig(dir) {
|
|
|
3013
3109
|
const raw = await readRaw(dir);
|
|
3014
3110
|
const cfg = {};
|
|
3015
3111
|
if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
|
|
3112
|
+
const baseline = asBaseline(raw["lastOptimize"]);
|
|
3113
|
+
if (baseline) cfg.lastOptimize = baseline;
|
|
3016
3114
|
return cfg;
|
|
3017
3115
|
}
|
|
3018
3116
|
async function saveCliConfig(dir, patch) {
|
|
@@ -3080,6 +3178,8 @@ async function runAudit(opts) {
|
|
|
3080
3178
|
const configDir = join4(opts.home ?? homedir3(), ".costclaw");
|
|
3081
3179
|
const { plan, planSource } = await resolvePlan(configDir, opts.plan);
|
|
3082
3180
|
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
|
|
3181
|
+
const baseline = (await readCliConfig(configDir)).lastOptimize;
|
|
3182
|
+
const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
|
|
3083
3183
|
let snapshotNotice = null;
|
|
3084
3184
|
try {
|
|
3085
3185
|
const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
|
|
@@ -3096,12 +3196,12 @@ async function runAudit(opts) {
|
|
|
3096
3196
|
`);
|
|
3097
3197
|
}
|
|
3098
3198
|
const color = !opts.json && process.stdout.isTTY === true && !process.env["NO_COLOR"];
|
|
3099
|
-
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource }, color);
|
|
3199
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize }, color);
|
|
3100
3200
|
const notices = [];
|
|
3101
3201
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
3102
3202
|
if (opts.html) {
|
|
3103
3203
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
3104
|
-
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
3204
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize });
|
|
3105
3205
|
await writeFile2(target, doc, "utf8");
|
|
3106
3206
|
openInBrowser(target);
|
|
3107
3207
|
notices.push(`HTML report written to ${target}`);
|
|
@@ -3750,11 +3850,22 @@ async function runOptimize(opts) {
|
|
|
3750
3850
|
const report = analyzeUploads(logs);
|
|
3751
3851
|
const cmd = analyzeClaudeMd(claudeMd);
|
|
3752
3852
|
const { pillars } = scorePillars(report, cmd, {});
|
|
3753
|
-
const
|
|
3853
|
+
const configDir = join6(opts.home ?? homedir4(), ".costclaw");
|
|
3854
|
+
const { plan } = await resolvePlan(configDir, opts.plan);
|
|
3754
3855
|
const { fixes } = synthesize(report, pillars, cmd, plan);
|
|
3755
3856
|
const project = await scanProject(projectDir);
|
|
3756
3857
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
3757
3858
|
const recoverable = cacheMissExposureUsd(report);
|
|
3859
|
+
const baselineSpend = report.summary.cost_usd;
|
|
3860
|
+
await saveCliConfig(configDir, {
|
|
3861
|
+
lastOptimize: {
|
|
3862
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3863
|
+
totals: { ...report.summary.totals },
|
|
3864
|
+
cacheHitRate: report.summary.cacheHitRate,
|
|
3865
|
+
headlineWasteShare: baselineSpend > 0 ? recoverable / baselineSpend : 0,
|
|
3866
|
+
spendUsd: baselineSpend
|
|
3867
|
+
}
|
|
3868
|
+
});
|
|
3758
3869
|
const outDir = opts.out || join6(process.cwd(), "costclaw-out");
|
|
3759
3870
|
await mkdir3(outDir, { recursive: true });
|
|
3760
3871
|
const playbookPath = join6(outDir, PLAYBOOK_NAME);
|
|
@@ -3834,6 +3945,7 @@ async function runOptimize(opts) {
|
|
|
3834
3945
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
3835
3946
|
}
|
|
3836
3947
|
lines.push("");
|
|
3948
|
+
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
3837
3949
|
lines.push("Nothing left your machine.");
|
|
3838
3950
|
return { output: lines.join("\n") };
|
|
3839
3951
|
}
|
|
@@ -3999,12 +4111,44 @@ async function runDiff(opts) {
|
|
|
3999
4111
|
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
|
|
4000
4112
|
import { join as join8 } from "path";
|
|
4001
4113
|
import { homedir as homedir6, hostname } from "os";
|
|
4002
|
-
|
|
4114
|
+
|
|
4115
|
+
// ../../packages/license/src/keys.ts
|
|
4003
4116
|
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
4117
|
+
var KEY_PREFIX = "CC1";
|
|
4004
4118
|
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
4005
4119
|
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
4006
4120
|
-----END PUBLIC KEY-----`;
|
|
4007
|
-
|
|
4121
|
+
|
|
4122
|
+
// ../../packages/license/src/verify.ts
|
|
4123
|
+
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
4124
|
+
function base64UrlDecode(part) {
|
|
4125
|
+
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
4126
|
+
}
|
|
4127
|
+
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
4128
|
+
const parts = licenseKey.trim().split(".");
|
|
4129
|
+
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
4130
|
+
const [prefix, payloadPart, signaturePart] = parts;
|
|
4131
|
+
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
4132
|
+
try {
|
|
4133
|
+
const publicKey = createPublicKey(publicKeyPem);
|
|
4134
|
+
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
4135
|
+
const signature = base64UrlDecode(signaturePart);
|
|
4136
|
+
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
4137
|
+
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
4138
|
+
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
4139
|
+
return payload;
|
|
4140
|
+
} catch {
|
|
4141
|
+
return null;
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
|
|
4145
|
+
// ../../packages/license/src/mint.ts
|
|
4146
|
+
import { createPrivateKey, sign } from "crypto";
|
|
4147
|
+
|
|
4148
|
+
// ../../packages/license/src/stripe.ts
|
|
4149
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4150
|
+
|
|
4151
|
+
// src/license.ts
|
|
4008
4152
|
var NOT_ACTIVATED_MESSAGE = [
|
|
4009
4153
|
"costclaw optimize needs a license.",
|
|
4010
4154
|
"",
|
|
@@ -4028,26 +4172,6 @@ function defaultConfigDir() {
|
|
|
4028
4172
|
function licenseFile(dir) {
|
|
4029
4173
|
return join8(dir, "license.json");
|
|
4030
4174
|
}
|
|
4031
|
-
function base64UrlDecode(part) {
|
|
4032
|
-
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
4033
|
-
}
|
|
4034
|
-
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
4035
|
-
const parts = licenseKey.trim().split(".");
|
|
4036
|
-
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
4037
|
-
const [prefix, payloadPart, signaturePart] = parts;
|
|
4038
|
-
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
4039
|
-
try {
|
|
4040
|
-
const publicKey = createPublicKey(publicKeyPem);
|
|
4041
|
-
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
4042
|
-
const signature = base64UrlDecode(signaturePart);
|
|
4043
|
-
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
4044
|
-
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
4045
|
-
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
4046
|
-
return payload;
|
|
4047
|
-
} catch {
|
|
4048
|
-
return null;
|
|
4049
|
-
}
|
|
4050
|
-
}
|
|
4051
4175
|
async function readStoredLicense(dir) {
|
|
4052
4176
|
try {
|
|
4053
4177
|
const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
|
|
@@ -4149,7 +4273,7 @@ function parseBadgeFlags(args) {
|
|
|
4149
4273
|
};
|
|
4150
4274
|
}
|
|
4151
4275
|
function cliVersion() {
|
|
4152
|
-
return true ? "0.5.
|
|
4276
|
+
return true ? "0.5.5" : "0.0.0-dev";
|
|
4153
4277
|
}
|
|
4154
4278
|
function helpText() {
|
|
4155
4279
|
return [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.5",
|
|
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": {
|