costclaw 0.5.4 → 0.5.6
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 -43
- 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("");
|
|
@@ -1808,7 +1846,6 @@ function buildClaudeMd(input, recoverable, notes, stats) {
|
|
|
1808
1846
|
}
|
|
1809
1847
|
if (carried.workflow) {
|
|
1810
1848
|
parts.push(["## Workflow", "", carried.workflow].join("\n"));
|
|
1811
|
-
filled.push("Workflow");
|
|
1812
1849
|
} else {
|
|
1813
1850
|
stats.placeholders += 1;
|
|
1814
1851
|
parts.push(
|
|
@@ -1826,7 +1863,6 @@ function buildClaudeMd(input, recoverable, notes, stats) {
|
|
|
1826
1863
|
}
|
|
1827
1864
|
if (carried.architecture) {
|
|
1828
1865
|
parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
|
|
1829
|
-
filled.push("Architecture and gotchas");
|
|
1830
1866
|
} else {
|
|
1831
1867
|
stats.placeholders += 1;
|
|
1832
1868
|
parts.push(
|
|
@@ -1907,6 +1943,11 @@ function buildClaudeMd(input, recoverable, notes, stats) {
|
|
|
1907
1943
|
`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
1944
|
);
|
|
1909
1945
|
}
|
|
1946
|
+
if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
|
|
1947
|
+
notes.push(
|
|
1948
|
+
"Left out the YAML frontmatter: CLAUDE.md needs none, and metadata like last-verified dates churns the cache."
|
|
1949
|
+
);
|
|
1950
|
+
}
|
|
1910
1951
|
if (project) {
|
|
1911
1952
|
if (filled.length > 0) {
|
|
1912
1953
|
const growNote = carried.architecture ? "" : "; Architecture and gotchas is left as a placeholder for you to grow";
|
|
@@ -1987,7 +2028,7 @@ function countSessions(report, ruleId) {
|
|
|
1987
2028
|
function tokenDiscipline(report) {
|
|
1988
2029
|
const misroute = countSessions(report, "MODEL_MISROUTE");
|
|
1989
2030
|
const marathon = countSessions(report, "MARATHON_SESSION");
|
|
1990
|
-
const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short
|
|
2031
|
+
const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short premium-model session${misroute === 1 ? "" : "s"} a cheaper model would have served. ` : "";
|
|
1991
2032
|
const compactLead = marathon > 0 ? `Your audit found ${marathon} long session${marathon === 1 ? "" : "s"} whose cache decayed. ` : "";
|
|
1992
2033
|
return [
|
|
1993
2034
|
"## Token discipline",
|
|
@@ -1999,7 +2040,7 @@ function tokenDiscipline(report) {
|
|
|
1999
2040
|
"- Leaving everything on one high level pays for reasoning you do not need. Match the level to the task.",
|
|
2000
2041
|
"",
|
|
2001
2042
|
"### 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.`,
|
|
2043
|
+
`- ${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
2044
|
"",
|
|
2004
2045
|
"### Use fast mode for bulk work",
|
|
2005
2046
|
"- `/fast` pays off when the model already knows what to do: large refactors, documentation, and test generation.",
|
|
@@ -2122,6 +2163,7 @@ function toUsageMetrics(report) {
|
|
|
2122
2163
|
cacheHitRate: round4(s.cacheHitRate),
|
|
2123
2164
|
totalTokens: { ...s.totals },
|
|
2124
2165
|
sessionsCount: s.sessionsCount,
|
|
2166
|
+
delegatedSessionsCount: s.delegatedSessionsCount,
|
|
2125
2167
|
projectsCount: s.projectsCount,
|
|
2126
2168
|
durationHours: round2(s.durationHours),
|
|
2127
2169
|
modelBreakdown,
|
|
@@ -2276,6 +2318,34 @@ function diffAudits(a, b) {
|
|
|
2276
2318
|
fixes: { resolved, appeared, changed }
|
|
2277
2319
|
};
|
|
2278
2320
|
}
|
|
2321
|
+
var SINCE_BASELINE_MIN_TOKENS = 1e6;
|
|
2322
|
+
function sinceBaseline(baseline, current) {
|
|
2323
|
+
const cur = current.usageMetrics.totalTokens;
|
|
2324
|
+
const base = baseline.totals;
|
|
2325
|
+
const period = {
|
|
2326
|
+
input_tokens: cur.input_tokens - base.input_tokens,
|
|
2327
|
+
output_tokens: cur.output_tokens - base.output_tokens,
|
|
2328
|
+
cache_creation_tokens: cur.cache_creation_tokens - base.cache_creation_tokens,
|
|
2329
|
+
cache_read_tokens: cur.cache_read_tokens - base.cache_read_tokens
|
|
2330
|
+
};
|
|
2331
|
+
if (period.input_tokens < 0 || period.output_tokens < 0 || period.cache_creation_tokens < 0 || period.cache_read_tokens < 0) {
|
|
2332
|
+
return { comparable: false, reason: "history reset" };
|
|
2333
|
+
}
|
|
2334
|
+
const inputClass = period.input_tokens + period.cache_creation_tokens + period.cache_read_tokens;
|
|
2335
|
+
if (inputClass < SINCE_BASELINE_MIN_TOKENS) {
|
|
2336
|
+
return { comparable: false, reason: "not enough new usage yet" };
|
|
2337
|
+
}
|
|
2338
|
+
const periodCacheHitRate = cacheHitRate(period);
|
|
2339
|
+
const improvement = Math.max(0, periodCacheHitRate - baseline.cacheHitRate);
|
|
2340
|
+
const recoveredUsd = round22(improvement * inputClass * (FALLBACK.input - FALLBACK.cache_read) / 1e6);
|
|
2341
|
+
return {
|
|
2342
|
+
comparable: true,
|
|
2343
|
+
baselineCacheHitRate: round42(baseline.cacheHitRate),
|
|
2344
|
+
periodCacheHitRate: round42(periodCacheHitRate),
|
|
2345
|
+
recoveredUsd,
|
|
2346
|
+
newSpendUsd: round22(current.usageMetrics.spendUsd - baseline.spendUsd)
|
|
2347
|
+
};
|
|
2348
|
+
}
|
|
2279
2349
|
|
|
2280
2350
|
// ../../packages/engine/src/validate.ts
|
|
2281
2351
|
var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
@@ -2423,6 +2493,15 @@ function ansi(enabled) {
|
|
|
2423
2493
|
}
|
|
2424
2494
|
|
|
2425
2495
|
// src/format.ts
|
|
2496
|
+
function sinceOptimizeLine(meta) {
|
|
2497
|
+
const so = meta.sinceOptimize;
|
|
2498
|
+
if (!so || !so.result.comparable) return null;
|
|
2499
|
+
const r = so.result;
|
|
2500
|
+
const date = so.at.slice(0, 10);
|
|
2501
|
+
const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
|
|
2502
|
+
const worth = r.recoveredUsd >= 0.01 ? `; worth about ${usd2(r.recoveredUsd)} at Sonnet rates` : "";
|
|
2503
|
+
return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
|
|
2504
|
+
}
|
|
2426
2505
|
function usd2(n) {
|
|
2427
2506
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2428
2507
|
}
|
|
@@ -2521,9 +2600,10 @@ function formatAudit(record, meta, color = false) {
|
|
|
2521
2600
|
const shareText = `${(share * 100).toFixed(1)}%`;
|
|
2522
2601
|
const lines = [];
|
|
2523
2602
|
lines.push(a.bold("CostClaw audit"));
|
|
2603
|
+
const delegated = m.delegatedSessionsCount ?? 0;
|
|
2524
2604
|
pushProse(
|
|
2525
2605
|
lines,
|
|
2526
|
-
`Source: ${meta.root} (${
|
|
2606
|
+
`Source: ${meta.root} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${delegated > 0 ? ` +${delegated} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
|
|
2527
2607
|
0,
|
|
2528
2608
|
a.dim
|
|
2529
2609
|
);
|
|
@@ -2533,6 +2613,8 @@ function formatAudit(record, meta, color = false) {
|
|
|
2533
2613
|
lines.push(
|
|
2534
2614
|
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
2615
|
);
|
|
2616
|
+
const receipt = sinceOptimizeLine(meta);
|
|
2617
|
+
if (receipt) pushProse(lines, receipt, 0, a.dim);
|
|
2536
2618
|
lines.push("");
|
|
2537
2619
|
const mix = modelMix(m.modelBreakdown);
|
|
2538
2620
|
const statBlock = [
|
|
@@ -2851,10 +2933,12 @@ function renderHtml(record, meta) {
|
|
|
2851
2933
|
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
2934
|
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
2853
2935
|
const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
|
|
2936
|
+
const receipt = sinceOptimizeLine(meta);
|
|
2854
2937
|
const metaBlock = [
|
|
2855
|
-
`Source: ${esc(meta.root)} (${
|
|
2938
|
+
`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
2939
|
meta.claudeMdSource ? `CLAUDE.md: ${esc(meta.claudeMdSource)}` : "",
|
|
2857
|
-
`Pricing snapshot: ${esc(m.pricingSnapshotDate)}
|
|
2940
|
+
`Pricing snapshot: ${esc(m.pricingSnapshotDate)}`,
|
|
2941
|
+
receipt ? `<strong>${esc(receipt)}</strong>` : ""
|
|
2858
2942
|
].filter((line) => line.length > 0).map((line) => `<p class="meta">${line}</p>`).join("\n");
|
|
2859
2943
|
return `<!doctype html>
|
|
2860
2944
|
<html lang="en">
|
|
@@ -2998,6 +3082,16 @@ async function readSetup(home = homedir2()) {
|
|
|
2998
3082
|
// src/config.ts
|
|
2999
3083
|
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
3000
3084
|
import { join as join3 } from "path";
|
|
3085
|
+
var TOTAL_KEYS = ["input_tokens", "output_tokens", "cache_creation_tokens", "cache_read_tokens"];
|
|
3086
|
+
function asBaseline(value) {
|
|
3087
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
3088
|
+
const o = value;
|
|
3089
|
+
const totals = o["totals"];
|
|
3090
|
+
if (!totals || typeof totals !== "object" || Array.isArray(totals)) return void 0;
|
|
3091
|
+
const t = totals;
|
|
3092
|
+
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");
|
|
3093
|
+
return ok ? value : void 0;
|
|
3094
|
+
}
|
|
3001
3095
|
function configFile(dir) {
|
|
3002
3096
|
return join3(dir, "config.json");
|
|
3003
3097
|
}
|
|
@@ -3013,6 +3107,8 @@ async function readCliConfig(dir) {
|
|
|
3013
3107
|
const raw = await readRaw(dir);
|
|
3014
3108
|
const cfg = {};
|
|
3015
3109
|
if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
|
|
3110
|
+
const baseline = asBaseline(raw["lastOptimize"]);
|
|
3111
|
+
if (baseline) cfg.lastOptimize = baseline;
|
|
3016
3112
|
return cfg;
|
|
3017
3113
|
}
|
|
3018
3114
|
async function saveCliConfig(dir, patch) {
|
|
@@ -3080,6 +3176,8 @@ async function runAudit(opts) {
|
|
|
3080
3176
|
const configDir = join4(opts.home ?? homedir3(), ".costclaw");
|
|
3081
3177
|
const { plan, planSource } = await resolvePlan(configDir, opts.plan);
|
|
3082
3178
|
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
|
|
3179
|
+
const baseline = (await readCliConfig(configDir)).lastOptimize;
|
|
3180
|
+
const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
|
|
3083
3181
|
let snapshotNotice = null;
|
|
3084
3182
|
try {
|
|
3085
3183
|
const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
|
|
@@ -3096,12 +3194,12 @@ async function runAudit(opts) {
|
|
|
3096
3194
|
`);
|
|
3097
3195
|
}
|
|
3098
3196
|
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);
|
|
3197
|
+
let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize }, color);
|
|
3100
3198
|
const notices = [];
|
|
3101
3199
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
3102
3200
|
if (opts.html) {
|
|
3103
3201
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
3104
|
-
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
|
|
3202
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize });
|
|
3105
3203
|
await writeFile2(target, doc, "utf8");
|
|
3106
3204
|
openInBrowser(target);
|
|
3107
3205
|
notices.push(`HTML report written to ${target}`);
|
|
@@ -3750,11 +3848,22 @@ async function runOptimize(opts) {
|
|
|
3750
3848
|
const report = analyzeUploads(logs);
|
|
3751
3849
|
const cmd = analyzeClaudeMd(claudeMd);
|
|
3752
3850
|
const { pillars } = scorePillars(report, cmd, {});
|
|
3753
|
-
const
|
|
3851
|
+
const configDir = join6(opts.home ?? homedir4(), ".costclaw");
|
|
3852
|
+
const { plan } = await resolvePlan(configDir, opts.plan);
|
|
3754
3853
|
const { fixes } = synthesize(report, pillars, cmd, plan);
|
|
3755
3854
|
const project = await scanProject(projectDir);
|
|
3756
3855
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
3757
3856
|
const recoverable = cacheMissExposureUsd(report);
|
|
3857
|
+
const baselineSpend = report.summary.cost_usd;
|
|
3858
|
+
await saveCliConfig(configDir, {
|
|
3859
|
+
lastOptimize: {
|
|
3860
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3861
|
+
totals: { ...report.summary.totals },
|
|
3862
|
+
cacheHitRate: report.summary.cacheHitRate,
|
|
3863
|
+
headlineWasteShare: baselineSpend > 0 ? recoverable / baselineSpend : 0,
|
|
3864
|
+
spendUsd: baselineSpend
|
|
3865
|
+
}
|
|
3866
|
+
});
|
|
3758
3867
|
const outDir = opts.out || join6(process.cwd(), "costclaw-out");
|
|
3759
3868
|
await mkdir3(outDir, { recursive: true });
|
|
3760
3869
|
const playbookPath = join6(outDir, PLAYBOOK_NAME);
|
|
@@ -3834,6 +3943,7 @@ async function runOptimize(opts) {
|
|
|
3834
3943
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
3835
3944
|
}
|
|
3836
3945
|
lines.push("");
|
|
3946
|
+
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
3837
3947
|
lines.push("Nothing left your machine.");
|
|
3838
3948
|
return { output: lines.join("\n") };
|
|
3839
3949
|
}
|
|
@@ -3999,12 +4109,44 @@ async function runDiff(opts) {
|
|
|
3999
4109
|
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
|
|
4000
4110
|
import { join as join8 } from "path";
|
|
4001
4111
|
import { homedir as homedir6, hostname } from "os";
|
|
4002
|
-
|
|
4112
|
+
|
|
4113
|
+
// ../../packages/license/src/keys.ts
|
|
4003
4114
|
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
4115
|
+
var KEY_PREFIX = "CC1";
|
|
4004
4116
|
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
4005
4117
|
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
4006
4118
|
-----END PUBLIC KEY-----`;
|
|
4007
|
-
|
|
4119
|
+
|
|
4120
|
+
// ../../packages/license/src/verify.ts
|
|
4121
|
+
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
4122
|
+
function base64UrlDecode(part) {
|
|
4123
|
+
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
4124
|
+
}
|
|
4125
|
+
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
4126
|
+
const parts = licenseKey.trim().split(".");
|
|
4127
|
+
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
4128
|
+
const [prefix, payloadPart, signaturePart] = parts;
|
|
4129
|
+
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
4130
|
+
try {
|
|
4131
|
+
const publicKey = createPublicKey(publicKeyPem);
|
|
4132
|
+
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
4133
|
+
const signature = base64UrlDecode(signaturePart);
|
|
4134
|
+
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
4135
|
+
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
4136
|
+
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
4137
|
+
return payload;
|
|
4138
|
+
} catch {
|
|
4139
|
+
return null;
|
|
4140
|
+
}
|
|
4141
|
+
}
|
|
4142
|
+
|
|
4143
|
+
// ../../packages/license/src/mint.ts
|
|
4144
|
+
import { createPrivateKey, sign } from "crypto";
|
|
4145
|
+
|
|
4146
|
+
// ../../packages/license/src/stripe.ts
|
|
4147
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4148
|
+
|
|
4149
|
+
// src/license.ts
|
|
4008
4150
|
var NOT_ACTIVATED_MESSAGE = [
|
|
4009
4151
|
"costclaw optimize needs a license.",
|
|
4010
4152
|
"",
|
|
@@ -4028,26 +4170,6 @@ function defaultConfigDir() {
|
|
|
4028
4170
|
function licenseFile(dir) {
|
|
4029
4171
|
return join8(dir, "license.json");
|
|
4030
4172
|
}
|
|
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
4173
|
async function readStoredLicense(dir) {
|
|
4052
4174
|
try {
|
|
4053
4175
|
const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
|
|
@@ -4149,7 +4271,7 @@ function parseBadgeFlags(args) {
|
|
|
4149
4271
|
};
|
|
4150
4272
|
}
|
|
4151
4273
|
function cliVersion() {
|
|
4152
|
-
return true ? "0.5.
|
|
4274
|
+
return true ? "0.5.6" : "0.0.0-dev";
|
|
4153
4275
|
}
|
|
4154
4276
|
function helpText() {
|
|
4155
4277
|
return [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.6",
|
|
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": {
|