costclaw 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1
- package/dist/index.js +614 -63
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -184,6 +184,17 @@ scaffold, a prioritized fix playbook, and a conservative, project-derived
|
|
|
184
184
|
(default: the current directory) to auto-fill the scaffold from your real files.
|
|
185
185
|
By default it dry-runs into `./costclaw-out` and touches none of your files.
|
|
186
186
|
|
|
187
|
+
It also writes `DASHBOARD.html` and opens it: one page that browses every
|
|
188
|
+
artifact, the ranked fixes, and a before and after of your CLAUDE.md (by section,
|
|
189
|
+
as line changes, or side by side). Self-contained, no JavaScript, no network.
|
|
190
|
+
Pass `--no-dashboard` to skip it.
|
|
191
|
+
|
|
192
|
+
And it tells you what it actually did to the file that rides on every turn:
|
|
193
|
+
|
|
194
|
+
```
|
|
195
|
+
Your CLAUDE.md: an estimated 5,266 tokens to 2,479 (52.9% smaller), paid on every turn.
|
|
196
|
+
```
|
|
197
|
+
|
|
187
198
|
The playbook breaks the recoverable headline down by project, so you can see
|
|
188
199
|
which repo owes which dollars and at what cache hit rate:
|
|
189
200
|
|
|
@@ -202,7 +213,7 @@ The rows plus that remainder line always add up to the headline figure above
|
|
|
202
213
|
them, so the breakdown reconciles rather than approximating.
|
|
203
214
|
|
|
204
215
|
```
|
|
205
|
-
costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]
|
|
216
|
+
costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]
|
|
206
217
|
```
|
|
207
218
|
|
|
208
219
|
- `--write <file>` applies the optimized `CLAUDE.md` in place, after backing up
|
package/dist/index.js
CHANGED
|
@@ -244,7 +244,7 @@ function parseSession(text2, opts = {}) {
|
|
|
244
244
|
}
|
|
245
245
|
}
|
|
246
246
|
}
|
|
247
|
-
s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t,
|
|
247
|
+
s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
|
|
248
248
|
s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
|
|
249
249
|
let best = null;
|
|
250
250
|
let bestCount = 0;
|
|
@@ -687,20 +687,20 @@ function cacheMissExposureUsd(report) {
|
|
|
687
687
|
function cacheMissByProject(report) {
|
|
688
688
|
const out = [];
|
|
689
689
|
for (const proj of report.projects) {
|
|
690
|
-
let
|
|
690
|
+
let usd8 = 0;
|
|
691
691
|
let sessionsCount = 0;
|
|
692
692
|
const mainTotals = emptyTotals();
|
|
693
693
|
for (const s of proj.sessions) {
|
|
694
694
|
if (s.kind !== "main") continue;
|
|
695
695
|
sessionsCount += 1;
|
|
696
696
|
const p = priceFor(s.modelPrimary);
|
|
697
|
-
|
|
697
|
+
usd8 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
|
|
698
698
|
mainTotals.input_tokens += s.totals.input_tokens;
|
|
699
699
|
mainTotals.output_tokens += s.totals.output_tokens;
|
|
700
700
|
mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
|
|
701
701
|
mainTotals.cache_read_tokens += s.totals.cache_read_tokens;
|
|
702
702
|
}
|
|
703
|
-
out.push({ slug: proj.slug, usd:
|
|
703
|
+
out.push({ slug: proj.slug, usd: usd8, cacheHitRate: cacheHitRate(mainTotals), sessionsCount });
|
|
704
704
|
}
|
|
705
705
|
return out.sort((a, b) => b.usd - a.usd);
|
|
706
706
|
}
|
|
@@ -1256,6 +1256,7 @@ var CHECK_FIX = {
|
|
|
1256
1256
|
action: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill."
|
|
1257
1257
|
}
|
|
1258
1258
|
};
|
|
1259
|
+
var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
|
|
1259
1260
|
function severityRank(s) {
|
|
1260
1261
|
return s === "critical" ? 3 : s === "warn" ? 2 : 1;
|
|
1261
1262
|
}
|
|
@@ -1263,7 +1264,7 @@ function sizeFix(cmd) {
|
|
|
1263
1264
|
if (cmd.chars > 6e3) {
|
|
1264
1265
|
return {
|
|
1265
1266
|
title: "Trim your CLAUDE.md",
|
|
1266
|
-
action:
|
|
1267
|
+
action: `Your CLAUDE.md is an estimated ${cmd.estTokens.toLocaleString()} tokens (${cmd.chars.toLocaleString()} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
|
|
1267
1268
|
};
|
|
1268
1269
|
}
|
|
1269
1270
|
return {
|
|
@@ -1280,7 +1281,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1280
1281
|
const fixes = [];
|
|
1281
1282
|
const covered = /* @__PURE__ */ new Set();
|
|
1282
1283
|
const round23 = (n) => Math.round(n * 100) / 100;
|
|
1283
|
-
const
|
|
1284
|
+
const usd8 = (n) => {
|
|
1284
1285
|
const fixed = round23(n).toFixed(2);
|
|
1285
1286
|
const dot = fixed.indexOf(".");
|
|
1286
1287
|
const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
@@ -1366,7 +1367,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1366
1367
|
severity: sevForUsd(exposure),
|
|
1367
1368
|
wasteUsd: round23(exposure),
|
|
1368
1369
|
problem: sanitizeText(
|
|
1369
|
-
`Up to ${
|
|
1370
|
+
`Up to ${usd8(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
1370
1371
|
),
|
|
1371
1372
|
action: sanitizeText(action),
|
|
1372
1373
|
basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
|
|
@@ -1375,8 +1376,13 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1375
1376
|
covered.add("cache_churn");
|
|
1376
1377
|
covered.add("recoverable_exposure");
|
|
1377
1378
|
}
|
|
1379
|
+
const singleSessionTools = [];
|
|
1378
1380
|
for (const [tool, e] of heavyByTool) {
|
|
1379
1381
|
const n = Math.max(e.sessionsAffected, 1);
|
|
1382
|
+
if (n < HEAVY_TOOL_PATTERN_MIN_SESSIONS) {
|
|
1383
|
+
singleSessionTools.push([tool, e]);
|
|
1384
|
+
continue;
|
|
1385
|
+
}
|
|
1380
1386
|
fixes.push({
|
|
1381
1387
|
id: `heavy_tool_${tool}`,
|
|
1382
1388
|
title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
|
|
@@ -1389,6 +1395,21 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1389
1395
|
basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold.")
|
|
1390
1396
|
});
|
|
1391
1397
|
}
|
|
1398
|
+
if (singleSessionTools.length > 0) {
|
|
1399
|
+
const named = singleSessionTools.map(([tool, e]) => `${tool} (${e.maxFires}+ fires, 1 session)`);
|
|
1400
|
+
const k = singleSessionTools.length;
|
|
1401
|
+
fixes.push({
|
|
1402
|
+
id: "heavy_tool_single_session",
|
|
1403
|
+
title: `${k} more tool${k === 1 ? "" : "s"} flagged in a single session`,
|
|
1404
|
+
pillar: "prompting",
|
|
1405
|
+
pillarName: PILLARS.prompting.name,
|
|
1406
|
+
severity: "info",
|
|
1407
|
+
wasteUsd: 0,
|
|
1408
|
+
problem: sanitizeText(`${named.join(", ")} each fired 100 or more times, but only in one session so far, so it may be a one-off rather than a pattern.`),
|
|
1409
|
+
action: sanitizeText("Worth a look if it recurs across more sessions; not yet a repeating pattern to fix."),
|
|
1410
|
+
basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold; grouped because each tool affected only one session.")
|
|
1411
|
+
});
|
|
1412
|
+
}
|
|
1392
1413
|
if (shortCount > 0) {
|
|
1393
1414
|
fixes.push({
|
|
1394
1415
|
id: "short_sessions",
|
|
@@ -1411,7 +1432,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1411
1432
|
pillarName: PILLARS.cost_discipline.name,
|
|
1412
1433
|
severity: sevForUsd(misrouteUsd),
|
|
1413
1434
|
wasteUsd: round23(misrouteUsd),
|
|
1414
|
-
problem: sanitizeText(`${n} short premium-model ${sWord(n)} (Opus or Fable) with light tool use and small output cost about ${
|
|
1435
|
+
problem: sanitizeText(`${n} short premium-model ${sWord(n)} (Opus or Fable) with light tool use and small output cost about ${usd8(misrouteUsd)} more than a cheaper model would have.`),
|
|
1415
1436
|
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve premium models for hard reasoning."),
|
|
1416
1437
|
basis: sanitizeText("Premium session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1417
1438
|
});
|
|
@@ -1425,7 +1446,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1425
1446
|
pillarName: PILLARS.session_mgmt.name,
|
|
1426
1447
|
severity: sevForUsd(marathonUsd),
|
|
1427
1448
|
wasteUsd: round23(marathonUsd),
|
|
1428
|
-
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${
|
|
1449
|
+
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd8(marathonUsd)} for context in the later turns.`),
|
|
1429
1450
|
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1430
1451
|
basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
|
|
1431
1452
|
});
|
|
@@ -1438,7 +1459,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1438
1459
|
pillarName: PILLARS.cost_discipline.name,
|
|
1439
1460
|
severity: "info",
|
|
1440
1461
|
wasteUsd: 0,
|
|
1441
|
-
problem: sanitizeText(`Workflow and subagent runs cost about ${
|
|
1462
|
+
problem: sanitizeText(`Workflow and subagent runs cost about ${usd8(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
|
|
1442
1463
|
action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
|
|
1443
1464
|
basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
|
|
1444
1465
|
});
|
|
@@ -1511,20 +1532,20 @@ function computeWindowStats(report) {
|
|
|
1511
1532
|
}
|
|
1512
1533
|
const windows = [];
|
|
1513
1534
|
let windowStart = -Infinity;
|
|
1514
|
-
for (const [t,
|
|
1535
|
+
for (const [t, usd8] of buckets) {
|
|
1515
1536
|
if (t >= windowStart + WINDOW_BUCKETS) {
|
|
1516
1537
|
windows.push({ usd: 0, activeMinutes: 0 });
|
|
1517
1538
|
windowStart = t;
|
|
1518
1539
|
}
|
|
1519
1540
|
const w = windows[windows.length - 1];
|
|
1520
|
-
w.usd +=
|
|
1541
|
+
w.usd += usd8;
|
|
1521
1542
|
w.activeMinutes += BUCKET_MINUTES;
|
|
1522
1543
|
}
|
|
1523
1544
|
const firstT = buckets[0][0];
|
|
1524
1545
|
const weeks = /* @__PURE__ */ new Map();
|
|
1525
|
-
for (const [t,
|
|
1546
|
+
for (const [t, usd8] of buckets) {
|
|
1526
1547
|
const week = Math.floor((t - firstT) / WEEK_BUCKETS);
|
|
1527
|
-
weeks.set(week, (weeks.get(week) ?? 0) +
|
|
1548
|
+
weeks.set(week, (weeks.get(week) ?? 0) + usd8);
|
|
1528
1549
|
}
|
|
1529
1550
|
const byUsd = windows.slice().sort((a, b) => a.usd - b.usd);
|
|
1530
1551
|
const usdAsc = byUsd.map((w) => w.usd);
|
|
@@ -1567,22 +1588,22 @@ function burnClock(report, offsetMinutes = 0) {
|
|
|
1567
1588
|
const byDay = [0, 0, 0, 0, 0, 0, 0];
|
|
1568
1589
|
const byQuarter = [0, 0, 0, 0];
|
|
1569
1590
|
const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
|
|
1570
|
-
for (const [t,
|
|
1591
|
+
for (const [t, usd8] of merged) {
|
|
1571
1592
|
const d = new Date(t * 9e5 + offsetMinutes * 6e4);
|
|
1572
1593
|
const day2 = d.getUTCDay();
|
|
1573
1594
|
const quarter = Math.floor(d.getUTCHours() / 6);
|
|
1574
|
-
byDay[day2] +=
|
|
1575
|
-
byQuarter[quarter] +=
|
|
1576
|
-
slot[day2][quarter] +=
|
|
1595
|
+
byDay[day2] += usd8;
|
|
1596
|
+
byQuarter[quarter] += usd8;
|
|
1597
|
+
slot[day2][quarter] += usd8;
|
|
1577
1598
|
}
|
|
1578
1599
|
let topSlot = null;
|
|
1579
1600
|
let quietSlot = null;
|
|
1580
1601
|
for (let day2 = 0; day2 < 7; day2++) {
|
|
1581
1602
|
for (let quarter = 0; quarter < 4; quarter++) {
|
|
1582
|
-
const
|
|
1583
|
-
if (
|
|
1584
|
-
if (!topSlot ||
|
|
1585
|
-
if (!quietSlot ||
|
|
1603
|
+
const usd8 = slot[day2][quarter];
|
|
1604
|
+
if (usd8 <= 0) continue;
|
|
1605
|
+
if (!topSlot || usd8 > topSlot.usd) topSlot = { day: day2, quarter, usd: usd8 };
|
|
1606
|
+
if (!quietSlot || usd8 < quietSlot.usd) quietSlot = { day: day2, quarter, usd: usd8 };
|
|
1586
1607
|
}
|
|
1587
1608
|
}
|
|
1588
1609
|
return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
|
|
@@ -1753,7 +1774,20 @@ function stackOneLiner(stack) {
|
|
|
1753
1774
|
}
|
|
1754
1775
|
return `A ${joined} project.`;
|
|
1755
1776
|
}
|
|
1756
|
-
function
|
|
1777
|
+
function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy) {
|
|
1778
|
+
const re = REGENERATED_HEADING[categoryIndex];
|
|
1779
|
+
const wasReplaced = carried.replaced.some((h) => re.test(h));
|
|
1780
|
+
if (wasReplaced) {
|
|
1781
|
+
return {
|
|
1782
|
+
name: label,
|
|
1783
|
+
disposition: "replaced",
|
|
1784
|
+
why: `Replaced your existing ${label} section with the version derived from the project scan.`
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
if (hasContent) return { name: label, disposition: "filled", why: filledWhy };
|
|
1788
|
+
return { name: label, disposition: "placeholder", why: `${label} was left as a placeholder; no matching evidence was found.` };
|
|
1789
|
+
}
|
|
1790
|
+
function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
|
|
1757
1791
|
const { currentClaudeMd, project } = input;
|
|
1758
1792
|
const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
|
|
1759
1793
|
const recoverableLine = recoverable >= 1 ? ` - Your audit valued cache-miss exposure at ${usd(recoverable)}. Keeping this file small and stable is part of recovering it; the matching PLAYBOOK.md has the rest.` : " - Keeping this file small and stable keeps the cached prefix cheap to reuse each turn.";
|
|
@@ -1792,10 +1826,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1792
1826
|
const titleText = projectName ?? title ?? "Project name";
|
|
1793
1827
|
if (projectName) {
|
|
1794
1828
|
filled.push("Title");
|
|
1829
|
+
dispositions.push({ name: "Title", disposition: "filled", why: "Filled from the project's detected name." });
|
|
1795
1830
|
} else if (title) {
|
|
1796
1831
|
notes.push(`Carried across the project title from your CLAUDE.md: "${title}".`);
|
|
1832
|
+
dispositions.push({ name: "Title", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
|
|
1797
1833
|
} else {
|
|
1798
1834
|
notes.push("No project title was detectable, so the title is a placeholder.");
|
|
1835
|
+
dispositions.push({ name: "Title", disposition: "placeholder", why: "No project title was detectable." });
|
|
1799
1836
|
}
|
|
1800
1837
|
const projectDesc = project?.description?.trim() || null;
|
|
1801
1838
|
const synthesized = project ? stackOneLiner(project.stack) : null;
|
|
@@ -1808,14 +1845,24 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1808
1845
|
}
|
|
1809
1846
|
if (projectDesc) {
|
|
1810
1847
|
filled.push("Description");
|
|
1848
|
+
dispositions.push({ name: "Description", disposition: "filled", why: "Filled from the project's manifest description." });
|
|
1811
1849
|
} else if (synthesized) {
|
|
1812
1850
|
filled.push("Stack");
|
|
1851
|
+
dispositions.push({ name: "Description", disposition: "filled", why: "Filled with a one-line summary of the detected stack." });
|
|
1813
1852
|
} else if (intro) {
|
|
1814
1853
|
notes.push("Carried across your one-line project description.");
|
|
1854
|
+
dispositions.push({ name: "Description", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
|
|
1815
1855
|
} else if (introDropped) {
|
|
1816
1856
|
notes.push(
|
|
1817
1857
|
"Left your existing description out because it carried volatile markers (a date or status note) that would churn the cache."
|
|
1818
1858
|
);
|
|
1859
|
+
dispositions.push({
|
|
1860
|
+
name: "Description",
|
|
1861
|
+
disposition: "placeholder",
|
|
1862
|
+
why: "Your existing description carried volatile markers that would churn the cache, so it was left out."
|
|
1863
|
+
});
|
|
1864
|
+
} else {
|
|
1865
|
+
dispositions.push({ name: "Description", disposition: "placeholder", why: "No description was detectable." });
|
|
1819
1866
|
}
|
|
1820
1867
|
parts.push([`# ${titleText}`, "", descLine].join("\n"));
|
|
1821
1868
|
const allCommands = project?.commands ?? [];
|
|
@@ -1838,8 +1885,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1838
1885
|
}
|
|
1839
1886
|
parts.push(lines.join("\n"));
|
|
1840
1887
|
filled.push("Commands");
|
|
1888
|
+
dispositions.push(regenDisposition("Commands", 0, carried, true, "Filled from the project's manifest commands."));
|
|
1841
1889
|
} else {
|
|
1842
1890
|
stats.placeholders += 1;
|
|
1891
|
+
dispositions.push(regenDisposition("Commands", 0, carried, false, ""));
|
|
1843
1892
|
parts.push(
|
|
1844
1893
|
[
|
|
1845
1894
|
"## Commands",
|
|
@@ -1869,8 +1918,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1869
1918
|
}
|
|
1870
1919
|
parts.push(lines.join("\n"));
|
|
1871
1920
|
filled.push("Project structure");
|
|
1921
|
+
dispositions.push(regenDisposition("Project structure", 1, carried, true, "Filled from the project's detected directory layout."));
|
|
1872
1922
|
} else {
|
|
1873
1923
|
stats.placeholders += 1;
|
|
1924
|
+
dispositions.push(regenDisposition("Project structure", 1, carried, false, ""));
|
|
1874
1925
|
parts.push(
|
|
1875
1926
|
[
|
|
1876
1927
|
"## Project structure",
|
|
@@ -1892,8 +1943,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1892
1943
|
for (const s of codeStyle) lines.push(`- ${s}`);
|
|
1893
1944
|
parts.push(lines.join("\n"));
|
|
1894
1945
|
filled.push("Code style");
|
|
1946
|
+
dispositions.push(regenDisposition("Code style", 2, carried, true, "Filled from the project's detected style conventions."));
|
|
1895
1947
|
} else {
|
|
1896
1948
|
stats.placeholders += 1;
|
|
1949
|
+
dispositions.push(regenDisposition("Code style", 2, carried, false, ""));
|
|
1897
1950
|
parts.push(
|
|
1898
1951
|
[
|
|
1899
1952
|
"## Code style",
|
|
@@ -1915,8 +1968,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1915
1968
|
for (const t of testing) lines.push(`- ${t}`);
|
|
1916
1969
|
parts.push(lines.join("\n"));
|
|
1917
1970
|
filled.push("Testing");
|
|
1971
|
+
dispositions.push(regenDisposition("Testing", 3, carried, true, "Filled from the project's detected test setup."));
|
|
1918
1972
|
} else {
|
|
1919
1973
|
stats.placeholders += 1;
|
|
1974
|
+
dispositions.push(regenDisposition("Testing", 3, carried, false, ""));
|
|
1920
1975
|
parts.push(
|
|
1921
1976
|
[
|
|
1922
1977
|
"## Testing",
|
|
@@ -1932,8 +1987,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1932
1987
|
}
|
|
1933
1988
|
if (carried.workflow) {
|
|
1934
1989
|
parts.push(["## Workflow", "", carried.workflow].join("\n"));
|
|
1990
|
+
dispositions.push({ name: "Workflow", disposition: "carried", why: "Carried across your Workflow section from the existing CLAUDE.md." });
|
|
1935
1991
|
} else {
|
|
1936
1992
|
stats.placeholders += 1;
|
|
1993
|
+
dispositions.push({ name: "Workflow", disposition: "placeholder", why: "No Workflow section was found, so this is a placeholder." });
|
|
1937
1994
|
parts.push(
|
|
1938
1995
|
[
|
|
1939
1996
|
"## Workflow",
|
|
@@ -1949,8 +2006,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1949
2006
|
}
|
|
1950
2007
|
if (carried.architecture) {
|
|
1951
2008
|
parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
|
|
2009
|
+
dispositions.push({ name: "Architecture and gotchas", disposition: "carried", why: "Carried across your Architecture and gotchas section from the existing CLAUDE.md." });
|
|
1952
2010
|
} else {
|
|
1953
2011
|
stats.placeholders += 1;
|
|
2012
|
+
dispositions.push({ name: "Architecture and gotchas", disposition: "placeholder", why: "No Architecture and gotchas section was found, so this is a placeholder to grow over time." });
|
|
1954
2013
|
parts.push(
|
|
1955
2014
|
[
|
|
1956
2015
|
"## Architecture and gotchas",
|
|
@@ -1968,6 +2027,7 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1968
2027
|
}
|
|
1969
2028
|
for (const section of carried.other) {
|
|
1970
2029
|
parts.push([`## ${section.heading}`, "", section.body].join("\n"));
|
|
2030
|
+
dispositions.push({ name: section.heading, disposition: "carried", why: "Carried across from your existing CLAUDE.md under its own heading." });
|
|
1971
2031
|
}
|
|
1972
2032
|
const envVars = (project?.envVars ?? []).map((v) => v.trim()).filter((v) => v.length > 0);
|
|
1973
2033
|
if (envVars.length > 0) {
|
|
@@ -1980,8 +2040,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
1980
2040
|
].join("\n")
|
|
1981
2041
|
);
|
|
1982
2042
|
filled.push("Environment");
|
|
2043
|
+
dispositions.push(regenDisposition("Environment", 4, carried, true, "Filled from the project's detected environment variable names."));
|
|
1983
2044
|
} else {
|
|
1984
2045
|
stats.placeholders += 1;
|
|
2046
|
+
dispositions.push(regenDisposition("Environment", 4, carried, false, ""));
|
|
1985
2047
|
parts.push(
|
|
1986
2048
|
[
|
|
1987
2049
|
"## Environment",
|
|
@@ -2028,6 +2090,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
|
|
|
2028
2090
|
notes.push(
|
|
2029
2091
|
`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.`
|
|
2030
2092
|
);
|
|
2093
|
+
for (const heading of carried.droppedVolatile) {
|
|
2094
|
+
dispositions.push({
|
|
2095
|
+
name: heading,
|
|
2096
|
+
disposition: "dropped",
|
|
2097
|
+
why: "Status-style sections churn on every update and bust the prompt cache."
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2031
2100
|
}
|
|
2032
2101
|
if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
|
|
2033
2102
|
notes.push(
|
|
@@ -2091,6 +2160,10 @@ function renderCacheTable(report) {
|
|
|
2091
2160
|
`${tail.length} smaller project${tail.length === 1 ? "" : "s"} account for the remaining ${usd(tailUsd)}.`
|
|
2092
2161
|
);
|
|
2093
2162
|
}
|
|
2163
|
+
lines.push("");
|
|
2164
|
+
lines.push(
|
|
2165
|
+
"A high cache hit rate next to a real dollar figure is not a contradiction: this total also prices new cache-creation (write) tokens against the cache-read rate, not misses alone, so a project that keeps writing fresh content into the cache every turn can carry a big number even at a high hit rate. Treat it as an upper bound, not a guarantee."
|
|
2166
|
+
);
|
|
2094
2167
|
return lines.join("\n");
|
|
2095
2168
|
}
|
|
2096
2169
|
function practices(report, scores, recoverable) {
|
|
@@ -2165,7 +2238,16 @@ function tokenDiscipline(report) {
|
|
|
2165
2238
|
"- Set `ANTHROPIC_MODEL` and `CLAUDE_CODE_EFFORT_LEVEL` in your shell profile so every session starts on the right model and effort without a per-session step."
|
|
2166
2239
|
].join("\n");
|
|
2167
2240
|
}
|
|
2168
|
-
function
|
|
2241
|
+
function claudeMdReceiptLine(claudeMdTokens) {
|
|
2242
|
+
const { before, after } = claudeMdTokens;
|
|
2243
|
+
if (before == null || before === after) return null;
|
|
2244
|
+
const delta = after - before;
|
|
2245
|
+
const grew = delta > 0;
|
|
2246
|
+
const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
|
|
2247
|
+
const tail = grew ? "It is re-read on every turn, so the larger file costs a little more every time too." : "It is re-read on every turn, so that saving repeats every session.";
|
|
2248
|
+
return `Your optimized CLAUDE.md goes from an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()}${pct2}. ${tail}`;
|
|
2249
|
+
}
|
|
2250
|
+
function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
|
|
2169
2251
|
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
|
|
2170
2252
|
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
2171
2253
|
const parts = [];
|
|
@@ -2181,6 +2263,8 @@ function buildPlaybook(report, fixes, scores, recoverable, project) {
|
|
|
2181
2263
|
"This is the ranked plan from your audit. The priority fixes are ordered by the dollars they recover; the setup warnings follow. CostClaw generates the plan; working through it is what recovers the spend."
|
|
2182
2264
|
].join("\n")
|
|
2183
2265
|
);
|
|
2266
|
+
const receipt = claudeMdReceiptLine(claudeMdTokens);
|
|
2267
|
+
if (receipt) parts.push(receipt);
|
|
2184
2268
|
dollarFixes.forEach((fix, i) => {
|
|
2185
2269
|
parts.push(renderDollarFix(fix, i + 1));
|
|
2186
2270
|
if (fix.id === "cache_recovery") {
|
|
@@ -2376,22 +2460,39 @@ function optimize(input) {
|
|
|
2376
2460
|
const notes = [];
|
|
2377
2461
|
const stats = { placeholders: 0 };
|
|
2378
2462
|
const carried = carriedSections(input.currentClaudeMd);
|
|
2379
|
-
const
|
|
2380
|
-
const
|
|
2463
|
+
const dispositions = [];
|
|
2464
|
+
const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried, dispositions);
|
|
2465
|
+
const claudeMdTokens = {
|
|
2466
|
+
before: input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null,
|
|
2467
|
+
after: Math.round(optimizedClaudeMd.trim().length / 4)
|
|
2468
|
+
};
|
|
2469
|
+
const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
|
|
2381
2470
|
const settingsJson = buildSettings(input.project);
|
|
2382
2471
|
const harnessPrompt = buildHarnessPrompt(input, carried);
|
|
2383
2472
|
const cleanNotes = notes.map((n) => clean(n));
|
|
2384
|
-
|
|
2473
|
+
const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
|
|
2474
|
+
if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
|
|
2385
2475
|
return {
|
|
2386
2476
|
optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
|
|
2387
2477
|
playbook: sanitizeText(playbook),
|
|
2388
2478
|
settingsJson: sanitizeText(settingsJson),
|
|
2389
2479
|
harnessPrompt: sanitizeText(harnessPrompt),
|
|
2390
2480
|
notes: cleanNotes.map(sanitizeText),
|
|
2391
|
-
placeholdersRemaining: stats.placeholders
|
|
2481
|
+
placeholdersRemaining: stats.placeholders,
|
|
2482
|
+
claudeMdTokens,
|
|
2483
|
+
sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
|
|
2392
2484
|
};
|
|
2393
2485
|
}
|
|
2394
|
-
return {
|
|
2486
|
+
return {
|
|
2487
|
+
optimizedClaudeMd,
|
|
2488
|
+
playbook,
|
|
2489
|
+
settingsJson,
|
|
2490
|
+
harnessPrompt,
|
|
2491
|
+
notes: cleanNotes,
|
|
2492
|
+
placeholdersRemaining: stats.placeholders,
|
|
2493
|
+
claudeMdTokens,
|
|
2494
|
+
sectionDispositions: cleanDispositions
|
|
2495
|
+
};
|
|
2395
2496
|
}
|
|
2396
2497
|
|
|
2397
2498
|
// ../../packages/engine/src/audit.ts
|
|
@@ -2420,7 +2521,7 @@ function toUsageMetrics(report) {
|
|
|
2420
2521
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
2421
2522
|
}));
|
|
2422
2523
|
const modelBreakdown = {};
|
|
2423
|
-
for (const [model,
|
|
2524
|
+
for (const [model, usd8] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd8);
|
|
2424
2525
|
return {
|
|
2425
2526
|
spendUsd: round2(s.cost_usd),
|
|
2426
2527
|
cacheSavingsUsd: round2(s.cache_savings_usd),
|
|
@@ -2630,7 +2731,20 @@ var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
|
2630
2731
|
import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
2631
2732
|
import { join as join4, resolve } from "path";
|
|
2632
2733
|
import { homedir as homedir3 } from "os";
|
|
2734
|
+
|
|
2735
|
+
// src/open.ts
|
|
2633
2736
|
import { spawn } from "child_process";
|
|
2737
|
+
function openInBrowser(target) {
|
|
2738
|
+
try {
|
|
2739
|
+
const platform = process.platform;
|
|
2740
|
+
const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
2741
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
2742
|
+
child.on("error", () => {
|
|
2743
|
+
});
|
|
2744
|
+
child.unref();
|
|
2745
|
+
} catch {
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2634
2748
|
|
|
2635
2749
|
// src/read-sessions.ts
|
|
2636
2750
|
import { readdir } from "fs/promises";
|
|
@@ -3477,17 +3591,6 @@ async function resolvePlan(configDir, flag) {
|
|
|
3477
3591
|
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
3478
3592
|
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
3479
3593
|
var SNAPSHOT_KEEP = 50;
|
|
3480
|
-
function openInBrowser(target) {
|
|
3481
|
-
try {
|
|
3482
|
-
const platform = process.platform;
|
|
3483
|
-
const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
3484
|
-
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
3485
|
-
child.on("error", () => {
|
|
3486
|
-
});
|
|
3487
|
-
child.unref();
|
|
3488
|
-
} catch {
|
|
3489
|
-
}
|
|
3490
|
-
}
|
|
3491
3594
|
async function loadAuditInputs(opts) {
|
|
3492
3595
|
const root = opts.path || defaultProjectsPath();
|
|
3493
3596
|
const { logs, skipped } = await readSessions(root);
|
|
@@ -3573,6 +3676,412 @@ import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat a
|
|
|
3573
3676
|
import { join as join6, dirname } from "path";
|
|
3574
3677
|
import { homedir as homedir4 } from "os";
|
|
3575
3678
|
|
|
3679
|
+
// src/optimize-dashboard.ts
|
|
3680
|
+
function usd5(n) {
|
|
3681
|
+
const rounded = Math.round(n * 100) / 100;
|
|
3682
|
+
const neg = rounded < 0;
|
|
3683
|
+
const fixed = Math.abs(rounded).toFixed(2);
|
|
3684
|
+
const dot = fixed.indexOf(".");
|
|
3685
|
+
const whole = fixed.slice(0, dot);
|
|
3686
|
+
const cents = fixed.slice(dot);
|
|
3687
|
+
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3688
|
+
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
3689
|
+
}
|
|
3690
|
+
function fmtTokens(n) {
|
|
3691
|
+
const rounded = Math.round(n);
|
|
3692
|
+
const neg = rounded < 0;
|
|
3693
|
+
const grouped = Math.abs(rounded).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3694
|
+
return `${neg ? "-" : ""}${grouped}`;
|
|
3695
|
+
}
|
|
3696
|
+
function approxTokens(n) {
|
|
3697
|
+
return `~${fmtTokens(n)}`;
|
|
3698
|
+
}
|
|
3699
|
+
function plural2(n, noun) {
|
|
3700
|
+
return n === 1 ? noun : `${noun}s`;
|
|
3701
|
+
}
|
|
3702
|
+
var STYLE2 = `
|
|
3703
|
+
:root{
|
|
3704
|
+
--bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
|
|
3705
|
+
--accent:#8a5a2b; --good:#2f6f4f; --warn:#8a6a1f; --bad:#8a3a2b;
|
|
3706
|
+
--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
|
3707
|
+
--sans:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
|
|
3708
|
+
}
|
|
3709
|
+
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
|
|
3710
|
+
--bg:#15151a; --panel:#1d1d23; --ink:#f0eeea; --ink2:#a8a49c; --line:#33323a;
|
|
3711
|
+
--accent:#d9a05b; --good:#6fbf8f; --warn:#d9b95b; --bad:#e08a72;
|
|
3712
|
+
}}
|
|
3713
|
+
*{box-sizing:border-box}
|
|
3714
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);
|
|
3715
|
+
-webkit-font-smoothing:antialiased}
|
|
3716
|
+
.wrap{max-width:1080px;margin:0 auto;padding:40px 24px 96px}
|
|
3717
|
+
header{border-bottom:1px solid var(--line);padding-bottom:24px;margin-bottom:32px}
|
|
3718
|
+
.kicker{font-size:.72rem;letter-spacing:.13em;text-transform:uppercase;color:var(--ink2);margin:0 0 10px}
|
|
3719
|
+
h1{font-size:clamp(1.6rem,3.6vw,2.3rem);margin:0 0 6px;letter-spacing:-.02em;font-weight:750}
|
|
3720
|
+
.sub{color:var(--ink2);margin:0;font-size:.95rem}
|
|
3721
|
+
h2{font-size:1.06rem;letter-spacing:-.01em;margin:40px 0 14px;font-weight:700}
|
|
3722
|
+
h2 .n{color:var(--ink2);font-weight:400;font-size:.85rem;margin-left:8px}
|
|
3723
|
+
.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px 22px}
|
|
3724
|
+
.grid{display:grid;gap:16px}
|
|
3725
|
+
.g3{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
|
|
3726
|
+
.g2{grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
|
|
3727
|
+
.stat{font-variant-numeric:tabular-nums}
|
|
3728
|
+
.stat .v{font-size:1.65rem;font-weight:750;letter-spacing:-.02em;display:block}
|
|
3729
|
+
.stat .l{color:var(--ink2);font-size:.8rem;text-transform:uppercase;letter-spacing:.07em}
|
|
3730
|
+
.stat .d{font-size:.83rem;margin-top:6px;color:var(--ink2)}
|
|
3731
|
+
.win{color:var(--good);font-weight:650}
|
|
3732
|
+
.bar{height:26px;border-radius:6px;background:linear-gradient(90deg,var(--accent) 0%,var(--accent) 100%);
|
|
3733
|
+
position:relative;overflow:hidden}
|
|
3734
|
+
.bar .cut{position:absolute;inset:0 0 0 95.6%;background:var(--good);opacity:.85}
|
|
3735
|
+
.barlabels{display:flex;justify-content:space-between;font-size:.78rem;color:var(--ink2);margin-top:6px;
|
|
3736
|
+
font-variant-numeric:tabular-nums}
|
|
3737
|
+
table{width:100%;border-collapse:collapse;font-size:.9rem;font-variant-numeric:tabular-nums}
|
|
3738
|
+
th,td{text-align:left;padding:9px 10px;border-bottom:1px solid var(--line)}
|
|
3739
|
+
th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);font-weight:600}
|
|
3740
|
+
td.num,th.num{text-align:right}
|
|
3741
|
+
.scroll{overflow-x:auto}
|
|
3742
|
+
.fix{border-left:3px solid var(--accent);padding:2px 0 2px 16px;margin:0 0 22px}
|
|
3743
|
+
.fix h3{margin:0 0 4px;font-size:1rem}
|
|
3744
|
+
.fix .amt{font-family:var(--mono);color:var(--accent);font-weight:700}
|
|
3745
|
+
.fix p{margin:8px 0 0;font-size:.93rem}
|
|
3746
|
+
.fix .do{background:color-mix(in srgb,var(--accent) 8%,transparent);border-radius:8px;padding:11px 13px;margin-top:10px}
|
|
3747
|
+
ul.warn{list-style:none;padding:0;margin:0}
|
|
3748
|
+
ul.warn li{padding:10px 0;border-bottom:1px solid var(--line);font-size:.92rem}
|
|
3749
|
+
ul.warn li:last-child{border-bottom:0}
|
|
3750
|
+
ul.warn b{font-weight:650}
|
|
3751
|
+
.pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
|
|
3752
|
+
color:var(--ink2);margin-left:8px;vertical-align:1px}
|
|
3753
|
+
.files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
|
|
3754
|
+
.file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
|
|
3755
|
+
display:flex;flex-direction:column;gap:6px}
|
|
3756
|
+
.file .nm{font-family:var(--mono);font-size:.86rem;font-weight:650;color:var(--accent)}
|
|
3757
|
+
.file .ds{font-size:.84rem;color:var(--ink2)}
|
|
3758
|
+
.file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
|
|
3759
|
+
align-self:flex-start;padding-bottom:1px}
|
|
3760
|
+
.file a:hover{border-color:var(--accent)}
|
|
3761
|
+
.cta{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--good);
|
|
3762
|
+
border-radius:10px;padding:18px 20px}
|
|
3763
|
+
code.cmd{display:block;font-family:var(--mono);font-size:.86rem;background:color-mix(in srgb,var(--ink) 6%,transparent);
|
|
3764
|
+
padding:11px 13px;border-radius:7px;margin-top:10px;overflow-x:auto;white-space:pre}
|
|
3765
|
+
.note{font-size:.82rem;color:var(--ink2);margin-top:10px}
|
|
3766
|
+
footer{margin-top:56px;padding-top:20px;border-top:1px solid var(--line);color:var(--ink2);font-size:.82rem}
|
|
3767
|
+
details summary{cursor:pointer;font-size:.88rem;color:var(--ink2)}
|
|
3768
|
+
details[open] summary{margin-bottom:10px}
|
|
3769
|
+
.cols{columns:2;column-gap:28px;font-size:.86rem;color:var(--ink2)}
|
|
3770
|
+
@media(max-width:640px){.cols{columns:1}}
|
|
3771
|
+
.tabs input{position:absolute;opacity:0;pointer-events:none}
|
|
3772
|
+
.tabs label{display:inline-block;font-size:.85rem;padding:7px 13px;border:1px solid var(--line);
|
|
3773
|
+
border-radius:7px;margin:0 6px 14px 0;cursor:pointer;color:var(--ink2);user-select:none}
|
|
3774
|
+
.tabs label:hover{border-color:var(--accent)}
|
|
3775
|
+
.tabs input:checked + label{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
|
|
3776
|
+
.tabpane{display:none}
|
|
3777
|
+
#t-sections:checked ~ .tabpane[data-for="t-sections"],
|
|
3778
|
+
#t-diff:checked ~ .tabpane[data-for="t-diff"],
|
|
3779
|
+
#t-side:checked ~ .tabpane[data-for="t-side"]{display:block}
|
|
3780
|
+
.tag{font-family:var(--mono);font-size:.72rem;padding:2px 7px;border-radius:5px;white-space:nowrap}
|
|
3781
|
+
.tag.keep{background:color-mix(in srgb,var(--ink2) 16%,transparent);color:var(--ink)}
|
|
3782
|
+
.tag.fill{background:color-mix(in srgb,var(--good) 20%,transparent);color:var(--good)}
|
|
3783
|
+
.tag.repl{background:color-mix(in srgb,var(--warn) 22%,transparent);color:var(--warn)}
|
|
3784
|
+
.tag.drop{background:color-mix(in srgb,var(--bad) 18%,transparent);color:var(--bad)}
|
|
3785
|
+
.tag.hole{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent)}
|
|
3786
|
+
pre.diff,pre.src{font-family:var(--mono);font-size:.8rem;line-height:1.5;overflow-x:auto;
|
|
3787
|
+
background:color-mix(in srgb,var(--ink) 5%,transparent);padding:14px 16px;border-radius:8px;margin:0}
|
|
3788
|
+
pre.diff .add{color:var(--good);display:block}
|
|
3789
|
+
pre.diff .del{color:var(--bad);display:block}
|
|
3790
|
+
pre.diff .ctx{color:var(--ink2);display:block}
|
|
3791
|
+
.paneh{font-size:.8rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);
|
|
3792
|
+
margin:0 0 8px;font-weight:600}
|
|
3793
|
+
`;
|
|
3794
|
+
var TAG_META = {
|
|
3795
|
+
carried: { cls: "keep", label: "carried" },
|
|
3796
|
+
filled: { cls: "fill", label: "filled" },
|
|
3797
|
+
replaced: { cls: "repl", label: "replaced" },
|
|
3798
|
+
dropped: { cls: "drop", label: "left out" },
|
|
3799
|
+
placeholder: { cls: "hole", label: "placeholder" }
|
|
3800
|
+
};
|
|
3801
|
+
function renderSectionsTable(sections) {
|
|
3802
|
+
const rows = sections.map((s) => {
|
|
3803
|
+
const meta = TAG_META[s.disposition];
|
|
3804
|
+
return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
|
|
3805
|
+
}).join("");
|
|
3806
|
+
return `<p class="note" style="margin-top:0">Every section of your file and what this run did with it. Nothing was deleted silently: dropped sections are named with a reason.</p><div class="scroll"><table><thead><tr><th>Section</th><th>What happened</th><th>Why</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
|
3807
|
+
}
|
|
3808
|
+
var DIFF_LCS_LIMIT = 3e3;
|
|
3809
|
+
function diffLines(before, after) {
|
|
3810
|
+
const a = before.split("\n");
|
|
3811
|
+
const b = after.split("\n");
|
|
3812
|
+
const n = a.length;
|
|
3813
|
+
const m = b.length;
|
|
3814
|
+
if (n > DIFF_LCS_LIMIT || m > DIFF_LCS_LIMIT) {
|
|
3815
|
+
const ops2 = [];
|
|
3816
|
+
for (const line of a) ops2.push({ type: "del", text: line });
|
|
3817
|
+
for (const line of b) ops2.push({ type: "add", text: line });
|
|
3818
|
+
return ops2;
|
|
3819
|
+
}
|
|
3820
|
+
const width = m + 1;
|
|
3821
|
+
const dp = new Int32Array((n + 1) * width);
|
|
3822
|
+
for (let i2 = n - 1; i2 >= 0; i2--) {
|
|
3823
|
+
for (let j2 = m - 1; j2 >= 0; j2--) {
|
|
3824
|
+
const ai = a[i2];
|
|
3825
|
+
const bj = b[j2];
|
|
3826
|
+
dp[i2 * width + j2] = ai === bj ? dp[(i2 + 1) * width + (j2 + 1)] + 1 : Math.max(dp[(i2 + 1) * width + j2], dp[i2 * width + (j2 + 1)]);
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
const ops = [];
|
|
3830
|
+
let i = 0;
|
|
3831
|
+
let j = 0;
|
|
3832
|
+
while (i < n && j < m) {
|
|
3833
|
+
if (a[i] === b[j]) {
|
|
3834
|
+
ops.push({ type: "ctx", text: a[i] });
|
|
3835
|
+
i++;
|
|
3836
|
+
j++;
|
|
3837
|
+
} else if (dp[(i + 1) * width + j] >= dp[i * width + (j + 1)]) {
|
|
3838
|
+
ops.push({ type: "del", text: a[i] });
|
|
3839
|
+
i++;
|
|
3840
|
+
} else {
|
|
3841
|
+
ops.push({ type: "add", text: b[j] });
|
|
3842
|
+
j++;
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
while (i < n) {
|
|
3846
|
+
ops.push({ type: "del", text: a[i] });
|
|
3847
|
+
i++;
|
|
3848
|
+
}
|
|
3849
|
+
while (j < m) {
|
|
3850
|
+
ops.push({ type: "add", text: b[j] });
|
|
3851
|
+
j++;
|
|
3852
|
+
}
|
|
3853
|
+
return ops;
|
|
3854
|
+
}
|
|
3855
|
+
var DIFF_CONTEXT = 2;
|
|
3856
|
+
var DIFF_MAX_LINES = 4e3;
|
|
3857
|
+
function buildHunks(ops) {
|
|
3858
|
+
const keep = new Array(ops.length).fill(false);
|
|
3859
|
+
for (let i = 0; i < ops.length; i++) {
|
|
3860
|
+
if (ops[i].type !== "ctx") {
|
|
3861
|
+
for (let j = Math.max(0, i - DIFF_CONTEXT); j <= Math.min(ops.length - 1, i + DIFF_CONTEXT); j++) {
|
|
3862
|
+
keep[j] = true;
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
}
|
|
3866
|
+
const out = [];
|
|
3867
|
+
let lastKept = -2;
|
|
3868
|
+
for (let i = 0; i < ops.length; i++) {
|
|
3869
|
+
if (!keep[i]) continue;
|
|
3870
|
+
if (out.length > 0 && i - lastKept > 1) out.push({ type: "ctx", text: "" });
|
|
3871
|
+
out.push(ops[i]);
|
|
3872
|
+
lastKept = i;
|
|
3873
|
+
}
|
|
3874
|
+
return out;
|
|
3875
|
+
}
|
|
3876
|
+
function renderDiffTab(before, after) {
|
|
3877
|
+
const intro = `<p class="note" style="margin-top:0">Only the regions that differ, with context. A large file is not worth printing twice.</p>`;
|
|
3878
|
+
if (before === null) {
|
|
3879
|
+
return intro + `<p class="note">No existing CLAUDE.md was found, so there is nothing to compare. See Side by side for the new file.</p>`;
|
|
3880
|
+
}
|
|
3881
|
+
const hunks = buildHunks(diffLines(before, after));
|
|
3882
|
+
const truncated = hunks.length > DIFF_MAX_LINES;
|
|
3883
|
+
const shown = truncated ? hunks.slice(0, DIFF_MAX_LINES) : hunks;
|
|
3884
|
+
const body = shown.map((op) => {
|
|
3885
|
+
if (op.type === "ctx") return `<span class="ctx">${esc(op.text)}</span>`;
|
|
3886
|
+
const prefix = op.type === "add" ? "+ " : "- ";
|
|
3887
|
+
return `<span class="${op.type}">${esc(prefix + op.text)}</span>`;
|
|
3888
|
+
}).join("\n");
|
|
3889
|
+
const note = truncated ? `<p class="note">Diff truncated at ${DIFF_MAX_LINES} lines; open the file for the rest.</p>` : "";
|
|
3890
|
+
return `${intro}<pre class="diff">${body}</pre>${note}`;
|
|
3891
|
+
}
|
|
3892
|
+
var SIDE_PANE_CHAR_CAP = 2e4;
|
|
3893
|
+
function renderPane(text2) {
|
|
3894
|
+
const truncated = text2.length > SIDE_PANE_CHAR_CAP;
|
|
3895
|
+
const shown = truncated ? text2.slice(0, SIDE_PANE_CHAR_CAP) : text2;
|
|
3896
|
+
const note = truncated ? `<p class="note">Truncated; open the file for the rest.</p>` : "";
|
|
3897
|
+
return `<pre class="src">${esc(shown)}</pre>${note}`;
|
|
3898
|
+
}
|
|
3899
|
+
function renderSideBySideTab(before, after, tokens) {
|
|
3900
|
+
const afterCol = `<p class="paneh">Optimized <span class="win" style="font-weight:600">${esc(approxTokens(tokens.after))} tokens</span></p>` + renderPane(after);
|
|
3901
|
+
const beforeCol = before === null ? `<p class="paneh">Original</p><p class="note" style="margin-top:0">No existing CLAUDE.md.</p>` : `<p class="paneh">Original <span style="color:var(--ink2);font-weight:400">${esc(approxTokens(tokens.before))} tokens</span></p>` + renderPane(before);
|
|
3902
|
+
return `<div class="grid g2" style="gap:14px"><div>${beforeCol}</div><div>${afterCol}</div></div>`;
|
|
3903
|
+
}
|
|
3904
|
+
function renderComparisonTabs(input) {
|
|
3905
|
+
return `<div class="tabs"><input type="radio" name="cmp" id="t-sections" checked><label for="t-sections">By section</label><input type="radio" name="cmp" id="t-diff"><label for="t-diff">Line changes</label><input type="radio" name="cmp" id="t-side"><label for="t-side">Side by side</label><div class="tabpane" data-for="t-sections">${renderSectionsTable(input.sectionDispositions)}</div><div class="tabpane" data-for="t-diff">${renderDiffTab(input.currentClaudeMd, input.optimizedClaudeMd)}</div><div class="tabpane" data-for="t-side">${renderSideBySideTab(input.currentClaudeMd, input.optimizedClaudeMd, input.claudeMdTokens)}</div></div>`;
|
|
3906
|
+
}
|
|
3907
|
+
function countLines(s) {
|
|
3908
|
+
return s.length === 0 ? 0 : s.split("\n").length;
|
|
3909
|
+
}
|
|
3910
|
+
function renderTokenStat(input) {
|
|
3911
|
+
const { before, after } = input.claudeMdTokens;
|
|
3912
|
+
if (before === null) {
|
|
3913
|
+
return `<div class="stat"><span class="l">CLAUDE.md, every turn</span><span class="v">${esc(approxTokens(after))} tokens</span><span class="d">No existing CLAUDE.md was found, so this is a new file. It is re-read on every turn of every session, so its size sets a fixed cost per turn.</span></div>`;
|
|
3914
|
+
}
|
|
3915
|
+
const delta = after - before;
|
|
3916
|
+
const saved = delta < 0;
|
|
3917
|
+
const pct2 = before > 0 ? delta / before * 100 : 0;
|
|
3918
|
+
const deltaText = `${delta >= 0 ? "+" : ""}${fmtTokens(delta)} tokens`;
|
|
3919
|
+
const pctText = `${pct2 >= 0 ? "+" : ""}${pct2.toFixed(1)}%`;
|
|
3920
|
+
return `<div class="stat"><span class="l">CLAUDE.md, every turn</span><span class="v${saved ? " win" : ""}">${esc(deltaText)}</span><span class="d">${esc(approxTokens(before))} → ${esc(approxTokens(after))} tokens (${esc(pctText)}). This file is re-read on every turn of every session, so the ${saved ? "saving" : "change"} repeats.</span></div>`;
|
|
3921
|
+
}
|
|
3922
|
+
function renderSectionsStat(sections) {
|
|
3923
|
+
const counts = { carried: 0, filled: 0, replaced: 0, dropped: 0, placeholder: 0 };
|
|
3924
|
+
for (const s of sections) counts[s.disposition]++;
|
|
3925
|
+
const total = sections.length;
|
|
3926
|
+
const headline = counts.carried > 0 ? `${counts.carried} carried` : `${total} ${plural2(total, "section")}`;
|
|
3927
|
+
const rest = [];
|
|
3928
|
+
if (counts.replaced > 0) rest.push(`${counts.replaced} replaced from the scan`);
|
|
3929
|
+
if (counts.dropped > 0) rest.push(`${counts.dropped} volatile ${plural2(counts.dropped, "section")} dropped`);
|
|
3930
|
+
if (counts.filled > 0) rest.push(`${counts.filled} filled from your project`);
|
|
3931
|
+
if (counts.placeholder > 0) rest.push(`${counts.placeholder} left as ${counts.placeholder === 1 ? "a placeholder" : "placeholders"}`);
|
|
3932
|
+
const restText = rest.length > 0 ? rest.join(", ") + "." : "Nothing else to report.";
|
|
3933
|
+
return `<div class="stat"><span class="l">Sections handled</span><span class="v">${esc(headline)}</span><span class="d">${esc(restText)}</span></div>`;
|
|
3934
|
+
}
|
|
3935
|
+
function renderRecoverableStat(input) {
|
|
3936
|
+
const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
|
|
3937
|
+
return `<div class="stat"><span class="l">Recoverable usage</span><span class="v">${esc(pct2)}</span><span class="d">of analyzed usage, about ${esc(usd5(input.headlineWasteUsd))} at API rates. On a subscription that is rate-limit headroom, not money back.</span></div>`;
|
|
3938
|
+
}
|
|
3939
|
+
function renderReceipt(input) {
|
|
3940
|
+
const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
|
|
3941
|
+
const { before, after } = input.claudeMdTokens;
|
|
3942
|
+
let bar2 = "";
|
|
3943
|
+
if (before !== null && after < before) {
|
|
3944
|
+
const cutPct = Math.max(0, Math.min(100, after / before * 100));
|
|
3945
|
+
const savedTokens = before - after;
|
|
3946
|
+
bar2 = `<div style="margin-top:22px"><div class="bar"><div class="cut" style="inset:0 0 0 ${cutPct.toFixed(1)}%"></div></div><div class="barlabels"><span>optimized ${esc(approxTokens(after))} tokens</span><span>saved ${esc(fmtTokens(savedTokens))}</span></div></div>`;
|
|
3947
|
+
const lineDelta = countLines(input.optimizedClaudeMd) - countLines(input.currentClaudeMd ?? "");
|
|
3948
|
+
if (lineDelta !== 0) {
|
|
3949
|
+
bar2 += `<p class="note">Line count ${lineDelta > 0 ? "went up" : "went down"} by ${Math.abs(lineDelta)} while tokens went down by ${esc(fmtTokens(savedTokens))}. Tokens are what the cache charges for, so tokens are what is reported here.</p>`;
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
return `<div class="panel">${stats}${bar2}</div>`;
|
|
3953
|
+
}
|
|
3954
|
+
var CACHE_TABLE_FLOOR2 = 1;
|
|
3955
|
+
var CACHE_TABLE_CAP2 = 10;
|
|
3956
|
+
function renderCacheTable2(report) {
|
|
3957
|
+
const all = cacheMissByProject(report);
|
|
3958
|
+
const shown = all.filter((r) => r.usd >= CACHE_TABLE_FLOOR2).slice(0, CACHE_TABLE_CAP2);
|
|
3959
|
+
if (shown.length === 0) return "";
|
|
3960
|
+
const shownSlugs = new Set(shown.map((r) => r.slug));
|
|
3961
|
+
const tail = all.filter((r) => !shownSlugs.has(r.slug));
|
|
3962
|
+
const rows = shown.map(
|
|
3963
|
+
(r) => `<tr><td>${esc(r.slug)}</td><td class="num">${esc(usd5(r.usd))}</td><td class="num">${Math.round(r.cacheHitRate * 100)}%</td><td class="num">${r.sessionsCount}</td></tr>`
|
|
3964
|
+
).join("");
|
|
3965
|
+
let tailRow = "";
|
|
3966
|
+
if (tail.length > 0) {
|
|
3967
|
+
const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
|
|
3968
|
+
tailRow = `<tr><td colspan="4" style="color:var(--ink2)">${tail.length} smaller ${plural2(tail.length, "project")} account${tail.length === 1 ? "s" : ""} for the remaining ${esc(usd5(tailUsd))}.</td></tr>`;
|
|
3969
|
+
}
|
|
3970
|
+
return `<h4 style="margin:20px 0 8px;font-size:.9rem">Where that money is</h4><div class="scroll"><table><thead><tr><th>Project</th><th class="num">Recoverable</th><th class="num">Cache hit</th><th class="num">Main sessions</th></tr></thead><tbody>${rows}${tailRow}</tbody></table></div><p class="note"><b>Why a high hit rate can still leave money on the table:</b> the exposure counts cache writes, not just misses. A project can read its prefix from cache almost every turn and still rebuild that prefix often. This figure is an upper bound on what tighter session starts could recover.</p>`;
|
|
3971
|
+
}
|
|
3972
|
+
function renderFixes(fixes, report) {
|
|
3973
|
+
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
3974
|
+
if (dollarFixes.length === 0) return `<p class="note">No directly recoverable dollars found.</p>`;
|
|
3975
|
+
return dollarFixes.map((f, i) => {
|
|
3976
|
+
const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
|
|
3977
|
+
return `<div class="fix"><h3>${i + 1}. ${esc(f.title)} <span class="amt">${esc(usd5(f.wasteUsd))}</span></h3><p>${esc(f.problem)}</p><div class="do"><b>Do this:</b> ${esc(f.action)}</div>${table}</div>`;
|
|
3978
|
+
}).join("");
|
|
3979
|
+
}
|
|
3980
|
+
function toolWarnings(report) {
|
|
3981
|
+
const out = [];
|
|
3982
|
+
for (const f of report.findings) {
|
|
3983
|
+
const sessions = f.evidence?.["sessionsAffected"];
|
|
3984
|
+
const tool = f.evidence?.["tool"];
|
|
3985
|
+
if (typeof sessions === "number" && typeof tool === "string") {
|
|
3986
|
+
out.push({ title: f.title, sessions, tool, action: f.suggestedAction });
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
return out.sort((a, b) => b.sessions - a.sessions);
|
|
3990
|
+
}
|
|
3991
|
+
function renderSetupWarnings(fixes, report) {
|
|
3992
|
+
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
3993
|
+
const tool = toolWarnings(report);
|
|
3994
|
+
const multi = tool.filter((t) => t.sessions > 1);
|
|
3995
|
+
const single = tool.filter((t) => t.sessions === 1);
|
|
3996
|
+
const items = [];
|
|
3997
|
+
for (const f of warnFixes) {
|
|
3998
|
+
items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span></li>`);
|
|
3999
|
+
}
|
|
4000
|
+
for (const t of multi) {
|
|
4001
|
+
const sentence = t.action ? ` ${esc(t.action)}` : "";
|
|
4002
|
+
items.push(
|
|
4003
|
+
`<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span></li>`
|
|
4004
|
+
);
|
|
4005
|
+
}
|
|
4006
|
+
const list = items.length > 0 ? `<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
|
|
4007
|
+
let disclosure = "";
|
|
4008
|
+
if (single.length > 0) {
|
|
4009
|
+
const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
|
|
4010
|
+
disclosure = `<details style="margin-top:14px"><summary>${single.length} ${plural2(single.length, "finding")} seen in a single session each (${names})</summary><p class="note" style="margin:0">One session is not yet a pattern. These are listed for completeness and are not worth acting on until they repeat.</p></details>`;
|
|
4011
|
+
}
|
|
4012
|
+
return `<div class="panel">${list}${disclosure}</div>`;
|
|
4013
|
+
}
|
|
4014
|
+
var OPTIMIZED_NAME = "CLAUDE.optimized.md";
|
|
4015
|
+
var PLAYBOOK_NAME = "PLAYBOOK.md";
|
|
4016
|
+
var SETTINGS_NAME = "settings.suggested.json";
|
|
4017
|
+
var HARNESS_NAME = "HARNESS-UPGRADE.md";
|
|
4018
|
+
function renderArtifactCards(input) {
|
|
4019
|
+
const { before, after } = input.claudeMdTokens;
|
|
4020
|
+
const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
|
|
4021
|
+
const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
|
|
4022
|
+
const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
|
|
4023
|
+
const card = (name, desc) => `<div class="file"><span class="nm">${esc(name)}</span><span class="ds">${esc(desc)}</span><a href="${esc(name)}">Open file</a></div>`;
|
|
4024
|
+
return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") + `</div>`;
|
|
4025
|
+
}
|
|
4026
|
+
function renderApplyCta(input) {
|
|
4027
|
+
return `<div class="cta"><b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
|
|
4028
|
+
}
|
|
4029
|
+
function renderCarriedDisclosure(sections) {
|
|
4030
|
+
const carried = sections.filter((s) => s.disposition === "carried");
|
|
4031
|
+
if (carried.length === 0) return "";
|
|
4032
|
+
const names = carried.map((s) => esc(s.name)).join(" · ");
|
|
4033
|
+
return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md</summary><div class="cols">${names}</div></details>`;
|
|
4034
|
+
}
|
|
4035
|
+
function renderHeader(input) {
|
|
4036
|
+
const parts = [];
|
|
4037
|
+
const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
4038
|
+
if (stack.length > 0) parts.push(esc(stack.join(", ")));
|
|
4039
|
+
parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
|
|
4040
|
+
parts.push(`4 artifacts written to ${esc(input.artifactsDir)}/`);
|
|
4041
|
+
return `<header><p class="kicker">CostClaw optimize · dry run · nothing left your machine</p><h1>${esc(input.projectName)}</h1><p class="sub">${parts.join(" · ")}</p></header>`;
|
|
4042
|
+
}
|
|
4043
|
+
function renderOptimizeDashboard(input) {
|
|
4044
|
+
return `<!doctype html>
|
|
4045
|
+
<html lang="en">
|
|
4046
|
+
<head>
|
|
4047
|
+
<meta charset="utf-8">
|
|
4048
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4049
|
+
<title>CostClaw optimize: ${esc(input.projectName)}</title>
|
|
4050
|
+
<style>${STYLE2}</style>
|
|
4051
|
+
</head>
|
|
4052
|
+
<body>
|
|
4053
|
+
<div class="wrap">
|
|
4054
|
+
${renderHeader(input)}
|
|
4055
|
+
|
|
4056
|
+
<h2>What this run changed<span class="n">the receipt</span></h2>
|
|
4057
|
+
${renderReceipt(input)}
|
|
4058
|
+
|
|
4059
|
+
<h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
|
|
4060
|
+
<div class="panel">${renderComparisonTabs(input)}</div>
|
|
4061
|
+
|
|
4062
|
+
<h2>Fixes, ranked by what they recover</h2>
|
|
4063
|
+
${renderFixes(input.fixes, input.report)}
|
|
4064
|
+
|
|
4065
|
+
<h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
|
|
4066
|
+
${renderSetupWarnings(input.fixes, input.report)}
|
|
4067
|
+
|
|
4068
|
+
<h2>Your four artifacts</h2>
|
|
4069
|
+
${renderArtifactCards(input)}
|
|
4070
|
+
|
|
4071
|
+
<h2>Apply it</h2>
|
|
4072
|
+
${renderApplyCta(input)}
|
|
4073
|
+
|
|
4074
|
+
${renderCarriedDisclosure(input.sectionDispositions)}
|
|
4075
|
+
|
|
4076
|
+
<footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
|
|
4077
|
+
No network calls, no telemetry, no model calls.</footer>
|
|
4078
|
+
|
|
4079
|
+
</div>
|
|
4080
|
+
</body>
|
|
4081
|
+
</html>
|
|
4082
|
+
`;
|
|
4083
|
+
}
|
|
4084
|
+
|
|
3576
4085
|
// src/project-scan.ts
|
|
3577
4086
|
import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
|
|
3578
4087
|
import { join as join5, basename } from "path";
|
|
@@ -4095,11 +4604,12 @@ async function scanProject(dir) {
|
|
|
4095
4604
|
}
|
|
4096
4605
|
|
|
4097
4606
|
// src/optimize-command.ts
|
|
4098
|
-
var
|
|
4099
|
-
var
|
|
4100
|
-
var
|
|
4101
|
-
var
|
|
4102
|
-
|
|
4607
|
+
var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
|
|
4608
|
+
var PLAYBOOK_NAME2 = "PLAYBOOK.md";
|
|
4609
|
+
var SETTINGS_NAME2 = "settings.suggested.json";
|
|
4610
|
+
var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
|
|
4611
|
+
var DASHBOARD_NAME = "DASHBOARD.html";
|
|
4612
|
+
function usd6(n) {
|
|
4103
4613
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
4104
4614
|
}
|
|
4105
4615
|
function describeDetection(project) {
|
|
@@ -4243,12 +4753,35 @@ async function runOptimize(opts) {
|
|
|
4243
4753
|
});
|
|
4244
4754
|
const outDir = opts.out || join6(process.cwd(), "costclaw-out");
|
|
4245
4755
|
await mkdir3(outDir, { recursive: true });
|
|
4246
|
-
const playbookPath = join6(outDir,
|
|
4756
|
+
const playbookPath = join6(outDir, PLAYBOOK_NAME2);
|
|
4247
4757
|
await writeFile3(playbookPath, result.playbook, "utf8");
|
|
4248
|
-
const settingsPath = join6(outDir,
|
|
4758
|
+
const settingsPath = join6(outDir, SETTINGS_NAME2);
|
|
4249
4759
|
await writeFile3(settingsPath, result.settingsJson, "utf8");
|
|
4250
|
-
const harnessPath = join6(outDir,
|
|
4760
|
+
const harnessPath = join6(outDir, HARNESS_NAME2);
|
|
4251
4761
|
await writeFile3(harnessPath, result.harnessPrompt, "utf8");
|
|
4762
|
+
const wantDashboard = opts.dashboard !== false;
|
|
4763
|
+
let dashboardPath = null;
|
|
4764
|
+
if (wantDashboard) {
|
|
4765
|
+
const spend = report.summary.cost_usd;
|
|
4766
|
+
const html = renderOptimizeDashboard({
|
|
4767
|
+
version: opts.version ?? "",
|
|
4768
|
+
projectName: project.name ?? "your project",
|
|
4769
|
+
stack: project.stack,
|
|
4770
|
+
commandsCount: project.commands.length,
|
|
4771
|
+
artifactsDir: outDir,
|
|
4772
|
+
currentClaudeMd: claudeMd ?? null,
|
|
4773
|
+
optimizedClaudeMd: result.optimizedClaudeMd,
|
|
4774
|
+
claudeMdTokens: result.claudeMdTokens,
|
|
4775
|
+
sectionDispositions: result.sectionDispositions,
|
|
4776
|
+
placeholdersRemaining: result.placeholdersRemaining,
|
|
4777
|
+
fixes,
|
|
4778
|
+
report,
|
|
4779
|
+
headlineWasteShare: spend > 0 ? recoverable / spend : 0,
|
|
4780
|
+
headlineWasteUsd: recoverable
|
|
4781
|
+
});
|
|
4782
|
+
dashboardPath = join6(outDir, DASHBOARD_NAME);
|
|
4783
|
+
await writeFile3(dashboardPath, html, "utf8");
|
|
4784
|
+
}
|
|
4252
4785
|
const lines = [];
|
|
4253
4786
|
lines.push("CostClaw optimize");
|
|
4254
4787
|
lines.push("");
|
|
@@ -4284,7 +4817,7 @@ async function runOptimize(opts) {
|
|
|
4284
4817
|
}
|
|
4285
4818
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
4286
4819
|
} else {
|
|
4287
|
-
const optimizedPath = join6(outDir,
|
|
4820
|
+
const optimizedPath = join6(outDir, OPTIMIZED_NAME2);
|
|
4288
4821
|
await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
4289
4822
|
lines.push("Dry run (no files of yours were changed).");
|
|
4290
4823
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
@@ -4295,12 +4828,20 @@ async function runOptimize(opts) {
|
|
|
4295
4828
|
lines.push(describeDetection(project));
|
|
4296
4829
|
if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
|
|
4297
4830
|
if (plan === "api") {
|
|
4298
|
-
lines.push(`Recoverable spend (cache-miss exposure): ${
|
|
4831
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
|
|
4299
4832
|
} else {
|
|
4300
4833
|
const spend = report.summary.cost_usd;
|
|
4301
4834
|
const share = spend > 0 ? recoverable / spend * 100 : 0;
|
|
4302
4835
|
lines.push(
|
|
4303
|
-
`Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${
|
|
4836
|
+
`Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd6(recoverable)} at API rates)`
|
|
4837
|
+
);
|
|
4838
|
+
}
|
|
4839
|
+
const { before, after } = result.claudeMdTokens;
|
|
4840
|
+
if (before != null && before !== after) {
|
|
4841
|
+
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
4842
|
+
const dir = after > before ? "larger" : "smaller";
|
|
4843
|
+
lines.push(
|
|
4844
|
+
`Your CLAUDE.md: an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()} (${pct2}% ${dir}), paid on every turn.`
|
|
4304
4845
|
);
|
|
4305
4846
|
}
|
|
4306
4847
|
lines.push("");
|
|
@@ -4334,6 +4875,12 @@ async function runOptimize(opts) {
|
|
|
4334
4875
|
lines.push("");
|
|
4335
4876
|
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
4336
4877
|
lines.push("Nothing left your machine.");
|
|
4878
|
+
if (dashboardPath) {
|
|
4879
|
+
lines.push("");
|
|
4880
|
+
lines.push(`Opening the summary dashboard: ${dashboardPath}`);
|
|
4881
|
+
lines.push("It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it.");
|
|
4882
|
+
openInBrowser(dashboardPath);
|
|
4883
|
+
}
|
|
4337
4884
|
return { output: lines.join("\n") };
|
|
4338
4885
|
}
|
|
4339
4886
|
|
|
@@ -4374,11 +4921,11 @@ import { join as join7 } from "path";
|
|
|
4374
4921
|
import { homedir as homedir5 } from "os";
|
|
4375
4922
|
|
|
4376
4923
|
// src/format-diff.ts
|
|
4377
|
-
function
|
|
4924
|
+
function usd7(n) {
|
|
4378
4925
|
return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
|
|
4379
4926
|
}
|
|
4380
4927
|
function signedUsd(n) {
|
|
4381
|
-
return `${n < 0 ? "-" : "+"}${
|
|
4928
|
+
return `${n < 0 ? "-" : "+"}${usd7(n)}`;
|
|
4382
4929
|
}
|
|
4383
4930
|
function signedInt(n) {
|
|
4384
4931
|
return n > 0 ? `+${n}` : `${n}`;
|
|
@@ -4399,23 +4946,23 @@ function formatDiff(d) {
|
|
|
4399
4946
|
if (d.comparable && d.marginal) {
|
|
4400
4947
|
lines.push("Since the baseline:");
|
|
4401
4948
|
lines.push(
|
|
4402
|
-
` New spend ${
|
|
4949
|
+
` New spend ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
|
|
4403
4950
|
);
|
|
4404
4951
|
lines.push(
|
|
4405
4952
|
` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
|
|
4406
4953
|
);
|
|
4407
4954
|
lines.push(
|
|
4408
|
-
` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${
|
|
4955
|
+
` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
|
|
4409
4956
|
);
|
|
4410
4957
|
} else {
|
|
4411
4958
|
lines.push("Note: the current audit covers less history than the baseline (logs moved or");
|
|
4412
4959
|
lines.push("pruned), so period metrics are omitted.");
|
|
4413
4960
|
lines.push("");
|
|
4414
4961
|
lines.push(
|
|
4415
|
-
`Baseline (${day(d.baseline.createdAt)}): spend ${
|
|
4962
|
+
`Baseline (${day(d.baseline.createdAt)}): spend ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd7(d.baseline.recoverableUsd)}`
|
|
4416
4963
|
);
|
|
4417
4964
|
lines.push(
|
|
4418
|
-
`Current (${day(d.current.createdAt)}): spend ${
|
|
4965
|
+
`Current (${day(d.current.createdAt)}): spend ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd7(d.current.recoverableUsd)}`
|
|
4419
4966
|
);
|
|
4420
4967
|
}
|
|
4421
4968
|
lines.push("");
|
|
@@ -4438,18 +4985,18 @@ function formatDiff(d) {
|
|
|
4438
4985
|
if (resolved.length > 0) {
|
|
4439
4986
|
lines.push("");
|
|
4440
4987
|
lines.push("Fixes resolved since the baseline:");
|
|
4441
|
-
for (const f of resolved) lines.push(` - [${
|
|
4988
|
+
for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
|
|
4442
4989
|
}
|
|
4443
4990
|
if (appeared.length > 0) {
|
|
4444
4991
|
lines.push("");
|
|
4445
4992
|
lines.push("New since the baseline:");
|
|
4446
|
-
for (const f of appeared) lines.push(` - [${
|
|
4993
|
+
for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
|
|
4447
4994
|
}
|
|
4448
4995
|
if (changed.length > 0) {
|
|
4449
4996
|
lines.push("");
|
|
4450
4997
|
lines.push("Fixes that moved:");
|
|
4451
4998
|
for (const c of changed) {
|
|
4452
|
-
lines.push(` - ${c.title}: ${
|
|
4999
|
+
lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
|
|
4453
5000
|
}
|
|
4454
5001
|
}
|
|
4455
5002
|
return lines.join("\n");
|
|
@@ -4660,7 +5207,7 @@ function parseBadgeFlags(args) {
|
|
|
4660
5207
|
};
|
|
4661
5208
|
}
|
|
4662
5209
|
function cliVersion() {
|
|
4663
|
-
return true ? "0.
|
|
5210
|
+
return true ? "0.7.0" : "0.0.0-dev";
|
|
4664
5211
|
}
|
|
4665
5212
|
function isHelpRequest(command, args) {
|
|
4666
5213
|
if (command === void 0) return false;
|
|
@@ -4675,7 +5222,7 @@ function helpText() {
|
|
|
4675
5222
|
" costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
|
|
4676
5223
|
" costclaw diff [<baseline.json> <current.json>] [--json]",
|
|
4677
5224
|
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
4678
|
-
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
|
|
5225
|
+
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]",
|
|
4679
5226
|
" costclaw activate <license-key> [--name <machine-name>]",
|
|
4680
5227
|
" costclaw deactivate",
|
|
4681
5228
|
" costclaw --version",
|
|
@@ -4714,6 +5261,8 @@ function helpText() {
|
|
|
4714
5261
|
"--apply-settings [file] additively merges the derived permission allowlist into",
|
|
4715
5262
|
"the project's .claude/settings.json (or [file]); it only touches",
|
|
4716
5263
|
"permissions.allow and permissions.deny, backs up the original, and prints a diff.",
|
|
5264
|
+
"It also writes DASHBOARD.html and opens it: one page that browses every artifact,",
|
|
5265
|
+
"the ranked fixes, and a before and after of your CLAUDE.md. --no-dashboard skips it.",
|
|
4717
5266
|
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
4718
5267
|
"costclaw activate <key>. activate and deactivate move that license between",
|
|
4719
5268
|
"machines. audit never needs a license.",
|
|
@@ -4787,6 +5336,8 @@ Run: costclaw optimize
|
|
|
4787
5336
|
out: getFlag(args, "--out"),
|
|
4788
5337
|
write: getFlag(args, "--write"),
|
|
4789
5338
|
force: args.includes("--force"),
|
|
5339
|
+
dashboard: !args.includes("--no-dashboard"),
|
|
5340
|
+
version: cliVersion(),
|
|
4790
5341
|
applySettings: args.includes("--apply-settings"),
|
|
4791
5342
|
applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
|
|
4792
5343
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|