costclaw 0.12.4 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -72
- package/dist/index.js +874 -257
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -187,6 +187,30 @@ function cacheMissExposureForNormalizedUsage(model, usage) {
|
|
|
187
187
|
const p = priceFor(model);
|
|
188
188
|
return (usage.input_tokens * (p.input - p.cache_read) + usage.cache_creation_5m_input_tokens * (p.cache_write - p.cache_read) + usage.cache_creation_1h_input_tokens * (p.cache_write_1h - p.cache_read)) * pricingMultiplier(model, usage) / 1e6;
|
|
189
189
|
}
|
|
190
|
+
function uncachedInputExposureForNormalizedUsage(model, usage) {
|
|
191
|
+
const p = priceFor(model);
|
|
192
|
+
return usage.input_tokens * (p.input - p.cache_read) * pricingMultiplier(model, usage) / 1e6;
|
|
193
|
+
}
|
|
194
|
+
function cacheWritePremiumForNormalizedUsage(model, usage) {
|
|
195
|
+
const p = priceFor(model);
|
|
196
|
+
return (usage.cache_creation_5m_input_tokens * (p.cache_write - p.cache_read) + usage.cache_creation_1h_input_tokens * (p.cache_write_1h - p.cache_read)) * pricingMultiplier(model, usage) / 1e6;
|
|
197
|
+
}
|
|
198
|
+
function cacheAmortizationShare(totals) {
|
|
199
|
+
const writes = totals.cache_creation_tokens;
|
|
200
|
+
if (!Number.isFinite(writes) || writes <= 0) return 1;
|
|
201
|
+
const reads = Number.isFinite(totals.cache_read_tokens) ? totals.cache_read_tokens : 0;
|
|
202
|
+
return Math.min(1, Math.max(0, reads / writes));
|
|
203
|
+
}
|
|
204
|
+
function uncachedInputExposureForTotals(model, totals) {
|
|
205
|
+
return uncachedInputExposureForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
|
|
206
|
+
}
|
|
207
|
+
function cacheWritePremiumForTotals(model, totals) {
|
|
208
|
+
return cacheWritePremiumForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
|
|
209
|
+
}
|
|
210
|
+
function recoverableExposureForTotals(model, totals) {
|
|
211
|
+
const unamortized = 1 - cacheAmortizationShare(totals);
|
|
212
|
+
return uncachedInputExposureForTotals(model, totals) + cacheWritePremiumForTotals(model, totals) * unamortized;
|
|
213
|
+
}
|
|
190
214
|
function cacheHitRate(totals) {
|
|
191
215
|
const denom = totals.input_tokens + totals.cache_creation_tokens + totals.cache_read_tokens;
|
|
192
216
|
if (!Number.isFinite(denom) || denom <= 0) return 0;
|
|
@@ -391,6 +415,8 @@ function rebuildSessionUsage(session, fragments, extraWarnings = []) {
|
|
|
391
415
|
session.cost_usd = 0;
|
|
392
416
|
session.cache_savings_usd = 0;
|
|
393
417
|
session.cacheMissExposureUsd = 0;
|
|
418
|
+
session.uncachedInputExposureUsd = 0;
|
|
419
|
+
session.cacheWritePremiumUsd = 0;
|
|
394
420
|
session.modelCostsUsd = {};
|
|
395
421
|
session.unknownModelRequests = {};
|
|
396
422
|
session.pricedRequests = 0;
|
|
@@ -412,6 +438,8 @@ function rebuildSessionUsage(session, fragments, extraWarnings = []) {
|
|
|
412
438
|
session.cost_usd += fragment.costUsd;
|
|
413
439
|
session.cache_savings_usd += fragment.cacheSavingsUsd;
|
|
414
440
|
session.cacheMissExposureUsd += fragment.cacheMissExposureUsd;
|
|
441
|
+
session.uncachedInputExposureUsd += fragment.uncachedInputExposureUsd;
|
|
442
|
+
session.cacheWritePremiumUsd += fragment.cacheWritePremiumUsd;
|
|
415
443
|
const modelKey = fragment.model ?? "unknown";
|
|
416
444
|
session.modelCostsUsd[modelKey] = (session.modelCostsUsd[modelKey] ?? 0) + fragment.costUsd;
|
|
417
445
|
if (fragment.model && isKnownModel(fragment.model)) session.pricedRequests += 1;
|
|
@@ -467,6 +495,8 @@ function parseSession(text2, opts = {}) {
|
|
|
467
495
|
costBuckets: [],
|
|
468
496
|
modelCostsUsd: {},
|
|
469
497
|
cacheMissExposureUsd: 0,
|
|
498
|
+
uncachedInputExposureUsd: 0,
|
|
499
|
+
cacheWritePremiumUsd: 0,
|
|
470
500
|
accuracyWarnings: [],
|
|
471
501
|
unknownModelRequests: {},
|
|
472
502
|
pricedRequests: 0,
|
|
@@ -598,6 +628,8 @@ function parseSession(text2, opts = {}) {
|
|
|
598
628
|
costUsd: fragmentUsd,
|
|
599
629
|
cacheSavingsUsd: cacheSavingsForNormalizedUsage(accepted.model, u),
|
|
600
630
|
cacheMissExposureUsd: cacheMissExposureForNormalizedUsage(accepted.model, u),
|
|
631
|
+
uncachedInputExposureUsd: uncachedInputExposureForNormalizedUsage(accepted.model, u),
|
|
632
|
+
cacheWritePremiumUsd: cacheWritePremiumForNormalizedUsage(accepted.model, u),
|
|
601
633
|
timestampMs: accepted.timestampMs
|
|
602
634
|
});
|
|
603
635
|
}
|
|
@@ -1169,12 +1201,77 @@ function deduplicateLogicalRequests(sessions) {
|
|
|
1169
1201
|
}
|
|
1170
1202
|
return sessions.filter((session, index) => !dropSessions[index] && ((session.usageFragments?.length ?? 0) > 0 || originalCounts[index] === 0));
|
|
1171
1203
|
}
|
|
1204
|
+
function recoverableExposureForSession(s) {
|
|
1205
|
+
if (s.uncachedInputExposureUsd == null || s.cacheWritePremiumUsd == null) {
|
|
1206
|
+
return recoverableExposureForTotals(s.modelPrimary, s.totals);
|
|
1207
|
+
}
|
|
1208
|
+
return s.uncachedInputExposureUsd + s.cacheWritePremiumUsd * (1 - cacheAmortizationShare(s.totals));
|
|
1209
|
+
}
|
|
1210
|
+
function amortizedCacheWriteForSession(s) {
|
|
1211
|
+
const write = s.cacheWritePremiumUsd ?? cacheWritePremiumForTotals(s.modelPrimary, s.totals);
|
|
1212
|
+
return write * cacheAmortizationShare(s.totals);
|
|
1213
|
+
}
|
|
1172
1214
|
function cacheMissExposureUsd(report) {
|
|
1173
1215
|
let total = 0;
|
|
1174
1216
|
for (const proj of report.projects) {
|
|
1175
1217
|
for (const s of proj.sessions) {
|
|
1176
1218
|
if (s.kind !== "main") continue;
|
|
1177
|
-
total +=
|
|
1219
|
+
total += recoverableExposureForSession(s);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return total;
|
|
1223
|
+
}
|
|
1224
|
+
function recoverableTotalUsd(report) {
|
|
1225
|
+
return cacheMissExposureUsd(report) + idleCacheExpiry(report).longIdleUsd;
|
|
1226
|
+
}
|
|
1227
|
+
function coldStartExposureUsd(report) {
|
|
1228
|
+
let total = 0;
|
|
1229
|
+
for (const proj of report.projects) {
|
|
1230
|
+
for (const s of proj.sessions) {
|
|
1231
|
+
if (s.kind !== "main") continue;
|
|
1232
|
+
const first = s.usageFragments?.[0];
|
|
1233
|
+
if (first) total += first.uncachedInputExposureUsd;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
return total;
|
|
1237
|
+
}
|
|
1238
|
+
var CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
1239
|
+
var LONG_IDLE_MS = 60 * 60 * 1e3;
|
|
1240
|
+
function idleCacheExpiry(report) {
|
|
1241
|
+
let usd8 = 0;
|
|
1242
|
+
let events = 0;
|
|
1243
|
+
let longIdleUsd = 0;
|
|
1244
|
+
let longIdleEvents = 0;
|
|
1245
|
+
let maxGapMs = 0;
|
|
1246
|
+
for (const proj of report.projects) {
|
|
1247
|
+
for (const s of proj.sessions) {
|
|
1248
|
+
if (s.kind !== "main") continue;
|
|
1249
|
+
let prevTs = null;
|
|
1250
|
+
for (const f of s.usageFragments ?? []) {
|
|
1251
|
+
const ts = f.timestampMs;
|
|
1252
|
+
if (ts == null) continue;
|
|
1253
|
+
const gap = prevTs == null ? 0 : ts - prevTs;
|
|
1254
|
+
if (prevTs != null && gap > CACHE_TTL_MS && f.cacheWritePremiumUsd > 0) {
|
|
1255
|
+
usd8 += f.cacheWritePremiumUsd;
|
|
1256
|
+
events += 1;
|
|
1257
|
+
if (gap >= LONG_IDLE_MS) {
|
|
1258
|
+
longIdleUsd += f.cacheWritePremiumUsd;
|
|
1259
|
+
longIdleEvents += 1;
|
|
1260
|
+
}
|
|
1261
|
+
if (gap > maxGapMs) maxGapMs = gap;
|
|
1262
|
+
}
|
|
1263
|
+
prevTs = ts;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
return { usd: usd8, events, longIdleUsd, longIdleEvents, maxGapMinutes: maxGapMs / 6e4 };
|
|
1268
|
+
}
|
|
1269
|
+
function cacheWriteCostUsd(report) {
|
|
1270
|
+
let total = 0;
|
|
1271
|
+
for (const proj of report.projects) {
|
|
1272
|
+
for (const s of proj.sessions) {
|
|
1273
|
+
if (s.kind !== "main") continue;
|
|
1274
|
+
total += amortizedCacheWriteForSession(s);
|
|
1178
1275
|
}
|
|
1179
1276
|
}
|
|
1180
1277
|
return total;
|
|
@@ -1188,7 +1285,7 @@ function cacheMissByProject(report) {
|
|
|
1188
1285
|
for (const s of proj.sessions) {
|
|
1189
1286
|
if (s.kind !== "main") continue;
|
|
1190
1287
|
sessionsCount += 1;
|
|
1191
|
-
usd8 +=
|
|
1288
|
+
usd8 += recoverableExposureForSession(s);
|
|
1192
1289
|
mainTotals.input_tokens += s.totals.input_tokens;
|
|
1193
1290
|
mainTotals.output_tokens += s.totals.output_tokens;
|
|
1194
1291
|
mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
|
|
@@ -1436,6 +1533,41 @@ function optionScore(question, optionId) {
|
|
|
1436
1533
|
const opt = question.options.find((o) => o.id === optionId);
|
|
1437
1534
|
return opt ? opt.score : null;
|
|
1438
1535
|
}
|
|
1536
|
+
var CHECK_ACTION = {
|
|
1537
|
+
// CLAUDE.md quality. cmd_size is overridden per file, since trimming and
|
|
1538
|
+
// filling out are opposite instructions.
|
|
1539
|
+
cmd_size: "Keep CLAUDE.md to the durable conventions the agent actually needs and move the rest into docs it can open on demand.",
|
|
1540
|
+
cmd_structure: "Break the file into sections with headings and short bulleted rules so the agent finds the right guidance fast instead of scanning a wall of text.",
|
|
1541
|
+
cmd_stability: "Move dates, TODOs, and 'updated' notes into a separate scratch file. A stable CLAUDE.md keeps the cache warm across sessions instead of resetting it.",
|
|
1542
|
+
cmd_scope: "Limit CLAUDE.md to durable conventions and project facts. Changing notes belong elsewhere so the cached prefix stays constant.",
|
|
1543
|
+
// Context hygiene.
|
|
1544
|
+
cache_hit: "Open each session the same way, same CLAUDE.md and same first reads, so turn two onward reads the prefix at about a tenth of the input price instead of re-buying it.",
|
|
1545
|
+
cache_churn: "You are writing cache faster than you read it back. Stop editing CLAUDE.md mid-session and keep the opening reads identical, so one write serves many turns.",
|
|
1546
|
+
clear_between: "Run /clear or compact when you switch to an unrelated task so stale context stops riding along and inflating every turn.",
|
|
1547
|
+
// Prompting patterns.
|
|
1548
|
+
verify_loop: "End the prompt with the check: 'run the tests after implementing', 'verify the build succeeds', or a screenshot to compare. The loop then closes on its own instead of waiting for you to notice a mistake.",
|
|
1549
|
+
plan_before_code: "For work that touches several files or unfamiliar code, start in plan mode (Shift+Tab) or ask for a plan first, approve it, then implement. Skip the plan when you could describe the diff in one sentence.",
|
|
1550
|
+
prompt_specificity: "Name the file with @, paste the error or screenshot, state the scenario and what 'fixed' looks like. 'fix the login bug' becomes 'login fails after session timeout; check src/auth token refresh; write a failing test, then fix it'.",
|
|
1551
|
+
correction_churn: "When a session needs a third correction, run /clear and write a fresh prompt that includes what you learned. A clean session with a better prompt beats a long one full of failed approaches.",
|
|
1552
|
+
reusable_workflows: "Put any workflow you have typed twice into .claude/skills/<name>/SKILL.md and invoke it with /name. Delegate broad investigation to a subagent so the reading stays out of your main context.",
|
|
1553
|
+
plan_first: "Use plan mode or write a short spec for multi-step tasks. Planning first cuts the reactive tool loops that burn tokens.",
|
|
1554
|
+
success_criteria: "State the done condition or point at a test so the agent can verify its own work instead of guessing and retrying.",
|
|
1555
|
+
tool_thrash: "Give the loop a stop condition. Name the budget in the prompt, 'read at most five files then propose', or narrow the task so the agent is not scanning the repo to find its own footing.",
|
|
1556
|
+
// Session management.
|
|
1557
|
+
short_session_bloat: "Those sessions burned fast for how long they ran. Scope the prompt before you start, and open routine edits on a cheaper model instead of the most expensive one.",
|
|
1558
|
+
session_scope: "Start a fresh session per task and reset between them. Long marathon sessions carry a growing, expensive context.",
|
|
1559
|
+
session_marathon: "Compact or start a fresh session before the context outgrows the cache. The later turns of a long session re-pay for context you already bought.",
|
|
1560
|
+
// Tool and MCP config.
|
|
1561
|
+
permission_allowlist: "Add a settings allowlist for safe, frequent commands to cut approval prompts and the round trips they cost.",
|
|
1562
|
+
mcp_scoped: "Disable MCP servers and tools you do not use. Every loaded tool definition is context you pay for on every turn.",
|
|
1563
|
+
bash_reliance: "Replace shelling out for search and file reads with Grep, Glob, and Read. They are cheaper, cleaner, and easier to permission.",
|
|
1564
|
+
// Cost discipline.
|
|
1565
|
+
recoverable_exposure: "Most of this is input your setup could have served from cache. Keep the opening of each session identical so the prefix is a cache read rather than a repeat purchase.",
|
|
1566
|
+
model_routing: "Send the short, mechanical sessions to a cheaper model and keep the top model for the hard reasoning. Same work, lower bill.",
|
|
1567
|
+
model_choice: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill.",
|
|
1568
|
+
model_fit: "Match the model to the task rather than defaulting to one. Routine edits do not need the reasoning you are paying for.",
|
|
1569
|
+
cost_monitor: "Watch token spend or set a budget so a runaway session is caught early rather than at the monthly bill."
|
|
1570
|
+
};
|
|
1439
1571
|
|
|
1440
1572
|
// ../../packages/engine/src/prompting.ts
|
|
1441
1573
|
var SUBSTANTIAL_MIN_TURNS = 20;
|
|
@@ -1505,7 +1637,7 @@ function aggregatePrompting(report) {
|
|
|
1505
1637
|
function clamp2(n, lo = 0, hi = 100) {
|
|
1506
1638
|
return Math.max(lo, Math.min(hi, n));
|
|
1507
1639
|
}
|
|
1508
|
-
function makeCheck(id, pillar, label, score, basis, signal) {
|
|
1640
|
+
function makeCheck(id, pillar, label, score, basis, signal, actionOverride) {
|
|
1509
1641
|
const assessed = score !== null;
|
|
1510
1642
|
return {
|
|
1511
1643
|
id,
|
|
@@ -1515,9 +1647,13 @@ function makeCheck(id, pillar, label, score, basis, signal) {
|
|
|
1515
1647
|
score: assessed ? Math.round(score) : null,
|
|
1516
1648
|
basis,
|
|
1517
1649
|
signal,
|
|
1518
|
-
gap: assessed && score < GAP_THRESHOLD
|
|
1650
|
+
gap: assessed && score < GAP_THRESHOLD,
|
|
1651
|
+
action: actionOverride ?? CHECK_ACTION[id] ?? ""
|
|
1519
1652
|
};
|
|
1520
1653
|
}
|
|
1654
|
+
function num(n) {
|
|
1655
|
+
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1656
|
+
}
|
|
1521
1657
|
function questionnaireCheck(id, label, answers) {
|
|
1522
1658
|
const q = questionById(id);
|
|
1523
1659
|
if (!q) return makeCheck(id, "claude_md", label, null, "Unknown question.", "questionnaire");
|
|
@@ -1557,8 +1693,9 @@ function buildChecks(report, cmd2, answers, setup) {
|
|
|
1557
1693
|
"claude_md",
|
|
1558
1694
|
"Size",
|
|
1559
1695
|
cmd2.present ? cmd2.sizeScore : null,
|
|
1560
|
-
cmd2.present ? `Your CLAUDE.md is ${cmd2.chars
|
|
1561
|
-
"claudemd"
|
|
1696
|
+
cmd2.present ? `Your CLAUDE.md is ${num(cmd2.chars)} characters, about ${num(cmd2.estTokens)} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
|
|
1697
|
+
"claudemd",
|
|
1698
|
+
cmd2.present && cmd2.chars > 6e3 ? `Your CLAUDE.md is an estimated ${num(cmd2.estTokens)} tokens, 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.` : "Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
|
|
1562
1699
|
)
|
|
1563
1700
|
);
|
|
1564
1701
|
checks.push(
|
|
@@ -1567,7 +1704,7 @@ function buildChecks(report, cmd2, answers, setup) {
|
|
|
1567
1704
|
"claude_md",
|
|
1568
1705
|
"Structure",
|
|
1569
1706
|
cmd2.present ? cmd2.structureScore : null,
|
|
1570
|
-
cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${cmd2.chars
|
|
1707
|
+
cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${num(cmd2.chars)} characters.` : "No CLAUDE.md was provided.",
|
|
1571
1708
|
"claudemd"
|
|
1572
1709
|
)
|
|
1573
1710
|
);
|
|
@@ -1757,11 +1894,11 @@ function buildChecks(report, cmd2, answers, setup) {
|
|
|
1757
1894
|
"tooling",
|
|
1758
1895
|
"Tool fit",
|
|
1759
1896
|
tools.total >= 20 ? clamp2(100 - Math.max(0, bashShare - 0.3) * 200) : null,
|
|
1760
|
-
tools.total >= 20 ? `Bash was ${(bashShare * 100).toFixed(0)}% of your ${tools.total
|
|
1897
|
+
tools.total >= 20 ? `Bash was ${(bashShare * 100).toFixed(0)}% of your ${num(tools.total)} tool calls; dedicated tools like Grep, Glob, and Read are cheaper and cleaner than shelling out.` : "Too few tool calls to judge tool fit.",
|
|
1761
1898
|
"metrics"
|
|
1762
1899
|
)
|
|
1763
1900
|
);
|
|
1764
|
-
const exposure =
|
|
1901
|
+
const exposure = recoverableTotalUsd(report);
|
|
1765
1902
|
const spend = s.mainCostUsd;
|
|
1766
1903
|
const exposureShare = spend > 0 ? exposure / spend : 0;
|
|
1767
1904
|
const exposureValid = spend > 0 && exposure >= 0 && exposure <= spend + 1e-9;
|
|
@@ -1823,88 +1960,49 @@ function scorePillars(report, cmd2, answers, setup) {
|
|
|
1823
1960
|
}
|
|
1824
1961
|
|
|
1825
1962
|
// ../../packages/engine/src/synthesize.ts
|
|
1826
|
-
var
|
|
1827
|
-
verify_loop:
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
cmd_stability: {
|
|
1852
|
-
title: "Remove volatile content from CLAUDE.md",
|
|
1853
|
-
action: "Move dates, TODOs, and 'updated' notes into a separate scratch file. A stable CLAUDE.md keeps the cache warm across sessions instead of resetting it."
|
|
1854
|
-
},
|
|
1855
|
-
cmd_scope: {
|
|
1856
|
-
title: "Keep CLAUDE.md to stable facts",
|
|
1857
|
-
action: "Limit CLAUDE.md to durable conventions and project facts. Changing notes belong elsewhere so the cached prefix stays constant."
|
|
1858
|
-
},
|
|
1859
|
-
clear_between: {
|
|
1860
|
-
title: "Clear or compact between unrelated tasks",
|
|
1861
|
-
action: "Run /clear or compact when you switch to an unrelated task so stale context stops riding along and inflating every turn."
|
|
1862
|
-
},
|
|
1863
|
-
plan_first: {
|
|
1864
|
-
title: "Plan before acting on multi-step work",
|
|
1865
|
-
action: "Use plan mode or write a short spec for multi-step tasks. Planning first cuts the reactive tool loops that burn tokens."
|
|
1866
|
-
},
|
|
1867
|
-
success_criteria: {
|
|
1868
|
-
title: "Give the agent success criteria",
|
|
1869
|
-
action: "State the done condition or point at a test so the agent can verify its own work instead of guessing and retrying."
|
|
1870
|
-
},
|
|
1871
|
-
session_scope: {
|
|
1872
|
-
title: "Scope sessions to one task",
|
|
1873
|
-
action: "Start a fresh session per task and reset between them. Long marathon sessions carry a growing, expensive context."
|
|
1874
|
-
},
|
|
1875
|
-
mcp_scoped: {
|
|
1876
|
-
title: "Trim unused MCP servers and tools",
|
|
1877
|
-
action: "Disable MCP servers and tools you do not use. Every loaded tool definition is context you pay for on every turn."
|
|
1878
|
-
},
|
|
1879
|
-
permission_allowlist: {
|
|
1880
|
-
title: "Set a permission allowlist",
|
|
1881
|
-
action: "Add a settings allowlist for safe, frequent commands to cut approval prompts and the round trips they cost."
|
|
1882
|
-
},
|
|
1883
|
-
bash_reliance: {
|
|
1884
|
-
title: "Use dedicated tools over Bash",
|
|
1885
|
-
action: "Replace shelling out for search and file reads with Grep, Glob, and Read. They are cheaper, cleaner, and easier to permission."
|
|
1886
|
-
},
|
|
1887
|
-
cost_monitor: {
|
|
1888
|
-
title: "Track your spend",
|
|
1889
|
-
action: "Watch token spend or set a budget so a runaway session is caught early rather than at the monthly bill."
|
|
1890
|
-
},
|
|
1891
|
-
model_choice: {
|
|
1892
|
-
title: "Match the model to the task",
|
|
1893
|
-
action: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill."
|
|
1894
|
-
}
|
|
1963
|
+
var CHECK_TITLE = {
|
|
1964
|
+
verify_loop: "Give the agent a check it can run",
|
|
1965
|
+
plan_before_code: "Plan before multi-file changes",
|
|
1966
|
+
prompt_specificity: "Open with specifics, not a headline",
|
|
1967
|
+
correction_churn: "Clear and re-prompt after two corrections",
|
|
1968
|
+
reusable_workflows: "Turn repeated prompts into skills",
|
|
1969
|
+
tool_thrash: "Give the tool loop a stop condition",
|
|
1970
|
+
cmd_structure: "Give CLAUDE.md clear structure",
|
|
1971
|
+
cmd_stability: "Remove volatile content from CLAUDE.md",
|
|
1972
|
+
cmd_scope: "Keep CLAUDE.md to stable facts",
|
|
1973
|
+
cache_hit: "Open each session the same way",
|
|
1974
|
+
cache_churn: "Stop rewriting the cache mid-session",
|
|
1975
|
+
clear_between: "Clear or compact between unrelated tasks",
|
|
1976
|
+
plan_first: "Plan before acting on multi-step work",
|
|
1977
|
+
success_criteria: "Give the agent success criteria",
|
|
1978
|
+
session_scope: "Scope sessions to one task",
|
|
1979
|
+
session_marathon: "End a session before the cache stops helping",
|
|
1980
|
+
short_session_bloat: "Slow down the fastest-burning sessions",
|
|
1981
|
+
mcp_scoped: "Trim unused MCP servers and tools",
|
|
1982
|
+
permission_allowlist: "Set a permission allowlist",
|
|
1983
|
+
bash_reliance: "Use dedicated tools over Bash",
|
|
1984
|
+
cost_monitor: "Track your spend",
|
|
1985
|
+
model_routing: "Match the model to the task",
|
|
1986
|
+
model_choice: "Match the model to the task",
|
|
1987
|
+
model_fit: "Match the model to the task"
|
|
1895
1988
|
};
|
|
1989
|
+
function checkFix(id) {
|
|
1990
|
+
const title = CHECK_TITLE[id];
|
|
1991
|
+
const action = CHECK_ACTION[id];
|
|
1992
|
+
return title && action ? { title, action } : null;
|
|
1993
|
+
}
|
|
1896
1994
|
var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
|
|
1897
1995
|
function severityRank(s) {
|
|
1898
1996
|
return s === "critical" ? 3 : s === "warn" ? 2 : 1;
|
|
1899
1997
|
}
|
|
1900
|
-
function
|
|
1998
|
+
function num2(n) {
|
|
1901
1999
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1902
2000
|
}
|
|
1903
2001
|
function sizeFix(cmd2) {
|
|
1904
2002
|
if (cmd2.chars > 6e3) {
|
|
1905
2003
|
return {
|
|
1906
2004
|
title: "Trim your CLAUDE.md",
|
|
1907
|
-
action: `Your CLAUDE.md is an estimated ${
|
|
2005
|
+
action: `Your CLAUDE.md is an estimated ${num2(cmd2.estTokens)} tokens (${num2(cmd2.chars)} 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.`
|
|
1908
2006
|
};
|
|
1909
2007
|
}
|
|
1910
2008
|
return {
|
|
@@ -1913,11 +2011,15 @@ function sizeFix(cmd2) {
|
|
|
1913
2011
|
};
|
|
1914
2012
|
}
|
|
1915
2013
|
function synthesize(report, pillars, cmd2, plan = "api") {
|
|
1916
|
-
const headlineWasteUsd =
|
|
1917
|
-
const
|
|
1918
|
-
const
|
|
2014
|
+
const headlineWasteUsd = recoverableTotalUsd(report);
|
|
2015
|
+
const cacheRecoverable = cacheMissExposureUsd(report);
|
|
2016
|
+
const headlineWasteLabel = "Recoverable waste (estimate)";
|
|
2017
|
+
const spend = report.summary.mainCostUsd;
|
|
1919
2018
|
const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
|
|
1920
|
-
const exposure =
|
|
2019
|
+
const exposure = cacheRecoverable;
|
|
2020
|
+
const coldStartUsd = coldStartExposureUsd(report);
|
|
2021
|
+
const cacheAddressableUsd = Math.max(0, cacheRecoverable - coldStartUsd);
|
|
2022
|
+
const addressableUsd = Math.max(0, headlineWasteUsd - coldStartUsd);
|
|
1921
2023
|
const fixes = [];
|
|
1922
2024
|
const covered = /* @__PURE__ */ new Set();
|
|
1923
2025
|
const round23 = (n) => roundMoneyHalfUp(n);
|
|
@@ -1985,7 +2087,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
1985
2087
|
}
|
|
1986
2088
|
}
|
|
1987
2089
|
}
|
|
1988
|
-
const exposureMaterial = round23(
|
|
2090
|
+
const exposureMaterial = round23(cacheAddressableUsd) > 0 && cacheAddressableUsd > coldStartUsd;
|
|
1989
2091
|
if (exposureMaterial) {
|
|
1990
2092
|
const worst = cacheMissByProject(report).filter((r) => r.usd > 0).slice(0, 3).map((r) => r.slug);
|
|
1991
2093
|
const pct2 = (n) => Math.round(n * 100);
|
|
@@ -1996,25 +2098,55 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
1996
2098
|
action = `Your CLAUDE.md carries ${cmd2.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
|
|
1997
2099
|
} else if (badCacheBest) {
|
|
1998
2100
|
action = `The last ${badCacheBest.sessionsConsidered} sessions in ${badCacheBest.slug} reused only ${pct2(badCacheBest.recentHitRate)}% from the cache. Open each session the same way (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price.`;
|
|
2101
|
+
} else if (worst.length > 0) {
|
|
2102
|
+
action = `Most of it sits in ${worst[0]}. Open that project the same way every time (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price instead of re-paying for it.`;
|
|
1999
2103
|
} else {
|
|
2000
|
-
action = "
|
|
2104
|
+
action = "";
|
|
2001
2105
|
}
|
|
2106
|
+
if (action) {
|
|
2107
|
+
fixes.push({
|
|
2108
|
+
id: "cache_recovery",
|
|
2109
|
+
title: "Recover the cache misses a steadier setup would avoid",
|
|
2110
|
+
pillar: "context_hygiene",
|
|
2111
|
+
pillarName: PILLARS.context_hygiene.name,
|
|
2112
|
+
severity: sevForUsd(cacheAddressableUsd),
|
|
2113
|
+
// The fix carries what a change can reach, not the whole headline: the
|
|
2114
|
+
// cold start is in the headline but no fix removes it.
|
|
2115
|
+
wasteUsd: round23(cacheAddressableUsd),
|
|
2116
|
+
problem: sanitizeText(
|
|
2117
|
+
`${usd8(cacheAddressableUsd)} of your ${usd8(spend)} main-session spend went to input your setup could have served from cache, on top of the ${usd8(coldStartUsd)} first turns must pay whatever you do. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
2118
|
+
),
|
|
2119
|
+
action: sanitizeText(action),
|
|
2120
|
+
basis: sanitizeText("Uncached input priced at the gap between the input and cache-read rates, plus cache writes the same session never read back, summed across main sessions. Cache writes that earned reads are excluded: they are the price of having a cache.")
|
|
2121
|
+
});
|
|
2122
|
+
covered.add("cache_hit");
|
|
2123
|
+
covered.add("cache_churn");
|
|
2124
|
+
covered.add("recoverable_exposure");
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
const idle = idleCacheExpiry(report);
|
|
2128
|
+
if (round23(idle.longIdleUsd) > 0 && idle.longIdleEvents > 0) {
|
|
2129
|
+
const hours = Math.round(idle.maxGapMinutes / 60);
|
|
2130
|
+
const gapPhrase = hours >= 1 ? ` The longest was about ${hours} ${hours === 1 ? "hour" : "hours"}.` : "";
|
|
2002
2131
|
fixes.push({
|
|
2003
|
-
id: "
|
|
2004
|
-
title: "
|
|
2005
|
-
pillar: "
|
|
2006
|
-
pillarName: PILLARS.
|
|
2007
|
-
severity: sevForUsd(
|
|
2008
|
-
wasteUsd: round23(
|
|
2132
|
+
id: "idle_cache_expiry",
|
|
2133
|
+
title: "Compact before you walk away from a session",
|
|
2134
|
+
pillar: "session_mgmt",
|
|
2135
|
+
pillarName: PILLARS.session_mgmt.name,
|
|
2136
|
+
severity: sevForUsd(idle.longIdleUsd),
|
|
2137
|
+
wasteUsd: round23(idle.longIdleUsd),
|
|
2009
2138
|
problem: sanitizeText(
|
|
2010
|
-
`${usd8(
|
|
2139
|
+
`${usd8(idle.longIdleUsd)} went to rebuilding a prompt prefix that had expired during a break of an hour or more, across ${idle.longIdleEvents} ${sWord(idle.longIdleEvents)}.${gapPhrase} Counting shorter pauses too, idle gaps cost ${usd8(idle.usd)} over ${idle.events} turns.`
|
|
2140
|
+
),
|
|
2141
|
+
action: sanitizeText(
|
|
2142
|
+
"The prompt cache lives about five minutes, so a session you come back to hours later re-buys its whole context on the next turn, and the bill is whatever that context weighed when you left. Compact or clear before stepping away, or start a fresh session when you return, so what gets rebuilt is small."
|
|
2011
2143
|
),
|
|
2012
|
-
|
|
2013
|
-
|
|
2144
|
+
basis: sanitizeText(
|
|
2145
|
+
"Cache-write premium on turns that followed the previous turn by more than the cache lifetime, summed across main sessions from request timestamps."
|
|
2146
|
+
)
|
|
2014
2147
|
});
|
|
2015
|
-
covered.add("
|
|
2016
|
-
covered.add("
|
|
2017
|
-
covered.add("recoverable_exposure");
|
|
2148
|
+
covered.add("session_scope");
|
|
2149
|
+
covered.add("session_marathon");
|
|
2018
2150
|
}
|
|
2019
2151
|
const singleSessionTools = [];
|
|
2020
2152
|
for (const [tool, e] of heavyByTool) {
|
|
@@ -2107,7 +2239,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
2107
2239
|
for (const p of pillars) {
|
|
2108
2240
|
for (const c of p.checks) {
|
|
2109
2241
|
if (!c.gap || covered.has(c.id)) continue;
|
|
2110
|
-
const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) :
|
|
2242
|
+
const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) : checkFix(c.id);
|
|
2111
2243
|
if (!tmpl) continue;
|
|
2112
2244
|
const severity = (c.score ?? 100) < 40 ? "warn" : "info";
|
|
2113
2245
|
fixes.push({
|
|
@@ -2128,10 +2260,15 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
2128
2260
|
if (severityRank(b.severity) !== severityRank(a.severity)) return severityRank(b.severity) - severityRank(a.severity);
|
|
2129
2261
|
return PILLARS[b.pillar].weight - PILLARS[a.pillar].weight;
|
|
2130
2262
|
});
|
|
2263
|
+
const pctOf = (n) => spend > 0 ? `${(n / spend * 100).toFixed(1)}%` : "0.0%";
|
|
2264
|
+
const verdict = spend <= 0 ? "No main-session spend was found in these logs, so there is nothing to judge yet." : exposureMaterial ? `${usd8(addressableUsd)} of your ${usd8(spend)} main-session spend (${pctOf(addressableUsd)}) is waste a setup change can reach. That is on top of ${usd8(coldStartUsd)} your first turns must pay whatever you do, and it is the number the fixes below go after.` : `Your caching is doing its job. Of ${usd8(spend)} main-session spend, only ${usd8(exposure)} (${pctOf(exposure)}) was recoverable at all, and ${usd8(coldStartUsd)} of that is the cold start every first turn pays. There is no cache change worth making here; look at model routing and tool loops instead.`;
|
|
2131
2265
|
return {
|
|
2132
2266
|
headlineWasteUsd,
|
|
2133
2267
|
headlineWasteLabel,
|
|
2134
2268
|
headlineWasteShare,
|
|
2269
|
+
coldStartUsd,
|
|
2270
|
+
addressableUsd,
|
|
2271
|
+
verdict,
|
|
2135
2272
|
fixes
|
|
2136
2273
|
};
|
|
2137
2274
|
}
|
|
@@ -2282,6 +2419,197 @@ function burnClock(report, offsetMinutes = 0, timeZone) {
|
|
|
2282
2419
|
return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
|
|
2283
2420
|
}
|
|
2284
2421
|
|
|
2422
|
+
// ../../packages/engine/src/select.ts
|
|
2423
|
+
function makeUnit(rawLines, kind) {
|
|
2424
|
+
const text2 = rawLines.join("\n").replace(/\s+$/, "");
|
|
2425
|
+
return { text: text2, tokens: Math.round(text2.length / 4), kind };
|
|
2426
|
+
}
|
|
2427
|
+
var FENCE_RE = /^```/;
|
|
2428
|
+
var BULLET_START_RE = /^(?:[-*]|\d+[.)])\s+/;
|
|
2429
|
+
var INDENTED_RE = /^\s+\S/;
|
|
2430
|
+
function splitUnits(section) {
|
|
2431
|
+
const lines = section.body.split(/\r?\n/);
|
|
2432
|
+
const units = [];
|
|
2433
|
+
let i = 0;
|
|
2434
|
+
while (i < lines.length) {
|
|
2435
|
+
const line = lines[i] ?? "";
|
|
2436
|
+
if (line.trim() === "") {
|
|
2437
|
+
i++;
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
if (FENCE_RE.test(line.trim())) {
|
|
2441
|
+
const block2 = [line];
|
|
2442
|
+
i++;
|
|
2443
|
+
while (i < lines.length && !FENCE_RE.test((lines[i] ?? "").trim())) {
|
|
2444
|
+
block2.push(lines[i]);
|
|
2445
|
+
i++;
|
|
2446
|
+
}
|
|
2447
|
+
if (i < lines.length) {
|
|
2448
|
+
block2.push(lines[i]);
|
|
2449
|
+
i++;
|
|
2450
|
+
}
|
|
2451
|
+
units.push(makeUnit(block2, "code"));
|
|
2452
|
+
continue;
|
|
2453
|
+
}
|
|
2454
|
+
if (BULLET_START_RE.test(line)) {
|
|
2455
|
+
const block2 = [line];
|
|
2456
|
+
i++;
|
|
2457
|
+
while (i < lines.length) {
|
|
2458
|
+
const next = lines[i] ?? "";
|
|
2459
|
+
if (next.trim() === "") {
|
|
2460
|
+
const after = lines[i + 1] ?? "";
|
|
2461
|
+
if (INDENTED_RE.test(after)) {
|
|
2462
|
+
block2.push(next);
|
|
2463
|
+
i++;
|
|
2464
|
+
continue;
|
|
2465
|
+
}
|
|
2466
|
+
break;
|
|
2467
|
+
}
|
|
2468
|
+
if (INDENTED_RE.test(next)) {
|
|
2469
|
+
block2.push(next);
|
|
2470
|
+
i++;
|
|
2471
|
+
continue;
|
|
2472
|
+
}
|
|
2473
|
+
break;
|
|
2474
|
+
}
|
|
2475
|
+
units.push(makeUnit(block2, "bullet"));
|
|
2476
|
+
continue;
|
|
2477
|
+
}
|
|
2478
|
+
const block = [line];
|
|
2479
|
+
i++;
|
|
2480
|
+
while (i < lines.length) {
|
|
2481
|
+
const next = lines[i] ?? "";
|
|
2482
|
+
if (next.trim() === "" || FENCE_RE.test(next.trim()) || BULLET_START_RE.test(next)) break;
|
|
2483
|
+
block.push(next);
|
|
2484
|
+
i++;
|
|
2485
|
+
}
|
|
2486
|
+
units.push(makeUnit(block, "paragraph"));
|
|
2487
|
+
}
|
|
2488
|
+
return units;
|
|
2489
|
+
}
|
|
2490
|
+
var NORMATIVE_MARKER = /\b(never|always|must|do not|don't|required|only|forbidden|prohibited|before you|after you)\b/i;
|
|
2491
|
+
var CONCRETE_ANCHOR = /`[^`]+`|(?:^|[\s(])\.{0,2}\/[\w./-]*|\b[\w-]+\/[\w./-]+|--[a-z][\w-]*|\b\d+(?:\.\d+)?\b/i;
|
|
2492
|
+
var CONCRETE_ANCHOR_G = new RegExp(CONCRETE_ANCHOR.source, "gi");
|
|
2493
|
+
var IMPERATIVE_VERBS = /* @__PURE__ */ new Set([
|
|
2494
|
+
"run",
|
|
2495
|
+
"use",
|
|
2496
|
+
"keep",
|
|
2497
|
+
"add",
|
|
2498
|
+
"avoid",
|
|
2499
|
+
"prefer",
|
|
2500
|
+
"ensure",
|
|
2501
|
+
"verify",
|
|
2502
|
+
"check",
|
|
2503
|
+
"set",
|
|
2504
|
+
"enable",
|
|
2505
|
+
"disable",
|
|
2506
|
+
"remove",
|
|
2507
|
+
"delete",
|
|
2508
|
+
"write",
|
|
2509
|
+
"read",
|
|
2510
|
+
"call",
|
|
2511
|
+
"treat",
|
|
2512
|
+
"confirm",
|
|
2513
|
+
"install",
|
|
2514
|
+
"configure",
|
|
2515
|
+
"enforce",
|
|
2516
|
+
"apply",
|
|
2517
|
+
"update",
|
|
2518
|
+
"validate",
|
|
2519
|
+
"sanitize",
|
|
2520
|
+
"escape",
|
|
2521
|
+
"format",
|
|
2522
|
+
"commit",
|
|
2523
|
+
"push",
|
|
2524
|
+
"merge",
|
|
2525
|
+
"scope",
|
|
2526
|
+
"limit",
|
|
2527
|
+
"cap",
|
|
2528
|
+
"batch",
|
|
2529
|
+
"invoke",
|
|
2530
|
+
"spawn",
|
|
2531
|
+
"route",
|
|
2532
|
+
"reuse",
|
|
2533
|
+
"cache",
|
|
2534
|
+
"clear",
|
|
2535
|
+
"compact",
|
|
2536
|
+
"state",
|
|
2537
|
+
"branch",
|
|
2538
|
+
"start",
|
|
2539
|
+
"stop",
|
|
2540
|
+
"handle"
|
|
2541
|
+
]);
|
|
2542
|
+
function firstWord(text2) {
|
|
2543
|
+
const firstLine = text2.split(/\r?\n/)[0] ?? "";
|
|
2544
|
+
const stripped = firstLine.replace(/^\s*(?:[-*]|\d+[.)])\s+/, "").trim();
|
|
2545
|
+
const m = stripped.match(/^[A-Za-z']+/);
|
|
2546
|
+
return m ? m[0].toLowerCase() : "";
|
|
2547
|
+
}
|
|
2548
|
+
function isImperativeDirective(u) {
|
|
2549
|
+
return u.kind !== "code" && IMPERATIVE_VERBS.has(firstWord(u.text));
|
|
2550
|
+
}
|
|
2551
|
+
function classifyUnit(u) {
|
|
2552
|
+
if (NORMATIVE_MARKER.test(u.text) || isImperativeDirective(u)) return "rule";
|
|
2553
|
+
if (u.kind === "code" || CONCRETE_ANCHOR.test(u.text)) return "fact";
|
|
2554
|
+
return "prose";
|
|
2555
|
+
}
|
|
2556
|
+
function anchorScore(u) {
|
|
2557
|
+
if (u.kind === "code") return 1;
|
|
2558
|
+
const matches = u.text.match(CONCRETE_ANCHOR_G);
|
|
2559
|
+
return Math.max(1, matches?.length ?? 0);
|
|
2560
|
+
}
|
|
2561
|
+
function densityDescending(a, b) {
|
|
2562
|
+
const da = anchorScore(a.unit) / a.unit.tokens;
|
|
2563
|
+
const db = anchorScore(b.unit) / b.unit.tokens;
|
|
2564
|
+
if (db !== da) return db - da;
|
|
2565
|
+
return a.order - b.order;
|
|
2566
|
+
}
|
|
2567
|
+
function selectUnits(sections, budgetTokens) {
|
|
2568
|
+
const entries = [];
|
|
2569
|
+
let order = 0;
|
|
2570
|
+
for (const section of sections) {
|
|
2571
|
+
for (const unit of splitUnits(section)) {
|
|
2572
|
+
entries.push({ section, unit, tier: classifyUnit(unit), order: order++ });
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
const kept = /* @__PURE__ */ new Set();
|
|
2576
|
+
let used = 0;
|
|
2577
|
+
for (const e of entries) {
|
|
2578
|
+
if (e.tier !== "rule") continue;
|
|
2579
|
+
if (used + e.unit.tokens > budgetTokens) break;
|
|
2580
|
+
kept.add(e);
|
|
2581
|
+
used += e.unit.tokens;
|
|
2582
|
+
}
|
|
2583
|
+
for (const tier of ["fact", "prose"]) {
|
|
2584
|
+
const candidates = entries.filter((e) => e.tier === tier && !kept.has(e)).sort(densityDescending);
|
|
2585
|
+
for (const e of candidates) {
|
|
2586
|
+
if (used + e.unit.tokens > budgetTokens) continue;
|
|
2587
|
+
kept.add(e);
|
|
2588
|
+
used += e.unit.tokens;
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
const droppedEntries = entries.filter((e) => !kept.has(e));
|
|
2592
|
+
const droppedTokens = droppedEntries.reduce((sum, e) => sum + e.unit.tokens, 0);
|
|
2593
|
+
const dropped = droppedEntries.map((e) => ({
|
|
2594
|
+
heading: e.section.heading,
|
|
2595
|
+
kind: e.tier,
|
|
2596
|
+
tokens: e.unit.tokens
|
|
2597
|
+
}));
|
|
2598
|
+
const keptSections = [];
|
|
2599
|
+
for (const section of sections) {
|
|
2600
|
+
const keptForSection = entries.filter((e) => e.section === section && kept.has(e)).map((e) => e.unit);
|
|
2601
|
+
if (keptForSection.length === 0) continue;
|
|
2602
|
+
const body = keptForSection.map((u) => u.text).join("\n\n");
|
|
2603
|
+
keptSections.push({
|
|
2604
|
+
heading: section.heading,
|
|
2605
|
+
body,
|
|
2606
|
+
tokens: Math.round(body.length / 4),
|
|
2607
|
+
volatileLines: body.split(/\r?\n/).filter((l) => VOLATILE_MARKER.test(l)).length
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2610
|
+
return { kept: keptSections, droppedTokens, dropped };
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2285
2613
|
// ../../packages/engine/src/optimize.ts
|
|
2286
2614
|
function usd(n) {
|
|
2287
2615
|
const rounded = Math.round(n * 100) / 100;
|
|
@@ -2293,7 +2621,7 @@ function usd(n) {
|
|
|
2293
2621
|
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
2294
2622
|
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
2295
2623
|
}
|
|
2296
|
-
function
|
|
2624
|
+
function num3(n) {
|
|
2297
2625
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
2298
2626
|
}
|
|
2299
2627
|
function clean(text2) {
|
|
@@ -2376,6 +2704,8 @@ function carriedSections(currentClaudeMd) {
|
|
|
2376
2704
|
const out = {
|
|
2377
2705
|
workflow: null,
|
|
2378
2706
|
architecture: null,
|
|
2707
|
+
workflowHeading: null,
|
|
2708
|
+
architectureHeading: null,
|
|
2379
2709
|
other: [],
|
|
2380
2710
|
droppedVolatile: [],
|
|
2381
2711
|
replaced: [],
|
|
@@ -2394,10 +2724,12 @@ function carriedSections(currentClaudeMd) {
|
|
|
2394
2724
|
}
|
|
2395
2725
|
} else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
|
|
2396
2726
|
out.workflow = section.body;
|
|
2727
|
+
out.workflowHeading = section.heading;
|
|
2397
2728
|
out.carriedTokens += section.tokens;
|
|
2398
2729
|
out.carriedList.push(section);
|
|
2399
2730
|
} else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
|
|
2400
2731
|
out.architecture = section.body;
|
|
2732
|
+
out.architectureHeading = section.heading;
|
|
2401
2733
|
out.carriedTokens += section.tokens;
|
|
2402
2734
|
out.carriedList.push(section);
|
|
2403
2735
|
} else {
|
|
@@ -2484,37 +2816,8 @@ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy)
|
|
|
2484
2816
|
function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
|
|
2485
2817
|
const { currentClaudeMd, project } = input;
|
|
2486
2818
|
const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
|
|
2487
|
-
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.";
|
|
2488
2819
|
const parts = [];
|
|
2489
|
-
parts.push(
|
|
2490
|
-
[
|
|
2491
|
-
"<!--",
|
|
2492
|
-
" CLAUDE.md scaffold generated by CostClaw (https://costclaw.io).",
|
|
2493
|
-
"",
|
|
2494
|
-
" How to use this file:",
|
|
2495
|
-
" - Replace every placeholder comment with your project's real details, then",
|
|
2496
|
-
" delete any line that does not earn its place.",
|
|
2497
|
-
' - Keep it lean, but do not cut to a line count. For each line ask "would',
|
|
2498
|
-
' removing this make the agent make a mistake?" If not, cut it.',
|
|
2499
|
-
" - Only include what the agent cannot infer from the code: commands it cannot",
|
|
2500
|
-
" guess, conventions that differ from the language defaults, and non-obvious",
|
|
2501
|
-
" gotchas. Skip anything self-evident.",
|
|
2502
|
-
"",
|
|
2503
|
-
" Why this matters for cost:",
|
|
2504
|
-
" - Claude Code reads CLAUDE.md once at the start of a session and re-reads it",
|
|
2505
|
-
" from the prompt cache on every later turn at roughly a tenth of the input",
|
|
2506
|
-
" price. A small, stable file is cheap to cache and reuse; a bloated, churny",
|
|
2507
|
-
" one inflates every turn.",
|
|
2508
|
-
" - Keep volatile content (dates, TODOs, status notes, version numbers) out of",
|
|
2509
|
-
" this file. Put churn in a scratch note the agent opens on demand, or a",
|
|
2510
|
-
" path-scoped rule under .claude/rules/.",
|
|
2511
|
-
recoverableLine,
|
|
2512
|
-
" - Things that must happen every time (lint before commit, blocking a path)",
|
|
2513
|
-
" belong in a hook, not here: CLAUDE.md is context the agent usually follows,",
|
|
2514
|
-
" not an enforced rule.",
|
|
2515
|
-
"-->"
|
|
2516
|
-
].join("\n")
|
|
2517
|
-
);
|
|
2820
|
+
parts.push("<!-- Generated by CostClaw. Why each section is here: .claude/costclaw/PLAYBOOK.md -->");
|
|
2518
2821
|
const filled = [];
|
|
2519
2822
|
const projectName = project?.name?.trim() || null;
|
|
2520
2823
|
const titleText = projectName ?? title ?? "Project name";
|
|
@@ -2960,11 +3263,12 @@ function claudeMdReceiptLine(claudeMdTokens) {
|
|
|
2960
3263
|
const grew = delta > 0;
|
|
2961
3264
|
const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
|
|
2962
3265
|
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.";
|
|
2963
|
-
return `Your optimized CLAUDE.md goes from an estimated ${
|
|
3266
|
+
return `Your optimized CLAUDE.md goes from an estimated ${num3(before)} tokens to ${num3(after)}${pct2}. ${tail}`;
|
|
2964
3267
|
}
|
|
2965
3268
|
function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
|
|
2966
3269
|
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
|
|
2967
3270
|
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
3271
|
+
const coldStart = coldStartExposureUsd(report);
|
|
2968
3272
|
const parts = [];
|
|
2969
3273
|
parts.push("# CostClaw fix playbook");
|
|
2970
3274
|
const projectName = project?.name?.trim();
|
|
@@ -2973,13 +3277,22 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
|
|
|
2973
3277
|
parts.push(
|
|
2974
3278
|
[
|
|
2975
3279
|
...projectLine ? [projectLine, ""] : [],
|
|
2976
|
-
`
|
|
3280
|
+
`Recoverable waste estimate: ${usd(recoverable)} at current API list prices, of which ${usd(coldStart)} is the cold start your first turns pay whatever you change.`,
|
|
2977
3281
|
"",
|
|
2978
|
-
"This is the ranked plan from your audit. Priority suggestions are ordered by
|
|
3282
|
+
"This is the ranked plan from your audit. Priority suggestions are ordered by estimated value, followed by rule-based setup warnings. Cache writes that earned their reads back are excluded: paying to build a cache you then read from is the mechanism working, not waste."
|
|
2979
3283
|
].join("\n")
|
|
2980
3284
|
);
|
|
2981
3285
|
const receipt = claudeMdReceiptLine(claudeMdTokens);
|
|
2982
3286
|
if (receipt) parts.push(receipt);
|
|
3287
|
+
parts.push([
|
|
3288
|
+
"## How to keep this file lean",
|
|
3289
|
+
"",
|
|
3290
|
+
'- Cut by question, not by line count. For each line ask "would removing this make the agent make a mistake?" If not, cut it.',
|
|
3291
|
+
"- Only keep what the agent cannot infer from the code: commands it could not guess, conventions that differ from the language defaults, and non-obvious gotchas.",
|
|
3292
|
+
"- Keep volatile content out. Dates, TODOs, status notes and version numbers change between sessions and reset the cached prefix, so the next session re-pays for the whole file.",
|
|
3293
|
+
"- Things that must happen every time (lint before commit, blocking a path) belong in a hook. CLAUDE.md is context the agent usually follows, not an enforced rule.",
|
|
3294
|
+
recoverable >= 1 ? `- Your audit put ${usd(recoverable)} of recoverable waste in reach. A small, stable file is part of that; the ranked fixes below are the rest.` : "- A small, stable file keeps the cached prefix cheap to reuse on every later turn."
|
|
3295
|
+
].join("\n"));
|
|
2983
3296
|
dollarFixes.forEach((fix, i) => {
|
|
2984
3297
|
parts.push(renderDollarFix(fix, i + 1));
|
|
2985
3298
|
if (fix.id === "cache_recovery") {
|
|
@@ -3103,12 +3416,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3103
3416
|
if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
|
|
3104
3417
|
const rows = worklist.map((s) => {
|
|
3105
3418
|
const n2 = s.volatileLines;
|
|
3106
|
-
const dated = n2 > 0 ? `, ${
|
|
3107
|
-
return `- ${s.heading}: est. ${
|
|
3419
|
+
const dated = n2 > 0 ? `, ${num3(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
|
|
3420
|
+
return `- ${s.heading}: est. ${num3(s.tokens)} tokens${dated}.`;
|
|
3108
3421
|
});
|
|
3109
3422
|
const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
|
|
3110
3423
|
const rest = carried.carriedList.length - worklist.length;
|
|
3111
|
-
const tail = rest > 0 ? [`The remaining ${
|
|
3424
|
+
const tail = rest > 0 ? [`The remaining ${num3(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num3(carried.carriedTokens - shown)} tokens.`] : [];
|
|
3112
3425
|
const before = claudeMdTokens.before;
|
|
3113
3426
|
const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
|
|
3114
3427
|
const consequence = saved <= 0 ? "that is why the optimized file is no smaller." : saved < 0.2 ? "that is why the optimized file is barely smaller." : "it is the weight that is left.";
|
|
@@ -3116,7 +3429,7 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3116
3429
|
[
|
|
3117
3430
|
`## Task ${n++}: Reclaim the carried sections`,
|
|
3118
3431
|
"",
|
|
3119
|
-
`Your CLAUDE.md carries an estimated ${
|
|
3432
|
+
`Your CLAUDE.md carries an estimated ${num3(carried.carriedTokens)} tokens of your`,
|
|
3120
3433
|
"own prose, paid on every turn of every session.",
|
|
3121
3434
|
`costclaw does not rewrite your prose, so it passed all of it through untouched:`,
|
|
3122
3435
|
`${consequence} Doing the actual trimming is this task,`,
|
|
@@ -3226,15 +3539,43 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3226
3539
|
parts.push(verify.join("\n"));
|
|
3227
3540
|
return clean(parts.join("\n\n").trimEnd() + "\n");
|
|
3228
3541
|
}
|
|
3542
|
+
var CARRIED_BUDGET_FRACTION = 0.6;
|
|
3543
|
+
function clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore) {
|
|
3544
|
+
if (claudeMdBefore == null) return requestedBudget;
|
|
3545
|
+
const empty = { ...carried, workflow: null, architecture: null, other: [] };
|
|
3546
|
+
const floorMd = buildClaudeMd(input, recoverable, [], { placeholders: 0 }, empty, []);
|
|
3547
|
+
const floorTokens = Math.round(floorMd.trim().length / 4);
|
|
3548
|
+
const room = claudeMdBefore - floorTokens;
|
|
3549
|
+
if (room <= 0) return requestedBudget;
|
|
3550
|
+
return Math.min(requestedBudget, room);
|
|
3551
|
+
}
|
|
3552
|
+
function tierCounts(sections) {
|
|
3553
|
+
const counts = { rule: 0, fact: 0, prose: 0 };
|
|
3554
|
+
for (const section of sections) {
|
|
3555
|
+
for (const unit of splitUnits(section)) counts[classifyUnit(unit)]++;
|
|
3556
|
+
}
|
|
3557
|
+
return counts;
|
|
3558
|
+
}
|
|
3229
3559
|
function optimize(input) {
|
|
3230
3560
|
const recoverable = cacheMissExposureUsd(input.report);
|
|
3231
3561
|
const notes = [];
|
|
3232
3562
|
const stats = { placeholders: 0 };
|
|
3233
3563
|
const carried = carriedSections(input.currentClaudeMd);
|
|
3234
3564
|
const dispositions = [];
|
|
3235
|
-
const
|
|
3565
|
+
const claudeMdBefore = input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null;
|
|
3566
|
+
const requestedBudget = input.maxTokens ?? Math.round(carried.carriedTokens * CARRIED_BUDGET_FRACTION);
|
|
3567
|
+
const budgetTokens = clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore);
|
|
3568
|
+
const selection = selectUnits(carried.carriedList, budgetTokens);
|
|
3569
|
+
const keptByHeading = new Map(selection.kept.map((s) => [s.heading, s]));
|
|
3570
|
+
const carriedForBuild = {
|
|
3571
|
+
...carried,
|
|
3572
|
+
workflow: carried.workflowHeading ? keptByHeading.get(carried.workflowHeading)?.body ?? null : null,
|
|
3573
|
+
architecture: carried.architectureHeading ? keptByHeading.get(carried.architectureHeading)?.body ?? null : null,
|
|
3574
|
+
other: carried.other.map((s) => keptByHeading.get(s.heading)).filter((s) => s != null)
|
|
3575
|
+
};
|
|
3576
|
+
const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carriedForBuild, dispositions);
|
|
3236
3577
|
const claudeMdTokens = {
|
|
3237
|
-
before:
|
|
3578
|
+
before: claudeMdBefore,
|
|
3238
3579
|
after: Math.round(optimizedClaudeMd.trim().length / 4)
|
|
3239
3580
|
};
|
|
3240
3581
|
const carriedTokens = carried.carriedTokens;
|
|
@@ -3242,6 +3583,21 @@ function optimize(input) {
|
|
|
3242
3583
|
const settingsJson = buildSettings(input.project);
|
|
3243
3584
|
const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
|
|
3244
3585
|
const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
|
|
3586
|
+
const totalByTier = tierCounts(carried.carriedList);
|
|
3587
|
+
const droppedByTier = { rule: 0, fact: 0, prose: 0 };
|
|
3588
|
+
for (const d of selection.dropped) droppedByTier[d.kind]++;
|
|
3589
|
+
const keptByTier = {
|
|
3590
|
+
rule: totalByTier.rule - droppedByTier.rule,
|
|
3591
|
+
fact: totalByTier.fact - droppedByTier.fact,
|
|
3592
|
+
prose: totalByTier.prose - droppedByTier.prose
|
|
3593
|
+
};
|
|
3594
|
+
const selectionResult = {
|
|
3595
|
+
budgetTokens,
|
|
3596
|
+
keptTokens: selection.kept.reduce((sum, s) => sum + s.tokens, 0),
|
|
3597
|
+
droppedTokens: selection.droppedTokens,
|
|
3598
|
+
keptByTier,
|
|
3599
|
+
droppedByTier
|
|
3600
|
+
};
|
|
3245
3601
|
const cleanNotes = notes.map((n) => clean(n));
|
|
3246
3602
|
const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
|
|
3247
3603
|
if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || hasEmDash(includeMd) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
|
|
@@ -3256,7 +3612,8 @@ function optimize(input) {
|
|
|
3256
3612
|
placeholdersRemaining: stats.placeholders,
|
|
3257
3613
|
claudeMdTokens,
|
|
3258
3614
|
carriedTokens,
|
|
3259
|
-
sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
|
|
3615
|
+
sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) })),
|
|
3616
|
+
selection: selectionResult
|
|
3260
3617
|
};
|
|
3261
3618
|
}
|
|
3262
3619
|
return {
|
|
@@ -3270,7 +3627,8 @@ function optimize(input) {
|
|
|
3270
3627
|
placeholdersRemaining: stats.placeholders,
|
|
3271
3628
|
claudeMdTokens,
|
|
3272
3629
|
carriedTokens,
|
|
3273
|
-
sectionDispositions: cleanDispositions
|
|
3630
|
+
sectionDispositions: cleanDispositions,
|
|
3631
|
+
selection: selectionResult
|
|
3274
3632
|
};
|
|
3275
3633
|
}
|
|
3276
3634
|
|
|
@@ -3356,6 +3714,15 @@ function cleanFix(f) {
|
|
|
3356
3714
|
wasteUsd: round2(f.wasteUsd)
|
|
3357
3715
|
};
|
|
3358
3716
|
}
|
|
3717
|
+
function roundIdle(i) {
|
|
3718
|
+
return {
|
|
3719
|
+
usd: round2(i.usd),
|
|
3720
|
+
events: i.events,
|
|
3721
|
+
longIdleUsd: round2(i.longIdleUsd),
|
|
3722
|
+
longIdleEvents: i.longIdleEvents,
|
|
3723
|
+
maxGapMinutes: Math.round(i.maxGapMinutes)
|
|
3724
|
+
};
|
|
3725
|
+
}
|
|
3359
3726
|
function cleanCheck(c) {
|
|
3360
3727
|
return { ...c, basis: sanitizeText(c.basis) };
|
|
3361
3728
|
}
|
|
@@ -3367,7 +3734,7 @@ function buildAudit(input, opts = {}) {
|
|
|
3367
3734
|
const cmd2 = analyzeClaudeMd(input.claudeMd);
|
|
3368
3735
|
const { pillars, overall, band } = scorePillars(report, cmd2, input.questionnaire, input.setup);
|
|
3369
3736
|
const plan = input.plan ?? "api";
|
|
3370
|
-
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd2, plan);
|
|
3737
|
+
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, coldStartUsd, addressableUsd, verdict, fixes } = synthesize(report, pillars, cmd2, plan);
|
|
3371
3738
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
3372
3739
|
return {
|
|
3373
3740
|
schemaVersion: "1",
|
|
@@ -3388,6 +3755,11 @@ function buildAudit(input, opts = {}) {
|
|
|
3388
3755
|
headlineWasteLabel: sanitizeText(headlineWasteLabel),
|
|
3389
3756
|
plan,
|
|
3390
3757
|
headlineWasteShare: round4(headlineWasteShare),
|
|
3758
|
+
coldStartUsd: round2(coldStartUsd),
|
|
3759
|
+
addressableUsd: round2(addressableUsd),
|
|
3760
|
+
cacheWriteCostUsd: round2(cacheWriteCostUsd(report)),
|
|
3761
|
+
verdict: sanitizeText(verdict),
|
|
3762
|
+
idleCacheExpiry: roundIdle(idleCacheExpiry(report)),
|
|
3391
3763
|
usageWindows: roundWindows(computeWindowStats(report)),
|
|
3392
3764
|
burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0, input.timeZone)),
|
|
3393
3765
|
fixes: fixes.map(cleanFix),
|
|
@@ -3536,7 +3908,7 @@ var IMPORT_LINE = "@.claude/costclaw.md";
|
|
|
3536
3908
|
function estTokens(text2) {
|
|
3537
3909
|
return Math.round(text2.length / 4);
|
|
3538
3910
|
}
|
|
3539
|
-
function
|
|
3911
|
+
function num4(n) {
|
|
3540
3912
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3541
3913
|
}
|
|
3542
3914
|
function normalize(line) {
|
|
@@ -3639,7 +4011,7 @@ function markVolatile(lines, sections, b, destDir) {
|
|
|
3639
4011
|
id,
|
|
3640
4012
|
kind: "move",
|
|
3641
4013
|
heading: s.heading,
|
|
3642
|
-
instruction: `Move the ${
|
|
4014
|
+
instruction: `Move the ${num4(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
|
|
3643
4015
|
reason: VOLATILE_WHY,
|
|
3644
4016
|
tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
|
|
3645
4017
|
destination: dest
|
|
@@ -3776,8 +4148,8 @@ function reviewProjectClaudeMd(input) {
|
|
|
3776
4148
|
id,
|
|
3777
4149
|
kind: "remove",
|
|
3778
4150
|
heading: s.heading,
|
|
3779
|
-
instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${
|
|
3780
|
-
reason: `${
|
|
4151
|
+
instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${num4(covered.length)} covered ${covered.length === 1 ? "line" : "lines"} under "${s.heading}" and keep these ${num4(kept)} lines under the heading: the include ${IMPORT_LINE} does not have them.`,
|
|
4152
|
+
reason: `${num4(covered.length)} of ${num4(content.length)} lines appear verbatim in the generated include`,
|
|
3781
4153
|
tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
|
|
3782
4154
|
});
|
|
3783
4155
|
}
|
|
@@ -3901,8 +4273,8 @@ function reviewGlobalClaudeMd(input) {
|
|
|
3901
4273
|
id,
|
|
3902
4274
|
kind: "move",
|
|
3903
4275
|
heading: "(top)",
|
|
3904
|
-
instruction: `Split ${heaviest.label} (about ${
|
|
3905
|
-
reason: `this file plus its imports is about ${
|
|
4276
|
+
instruction: `Split ${heaviest.label} (about ${num4(estTokens(heaviest.text))} tokens) into docs the agent opens on demand, and keep only the rules that prevent mistakes.`,
|
|
4277
|
+
reason: `this file plus its imports is about ${num4(total)} tokens on every turn of every project`,
|
|
3906
4278
|
tokens: 0,
|
|
3907
4279
|
destination: "on-demand docs"
|
|
3908
4280
|
});
|
|
@@ -3922,7 +4294,7 @@ function changeList(review) {
|
|
|
3922
4294
|
const out = [];
|
|
3923
4295
|
review.changes.forEach((c, i) => {
|
|
3924
4296
|
const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
|
|
3925
|
-
const weight = c.tokens > 0 ? `, about ${
|
|
4297
|
+
const weight = c.tokens > 0 ? `, about ${num4(c.tokens)} tokens` : "";
|
|
3926
4298
|
out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
|
|
3927
4299
|
out.push(` Why: ${c.reason}`);
|
|
3928
4300
|
if (c.destination) out.push(` Destination: ${c.destination}`);
|
|
@@ -3936,7 +4308,7 @@ function changeList(review) {
|
|
|
3936
4308
|
return out;
|
|
3937
4309
|
}
|
|
3938
4310
|
function tokenTarget(review, what) {
|
|
3939
|
-
return `- ${what}: about ${
|
|
4311
|
+
return `- ${what}: about ${num4(review.tokens.afterChanges)} tokens per turn after these changes (about ${num4(review.tokens.total)} now).`;
|
|
3940
4312
|
}
|
|
3941
4313
|
function buildUpgradeAll(input) {
|
|
3942
4314
|
const parts = [];
|
|
@@ -3959,7 +4331,7 @@ function buildUpgradeAll(input) {
|
|
|
3959
4331
|
parts.push([
|
|
3960
4332
|
`## Global: ${input.global.path}`,
|
|
3961
4333
|
"",
|
|
3962
|
-
input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${
|
|
4334
|
+
input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${num4(input.global.changes.length)} ${input.global.changes.length === 1 ? "change" : "changes"} proposed.`,
|
|
3963
4335
|
"",
|
|
3964
4336
|
...changeList(input.global)
|
|
3965
4337
|
].join("\n"));
|
|
@@ -3990,7 +4362,7 @@ function buildUpgradeAll(input) {
|
|
|
3990
4362
|
|
|
3991
4363
|
// src/audit-command.ts
|
|
3992
4364
|
import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
3993
|
-
import { join as join5, resolve } from "path";
|
|
4365
|
+
import { join as join5, resolve as resolve2 } from "path";
|
|
3994
4366
|
import { homedir as homedir4 } from "os";
|
|
3995
4367
|
|
|
3996
4368
|
// src/open.ts
|
|
@@ -4010,8 +4382,8 @@ function openInBrowser(target) {
|
|
|
4010
4382
|
|
|
4011
4383
|
// src/read-sessions.ts
|
|
4012
4384
|
import { readdir } from "fs/promises";
|
|
4013
|
-
import { readFileSync, openSync, closeSync, readSync } from "fs";
|
|
4014
|
-
import { join, relative, sep } from "path";
|
|
4385
|
+
import { readFileSync, openSync, closeSync, readSync, statSync } from "fs";
|
|
4386
|
+
import { basename, dirname, join, relative, resolve, sep } from "path";
|
|
4015
4387
|
import { homedir } from "os";
|
|
4016
4388
|
function defaultProjectsPath() {
|
|
4017
4389
|
return process.env.CLAUDE_PROJECTS_PATH || join(homedir(), ".claude", "projects");
|
|
@@ -4055,6 +4427,45 @@ function lazyLog(full, meta) {
|
|
|
4055
4427
|
}
|
|
4056
4428
|
var CWD_PROBE_BYTES = 65536;
|
|
4057
4429
|
var CWD_PROBE_LINES = 40;
|
|
4430
|
+
function repoRootFor(startDir) {
|
|
4431
|
+
let dir;
|
|
4432
|
+
try {
|
|
4433
|
+
dir = resolve(startDir);
|
|
4434
|
+
} catch {
|
|
4435
|
+
return null;
|
|
4436
|
+
}
|
|
4437
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
4438
|
+
const dotGit = join(dir, ".git");
|
|
4439
|
+
let stat4;
|
|
4440
|
+
try {
|
|
4441
|
+
stat4 = statSync(dotGit);
|
|
4442
|
+
} catch {
|
|
4443
|
+
const parent2 = dirname(dir);
|
|
4444
|
+
if (parent2 === dir) return null;
|
|
4445
|
+
dir = parent2;
|
|
4446
|
+
continue;
|
|
4447
|
+
}
|
|
4448
|
+
if (stat4.isDirectory()) return dir;
|
|
4449
|
+
if (stat4.isFile()) {
|
|
4450
|
+
try {
|
|
4451
|
+
const pointer = readFileSync(dotGit, "utf8").trim();
|
|
4452
|
+
const match = /^gitdir:\s*(.+)$/m.exec(pointer);
|
|
4453
|
+
const gitDir = match?.[1]?.trim();
|
|
4454
|
+
if (gitDir) {
|
|
4455
|
+
const parts = resolve(gitDir).split(/[\\/]+/);
|
|
4456
|
+
const idx = parts.lastIndexOf(".git");
|
|
4457
|
+
if (idx > 0) return parts.slice(0, idx).join(sep);
|
|
4458
|
+
}
|
|
4459
|
+
} catch {
|
|
4460
|
+
}
|
|
4461
|
+
return dir;
|
|
4462
|
+
}
|
|
4463
|
+
const parent = dirname(dir);
|
|
4464
|
+
if (parent === dir) return null;
|
|
4465
|
+
dir = parent;
|
|
4466
|
+
}
|
|
4467
|
+
return null;
|
|
4468
|
+
}
|
|
4058
4469
|
function projectNameFromLogs(files) {
|
|
4059
4470
|
for (const full of files.slice(0, 3)) {
|
|
4060
4471
|
let fd;
|
|
@@ -4109,8 +4520,10 @@ async function readSessions(rootPath) {
|
|
|
4109
4520
|
}
|
|
4110
4521
|
const files = await collectJsonl(projPath);
|
|
4111
4522
|
const probe = projectNameFromLogs(files);
|
|
4112
|
-
const
|
|
4113
|
-
|
|
4523
|
+
const repoRoot = probe ? repoRootFor(probe.cwd) : null;
|
|
4524
|
+
const resolvedSlug = repoRoot ? basename(repoRoot) : probe?.slug;
|
|
4525
|
+
const projectSlug = resolvedSlug || dir.name;
|
|
4526
|
+
if (probe && !projectDirs.has(projectSlug)) projectDirs.set(projectSlug, repoRoot ?? probe.cwd);
|
|
4114
4527
|
for (const full of files) {
|
|
4115
4528
|
const rel = relative(projPath, full).split(sep).join("/");
|
|
4116
4529
|
const name = `${dir.name}/${rel}`;
|
|
@@ -4284,6 +4697,14 @@ function unassessedLine(pillars) {
|
|
|
4284
4697
|
});
|
|
4285
4698
|
return `Not yet scored: ${parts.join(" ")}`;
|
|
4286
4699
|
}
|
|
4700
|
+
function weakestGap(p) {
|
|
4701
|
+
let worst = null;
|
|
4702
|
+
for (const c of p.checks) {
|
|
4703
|
+
if (!c.assessed || c.score == null || !c.gap) continue;
|
|
4704
|
+
if (!worst || c.score < worst.score) worst = c;
|
|
4705
|
+
}
|
|
4706
|
+
return worst;
|
|
4707
|
+
}
|
|
4287
4708
|
function formatAudit(record, meta, color = false) {
|
|
4288
4709
|
const a = ansi(color);
|
|
4289
4710
|
const m = record.usageMetrics;
|
|
@@ -4304,8 +4725,12 @@ function formatAudit(record, meta, color = false) {
|
|
|
4304
4725
|
lines.push(a.dim("-".repeat(WRAP_WIDTH)));
|
|
4305
4726
|
lines.push("");
|
|
4306
4727
|
lines.push(
|
|
4307
|
-
subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd2(record.headlineWasteUsd)}
|
|
4728
|
+
subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd2(record.headlineWasteUsd)} API-equivalent)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd))}`
|
|
4308
4729
|
);
|
|
4730
|
+
if (record.verdict) {
|
|
4731
|
+
lines.push("");
|
|
4732
|
+
pushProse(lines, record.verdict);
|
|
4733
|
+
}
|
|
4309
4734
|
const receipt = sinceOptimizeLine(meta);
|
|
4310
4735
|
if (receipt) pushProse(lines, receipt, 0, a.dim);
|
|
4311
4736
|
lines.push("");
|
|
@@ -4319,17 +4744,24 @@ function formatAudit(record, meta, color = false) {
|
|
|
4319
4744
|
[
|
|
4320
4745
|
{ k: "Pricing snapshot", v: m.pricingSnapshotDate },
|
|
4321
4746
|
...mix ? [{ k: "Model spend", v: mix }] : []
|
|
4322
|
-
]
|
|
4747
|
+
],
|
|
4748
|
+
// Named explicitly because this figure used to sit inside the headline as
|
|
4749
|
+
// if it were waste. It is the cache paying for itself.
|
|
4750
|
+
...record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? [[{ k: "Cache writes that earned their reads (working cost, not waste)", v: usd2(record.cacheWriteCostUsd) }]] : []
|
|
4323
4751
|
];
|
|
4324
4752
|
for (const row of statRows(statBlock, a)) lines.push(row);
|
|
4325
|
-
|
|
4326
|
-
if (
|
|
4753
|
+
const cautions = accuracyNotes(record);
|
|
4754
|
+
if (cautions.length === 1) pushProse(lines, `Pricing caution: ${cautions[0]}`, 0, a.dim);
|
|
4755
|
+
else if (cautions.length > 1) {
|
|
4756
|
+
pushProse(lines, `Pricing caution: ${cautions[0]} (${cautions.length - 1} more in --json)`, 0, a.dim);
|
|
4757
|
+
}
|
|
4758
|
+
if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid recoverable-waste share; its percentage is unavailable.", 0, a.dim);
|
|
4327
4759
|
const w = record.usageWindows;
|
|
4328
4760
|
if (subscription) {
|
|
4329
4761
|
lines.push("");
|
|
4330
4762
|
pushProse(
|
|
4331
4763
|
lines,
|
|
4332
|
-
`Plan: ${record.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.
|
|
4764
|
+
`Plan: ${record.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work. Recoverable waste is a counterfactual: a session's first turn has no cache to read from.`,
|
|
4333
4765
|
0,
|
|
4334
4766
|
a.dim
|
|
4335
4767
|
);
|
|
@@ -4387,17 +4819,24 @@ function formatAudit(record, meta, color = false) {
|
|
|
4387
4819
|
);
|
|
4388
4820
|
for (const p of record.pillarScores) {
|
|
4389
4821
|
lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
|
|
4822
|
+
const weak = weakestGap(p);
|
|
4823
|
+
if (!weak) continue;
|
|
4824
|
+
lines.push(` ${a.dim("Weakest:")} ${weak.label} (${weak.score})`);
|
|
4825
|
+
pushProse(lines, weak.basis, 4, a.dim);
|
|
4826
|
+
if (weak.action) pushProse(lines, `Do this: ${weak.action}`, 4);
|
|
4827
|
+
lines.push("");
|
|
4390
4828
|
}
|
|
4391
4829
|
lines.push("");
|
|
4392
4830
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
|
|
4393
4831
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
4394
|
-
lines.push(a.bold("Top changes ranked by
|
|
4832
|
+
lines.push(a.bold("Top changes, ranked by what they recover:"));
|
|
4395
4833
|
if (dollarFixes.length === 0) {
|
|
4396
|
-
lines.push(" No
|
|
4834
|
+
lines.push(" No recoverable waste was found. See the issues below.");
|
|
4397
4835
|
} else {
|
|
4398
4836
|
for (const [i, f] of dollarFixes.entries()) {
|
|
4399
4837
|
if (i > 0) lines.push("");
|
|
4400
4838
|
lines.push(` - [${a.brand(usd2(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
|
|
4839
|
+
if (f.problem) pushProse(lines, f.problem, 6);
|
|
4401
4840
|
pushProse(lines, f.action, 6);
|
|
4402
4841
|
if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
|
|
4403
4842
|
}
|
|
@@ -4420,7 +4859,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
4420
4859
|
lines.push(a.dim(gapLine));
|
|
4421
4860
|
}
|
|
4422
4861
|
lines.push("");
|
|
4423
|
-
const methodology = "Methodology: amounts are list-price estimates from logged token fields using the current pricing snapshot.
|
|
4862
|
+
const methodology = "Methodology: amounts are list-price estimates from logged token fields using the current pricing snapshot. Recoverable waste counts uncached input plus cache writes a session never read back; cache writes that earned their reads are excluded, because paying to build a cache you then read from is the mechanism working.";
|
|
4424
4863
|
const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
|
|
4425
4864
|
pushProse(lines, methodology + provenance, 0, a.dim);
|
|
4426
4865
|
return lines.join("\n");
|
|
@@ -4503,6 +4942,14 @@ function burnClockChart(bc) {
|
|
|
4503
4942
|
}).join("");
|
|
4504
4943
|
return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Estimated current API-equivalent valuation by day of week" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
|
|
4505
4944
|
}
|
|
4945
|
+
function weakestGap2(p) {
|
|
4946
|
+
let worst = null;
|
|
4947
|
+
for (const c of p.checks) {
|
|
4948
|
+
if (!c.assessed || c.score == null || !c.gap) continue;
|
|
4949
|
+
if (!worst || c.score < worst.score) worst = c;
|
|
4950
|
+
}
|
|
4951
|
+
return worst;
|
|
4952
|
+
}
|
|
4506
4953
|
function pillarBars(pillars) {
|
|
4507
4954
|
return pillars.map((p) => {
|
|
4508
4955
|
const name = esc(p.name);
|
|
@@ -4511,7 +4958,9 @@ function pillarBars(pillars) {
|
|
|
4511
4958
|
}
|
|
4512
4959
|
const score = p.score;
|
|
4513
4960
|
const color = bandColorForScore(score);
|
|
4514
|
-
|
|
4961
|
+
const weak = weakestGap2(p);
|
|
4962
|
+
const detail = weak ? `<div class="p-detail"><div class="p-weak">Weakest: ${esc(weak.label)} (${weak.score})</div><p class="p-basis">${esc(weak.basis)}</p>` + (weak.action ? `<p class="p-action"><strong>Do this:</strong> ${esc(weak.action)}</p>` : "") + `</div>` : "";
|
|
4963
|
+
return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill" style="width:${score}%;background:${color}"></span></span><span class="p-score">${score}</span></div>` + detail;
|
|
4515
4964
|
}).join("");
|
|
4516
4965
|
}
|
|
4517
4966
|
function dollarFixCard(f) {
|
|
@@ -4543,13 +4992,13 @@ function nextStepsSection(record, meta) {
|
|
|
4543
4992
|
));
|
|
4544
4993
|
}
|
|
4545
4994
|
const waste = record.headlineWasteUsd;
|
|
4546
|
-
const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of
|
|
4995
|
+
const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of recoverable waste at current API list prices. ` : "";
|
|
4547
4996
|
if (licensed) {
|
|
4548
4997
|
const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
|
|
4549
4998
|
steps.push(step(
|
|
4550
4999
|
n++,
|
|
4551
5000
|
"Apply the fixes with optimize",
|
|
4552
|
-
`<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize
|
|
5001
|
+
`<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize once. With no <span class="mono">--project</span> it ranks every project this audit saw and generates for the top ones, then opens a page listing them. Nothing inside your projects is written yet.</p>` + cmd("npx costclaw optimize") + `<p>Then apply it where you want it. <span class="mono">apply</span> is additive: it writes the generated include to <span class="mono">.claude/costclaw.md</span> and adds one import line to your CLAUDE.md, leaving every line you wrote untouched. <span class="mono">--apply-settings</span> additively merges the suggested permission allowlist, and <span class="mono">--remove</span> undoes all of it.</p>` + cmd('npx costclaw apply <your-project> --apply-settings\nclaude "Follow UPGRADE-ALL.md"') + `<p class="fine">Moving machines? <span class="mono">costclaw deactivate</span> here, <span class="mono">costclaw activate <key></span> there.</p>`
|
|
4553
5002
|
));
|
|
4554
5003
|
} else {
|
|
4555
5004
|
steps.push(step(
|
|
@@ -4646,6 +5095,11 @@ h2 {
|
|
|
4646
5095
|
.score-head .big { font-size: 30px; font-weight: 700; letter-spacing: -0.01em; }
|
|
4647
5096
|
.score-head .band { font-size: 15px; color: var(--umber); font-weight: 600; }
|
|
4648
5097
|
.pillar { display: flex; align-items: center; gap: var(--s3); margin: var(--s2) 0; }
|
|
5098
|
+
.p-detail { margin: 0 0 var(--s3) 0; padding: var(--s2) var(--s3); border-left: 2px solid var(--line); }
|
|
5099
|
+
.p-weak { font-size: 13px; font-weight: 600; }
|
|
5100
|
+
.p-basis { margin: 4px 0 0 0; font-size: 13px; color: var(--muted); }
|
|
5101
|
+
.p-action { margin: 4px 0 0 0; font-size: 13px; }
|
|
5102
|
+
.verdict { margin: var(--s2) 0 0 0; font-size: 14px; line-height: 1.5; }
|
|
4649
5103
|
.p-name { flex: 0 0 190px; font-size: 14px; }
|
|
4650
5104
|
.p-track { flex: 1; height: 14px; background: var(--track); border-radius: 7px; overflow: hidden; }
|
|
4651
5105
|
.p-fill { display: block; height: 100%; border-radius: 7px; }
|
|
@@ -4748,7 +5202,7 @@ function renderHtml(record, meta) {
|
|
|
4748
5202
|
const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd3(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">90th-percentile 5h window</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (maximum)</div><div class="v">${esc(usd3(w.maxWindowUsd))}</div></div></div>` : "";
|
|
4749
5203
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
4750
5204
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
4751
|
-
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No
|
|
5205
|
+
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No recoverable waste was found. See the issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
|
|
4752
5206
|
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
4753
5207
|
const bc = record.burnClock;
|
|
4754
5208
|
const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
|
|
@@ -4781,6 +5235,7 @@ ${metaBlock}
|
|
|
4781
5235
|
<div class="banner">
|
|
4782
5236
|
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
4783
5237
|
${bannerAmount}
|
|
5238
|
+
${record.verdict ? `<p class="verdict">${esc(record.verdict)}</p>` : ""}
|
|
4784
5239
|
</div>
|
|
4785
5240
|
${planNote}
|
|
4786
5241
|
<div class="stats">
|
|
@@ -4788,6 +5243,7 @@ ${planNote}
|
|
|
4788
5243
|
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
4789
5244
|
<div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
4790
5245
|
${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
|
|
5246
|
+
${record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? `<div class="stat"><div class="k">Cache writes that earned their reads</div><div class="v">${esc(usd3(record.cacheWriteCostUsd))}</div><div class="k">working cost, not waste</div></div>` : ""}
|
|
4791
5247
|
</div>
|
|
4792
5248
|
${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
|
|
4793
5249
|
${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
|
|
@@ -4805,7 +5261,7 @@ ${burnSection}
|
|
|
4805
5261
|
<p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
|
|
4806
5262
|
${pillarBars(record.pillarScores)}
|
|
4807
5263
|
|
|
4808
|
-
<h2>Top changes ranked by
|
|
5264
|
+
<h2>Top changes, ranked by what they recover</h2>
|
|
4809
5265
|
${dollarSection}
|
|
4810
5266
|
${otherSection}
|
|
4811
5267
|
${skippedNote}
|
|
@@ -5171,7 +5627,7 @@ async function loadAuditInputs(opts) {
|
|
|
5171
5627
|
let claudeMdSource = null;
|
|
5172
5628
|
if (opts.claudeMdPath) {
|
|
5173
5629
|
claudeMd = await readFile4(opts.claudeMdPath, "utf8");
|
|
5174
|
-
claudeMdSource =
|
|
5630
|
+
claudeMdSource = resolve2(opts.claudeMdPath);
|
|
5175
5631
|
} else {
|
|
5176
5632
|
const fallback = join5(opts.home ?? homedir4(), ".claude", "CLAUDE.md");
|
|
5177
5633
|
try {
|
|
@@ -5227,14 +5683,14 @@ async function runAudit(opts) {
|
|
|
5227
5683
|
const notices = [];
|
|
5228
5684
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
5229
5685
|
if (opts.html) {
|
|
5230
|
-
const target =
|
|
5686
|
+
const target = resolve2(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
5231
5687
|
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license });
|
|
5232
5688
|
await writeFile3(target, doc, "utf8");
|
|
5233
5689
|
openInBrowser(target);
|
|
5234
5690
|
notices.push(`HTML report written to ${target}`);
|
|
5235
5691
|
}
|
|
5236
5692
|
if (opts.card) {
|
|
5237
|
-
const target =
|
|
5693
|
+
const target = resolve2(opts.cardPath || DEFAULT_CARD_FILE);
|
|
5238
5694
|
const svg = renderCard(record);
|
|
5239
5695
|
await writeFile3(target, svg, "utf8");
|
|
5240
5696
|
notices.push(`Score card written to ${target}`);
|
|
@@ -5249,24 +5705,24 @@ async function runAudit(opts) {
|
|
|
5249
5705
|
|
|
5250
5706
|
// src/optimize-command.ts
|
|
5251
5707
|
import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
|
|
5252
|
-
import { basename as
|
|
5708
|
+
import { basename as basename3, join as join10, resolve as resolve6 } from "path";
|
|
5253
5709
|
import { homedir as homedir5 } from "os";
|
|
5254
5710
|
|
|
5255
5711
|
// src/claude-md-imports.ts
|
|
5256
5712
|
import { readFile as readFile5 } from "fs/promises";
|
|
5257
|
-
import { dirname, isAbsolute, join as join6, resolve as
|
|
5713
|
+
import { dirname as dirname2, isAbsolute, join as join6, resolve as resolve3 } from "path";
|
|
5258
5714
|
var IMPORT_RE = /^@(\S+)\s*$/;
|
|
5259
5715
|
async function resolveClaudeMdImports(claudeMdPath, text2, home) {
|
|
5260
5716
|
const out = { imports: [], notes: [] };
|
|
5261
5717
|
if (!claudeMdPath || !text2) return out;
|
|
5262
|
-
const base =
|
|
5718
|
+
const base = dirname2(resolve3(claudeMdPath));
|
|
5263
5719
|
const seen = /* @__PURE__ */ new Set();
|
|
5264
5720
|
for (const line of text2.split(/\r?\n/)) {
|
|
5265
5721
|
const m = line.match(IMPORT_RE);
|
|
5266
5722
|
const raw = m?.[1];
|
|
5267
5723
|
if (!raw) continue;
|
|
5268
5724
|
const expanded = raw === "~" || raw.startsWith("~/") ? join6(home, raw.slice(1)) : raw;
|
|
5269
|
-
const full = isAbsolute(expanded) ?
|
|
5725
|
+
const full = isAbsolute(expanded) ? resolve3(expanded) : resolve3(base, expanded);
|
|
5270
5726
|
if (seen.has(full)) continue;
|
|
5271
5727
|
seen.add(full);
|
|
5272
5728
|
try {
|
|
@@ -5280,7 +5736,7 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
|
|
|
5280
5736
|
|
|
5281
5737
|
// src/apply-command.ts
|
|
5282
5738
|
import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
|
|
5283
|
-
import { join as join7, dirname as
|
|
5739
|
+
import { join as join7, dirname as dirname3 } from "path";
|
|
5284
5740
|
var IMPORT_LINE2 = "@.claude/costclaw.md";
|
|
5285
5741
|
var INCLUDE_REL = ".claude/costclaw.md";
|
|
5286
5742
|
var APPLY_DIR_REL = ".claude/costclaw";
|
|
@@ -5507,7 +5963,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
5507
5963
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
5508
5964
|
const merged = { ...existing, permissions: mergedPerms };
|
|
5509
5965
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
5510
|
-
await mkdir4(
|
|
5966
|
+
await mkdir4(dirname3(target), { recursive: true });
|
|
5511
5967
|
await writeFile4(backup, existingText, "utf8");
|
|
5512
5968
|
await writeFile4(target, mergedText, "utf8");
|
|
5513
5969
|
return [
|
|
@@ -5543,7 +5999,7 @@ function approxTokens(n) {
|
|
|
5543
5999
|
function plural2(n, noun) {
|
|
5544
6000
|
return n === 1 ? noun : `${noun}s`;
|
|
5545
6001
|
}
|
|
5546
|
-
function
|
|
6002
|
+
function num5(n) {
|
|
5547
6003
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
5548
6004
|
}
|
|
5549
6005
|
var STYLE2 = `
|
|
@@ -5597,6 +6053,8 @@ ul.warn li:last-child{border-bottom:0}
|
|
|
5597
6053
|
ul.warn b{font-weight:650}
|
|
5598
6054
|
.pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
|
|
5599
6055
|
color:var(--ink2);margin-left:8px;vertical-align:1px}
|
|
6056
|
+
.pill.own-apply{border-color:var(--accent);color:var(--accent);font-weight:650}
|
|
6057
|
+
.pill.own-you{font-weight:650}
|
|
5600
6058
|
.files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
|
|
5601
6059
|
.file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
|
|
5602
6060
|
display:flex;flex-direction:column;gap:6px}
|
|
@@ -5639,18 +6097,23 @@ pre.diff .ctx{color:var(--ink2);display:block}
|
|
|
5639
6097
|
margin:0 0 8px;font-weight:600}
|
|
5640
6098
|
`;
|
|
5641
6099
|
var TAG_META = {
|
|
5642
|
-
carried: { cls: "keep", label: "carried" },
|
|
5643
|
-
filled: { cls: "fill", label: "filled" },
|
|
5644
|
-
replaced: { cls: "repl", label: "replaced" },
|
|
5645
|
-
dropped: { cls: "drop", label: "left out" },
|
|
5646
|
-
placeholder: { cls: "hole", label: "placeholder" }
|
|
6100
|
+
carried: { cls: "keep", label: "carried", meaning: "kept word for word from your file" },
|
|
6101
|
+
filled: { cls: "fill", label: "filled", meaning: "an empty section completed from your project" },
|
|
6102
|
+
replaced: { cls: "repl", label: "replaced", meaning: "rewritten from what the scan found on disk" },
|
|
6103
|
+
dropped: { cls: "drop", label: "left out", meaning: "not copied over, reason in the next column" },
|
|
6104
|
+
placeholder: { cls: "hole", label: "placeholder", meaning: "still a blank for you to fill in" }
|
|
5647
6105
|
};
|
|
6106
|
+
function tagLegend(sections) {
|
|
6107
|
+
const used = new Set(sections.map((s) => s.disposition));
|
|
6108
|
+
const items = Object.keys(TAG_META).filter((k) => used.has(k)).map((k) => `<li><span class="tag ${TAG_META[k].cls}">${TAG_META[k].label}</span> ${esc(TAG_META[k].meaning)}</li>`).join("");
|
|
6109
|
+
return items ? `<ul class="taglegend">${items}</ul>` : "";
|
|
6110
|
+
}
|
|
5648
6111
|
function renderSectionsTable(sections) {
|
|
5649
6112
|
const rows = sections.map((s) => {
|
|
5650
6113
|
const meta = TAG_META[s.disposition];
|
|
5651
|
-
return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
|
|
6114
|
+
return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}" title="${esc(meta.meaning)}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
|
|
5652
6115
|
}).join("");
|
|
5653
|
-
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
|
|
6116
|
+
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>` + tagLegend(sections) + `<div class="scroll"><table><thead><tr><th>Section</th><th>What happened</th><th>Why</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
|
5654
6117
|
}
|
|
5655
6118
|
var DIFF_LCS_LIMIT = 3e3;
|
|
5656
6119
|
function diffLines(before, after) {
|
|
@@ -5751,6 +6214,14 @@ function renderSideBySideTab(before, after, tokens) {
|
|
|
5751
6214
|
function renderComparisonTabs(input) {
|
|
5752
6215
|
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>`;
|
|
5753
6216
|
}
|
|
6217
|
+
function renderComparisonSection(input) {
|
|
6218
|
+
const tabs = renderComparisonTabs(input);
|
|
6219
|
+
if (!input.review) return `<div class="panel">${tabs}</div>`;
|
|
6220
|
+
const after = countLines(input.optimizedClaudeMd);
|
|
6221
|
+
const before = input.currentClaudeMd === null ? null : countLines(input.currentClaudeMd);
|
|
6222
|
+
const size = before === null ? `${num5(after)} ${plural2(after, "line")}` : `${num5(before)} ${plural2(before, "line")} to ${num5(after)}`;
|
|
6223
|
+
return `<div class="panel"><details class="filedrop"><summary>Show the full before and after (${size})</summary>${tabs}</details></div>`;
|
|
6224
|
+
}
|
|
5754
6225
|
function countLines(s) {
|
|
5755
6226
|
return s.length === 0 ? 0 : s.split("\n").length;
|
|
5756
6227
|
}
|
|
@@ -5835,6 +6306,16 @@ function toolWarnings(report) {
|
|
|
5835
6306
|
}
|
|
5836
6307
|
return out.sort((a, b) => b.sessions - a.sessions);
|
|
5837
6308
|
}
|
|
6309
|
+
var APPLY_WRITES = /* @__PURE__ */ new Set([
|
|
6310
|
+
"check_permission_allowlist",
|
|
6311
|
+
"check_cmd_size",
|
|
6312
|
+
"check_cmd_structure",
|
|
6313
|
+
"check_cmd_stability",
|
|
6314
|
+
"check_cmd_scope"
|
|
6315
|
+
]);
|
|
6316
|
+
function ownerPill(fixId) {
|
|
6317
|
+
return APPLY_WRITES.has(fixId) ? `<span class="pill own-apply" title="Running apply on this project writes this change.">costclaw applies this</span>` : `<span class="pill own-you" title="No file costclaw writes can change this; the work order turns it into a task for your own Claude Code.">you change this</span>`;
|
|
6318
|
+
}
|
|
5838
6319
|
function renderSetupWarnings(fixes, report) {
|
|
5839
6320
|
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
5840
6321
|
const tool = toolWarnings(report);
|
|
@@ -5842,15 +6323,16 @@ function renderSetupWarnings(fixes, report) {
|
|
|
5842
6323
|
const single = tool.filter((t) => t.sessions === 1);
|
|
5843
6324
|
const items = [];
|
|
5844
6325
|
for (const f of warnFixes) {
|
|
5845
|
-
items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span
|
|
6326
|
+
items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span>${ownerPill(f.id)}</li>`);
|
|
5846
6327
|
}
|
|
5847
6328
|
for (const t of multi) {
|
|
5848
6329
|
const sentence = t.action ? ` ${esc(t.action)}` : "";
|
|
5849
6330
|
items.push(
|
|
5850
|
-
`<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span
|
|
6331
|
+
`<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span>${ownerPill("")}</li>`
|
|
5851
6332
|
);
|
|
5852
6333
|
}
|
|
5853
|
-
const
|
|
6334
|
+
const ownerNote = items.length > 0 ? `<p class="note" style="margin-top:0"><b>costclaw applies this</b> means running apply on the project writes it. <b>you change this</b> means no file costclaw writes can fix it; the work order on the index page turns those into tasks you can hand to your own Claude Code.</p>` : "";
|
|
6335
|
+
const list = items.length > 0 ? `${ownerNote}<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
|
|
5854
6336
|
let disclosure = "";
|
|
5855
6337
|
if (single.length > 0) {
|
|
5856
6338
|
const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
|
|
@@ -5882,7 +6364,7 @@ function renderCarriedDisclosure(sections, carriedTokens) {
|
|
|
5882
6364
|
const carried = sections.filter((s) => s.disposition === "carried");
|
|
5883
6365
|
if (carried.length === 0) return "";
|
|
5884
6366
|
const names = carried.map((s) => esc(s.name)).join(" · ");
|
|
5885
|
-
const weight = carriedTokens > 0 ? `, about ${
|
|
6367
|
+
const weight = carriedTokens > 0 ? `, about ${num5(carriedTokens)} tokens` : "";
|
|
5886
6368
|
const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
|
|
5887
6369
|
return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
|
|
5888
6370
|
}
|
|
@@ -5910,11 +6392,12 @@ ${renderHeader(input)}
|
|
|
5910
6392
|
<h2>What this run changed<span class="n">the receipt</span></h2>
|
|
5911
6393
|
${renderReceipt(input)}
|
|
5912
6394
|
|
|
5913
|
-
<h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
|
|
5914
|
-
<div class="panel">${renderComparisonTabs(input)}</div>
|
|
5915
6395
|
${input.review ? `
|
|
5916
|
-
<h2>What to change in your CLAUDE.md<span class="n">${
|
|
5917
|
-
<div class="panel">${renderAnnotatedFile(input.review)}</div
|
|
6396
|
+
<h2>What to change in your CLAUDE.md<span class="n">${num5(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
|
|
6397
|
+
<div class="panel">${renderAnnotatedFile(input.review)}</div>
|
|
6398
|
+
` : ""}
|
|
6399
|
+
<h2>Your CLAUDE.md, before and after<span class="n">${input.review ? "the evidence behind that list" : "what actually changed"}</span></h2>
|
|
6400
|
+
${renderComparisonSection(input)}
|
|
5918
6401
|
|
|
5919
6402
|
<h2>Fixes, ranked by what they recover</h2>
|
|
5920
6403
|
${renderFixes(input.fixes, input.report)}
|
|
@@ -5952,6 +6435,34 @@ pre.review .mark-move{background:color-mix(in srgb,var(--warn) 14%,transparent)}
|
|
|
5952
6435
|
pre.review .mark-add{background:color-mix(in srgb,var(--good) 14%,transparent)}
|
|
5953
6436
|
pre.review .skip{color:var(--ink2);font-style:italic}
|
|
5954
6437
|
.legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
|
|
6438
|
+
.taglegend{list-style:none;padding:0;margin:0 0 12px;display:flex;flex-wrap:wrap;gap:6px 16px;font-size:.78rem;color:var(--ink2)}
|
|
6439
|
+
.taglegend li{display:flex;align-items:center;gap:6px}
|
|
6440
|
+
.paths{display:grid;gap:14px;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));margin:0 0 10px}
|
|
6441
|
+
.path{position:relative;border:1px solid var(--line);border-radius:12px;padding:18px 18px 16px;background:var(--panel)}
|
|
6442
|
+
.path.best{border-color:var(--accent);border-width:2px}
|
|
6443
|
+
.path h3{margin:0 0 6px;font-size:1rem}
|
|
6444
|
+
.path p{margin:0 0 10px;font-size:.88rem;line-height:1.5}
|
|
6445
|
+
.path .badge{position:absolute;top:-10px;left:16px;background:var(--accent);color:#fff;font-size:.68rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:2px 9px;border-radius:99px}
|
|
6446
|
+
.path .cmd{display:block;margin-top:8px}
|
|
6447
|
+
.path textarea.prompt{margin-top:10px}
|
|
6448
|
+
.oneclick{margin:0 0 18px}
|
|
6449
|
+
.acts button.big{font-size:1rem;font-weight:650;padding:11px 22px}
|
|
6450
|
+
.path .opt{display:flex;align-items:flex-start;gap:8px;margin-top:12px;font-size:.84rem;color:var(--ink2);line-height:1.4}
|
|
6451
|
+
.path .opt input{margin-top:2px}
|
|
6452
|
+
th.pick,td.pick{width:1%;text-align:center;padding-right:0}
|
|
6453
|
+
.changed .chg{padding:10px 0;border-bottom:1px solid var(--line)}
|
|
6454
|
+
.changed .chg:last-of-type{border-bottom:0}
|
|
6455
|
+
.changed .chg b{font-size:.92rem}
|
|
6456
|
+
.changed .chg ul{margin:6px 0 0;padding-left:20px;font-size:.84rem;color:var(--ink2);line-height:1.5}
|
|
6457
|
+
.changes{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:10px}
|
|
6458
|
+
.changes li{line-height:1.45}
|
|
6459
|
+
.ch-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px}
|
|
6460
|
+
.changes .note{margin:2px 0 0}
|
|
6461
|
+
.tag.ch-remove{border-color:#c0504d;color:#c0504d}
|
|
6462
|
+
.tag.ch-move{border-color:#b8860b;color:#b8860b}
|
|
6463
|
+
.tag.ch-add{border-color:var(--accent);color:var(--accent)}
|
|
6464
|
+
.filedrop{margin-top:14px}
|
|
6465
|
+
.filedrop summary{cursor:pointer;font-size:.82rem;color:var(--ink2)}
|
|
5955
6466
|
.legend b{font-weight:650}
|
|
5956
6467
|
.legend .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 12px}
|
|
5957
6468
|
.legend .sw.r{background:color-mix(in srgb,var(--bad) 50%,transparent)}
|
|
@@ -5981,7 +6492,7 @@ function renderLines(lines, keepRunMax) {
|
|
|
5981
6492
|
const tail = run.slice(run.length - half);
|
|
5982
6493
|
for (const i of head) out.push(lineHtml(lines[i], i + 1));
|
|
5983
6494
|
out.push(
|
|
5984
|
-
`<span class="ln skip"><span class="g"></span>... ${
|
|
6495
|
+
`<span class="ln skip"><span class="g"></span>... ${num5(run.length - head.length - tail.length)} unchanged lines ...</span>`
|
|
5985
6496
|
);
|
|
5986
6497
|
for (const i of tail) out.push(lineHtml(lines[i], i + 1));
|
|
5987
6498
|
} else {
|
|
@@ -6001,6 +6512,35 @@ function renderLines(lines, keepRunMax) {
|
|
|
6001
6512
|
flush();
|
|
6002
6513
|
return `<pre class="review">${out.join("")}</pre>`;
|
|
6003
6514
|
}
|
|
6515
|
+
var CHANGE_KIND = {
|
|
6516
|
+
remove: { label: "remove", cls: "ch-remove" },
|
|
6517
|
+
move: { label: "move out", cls: "ch-move" },
|
|
6518
|
+
add: { label: "add", cls: "ch-add" }
|
|
6519
|
+
};
|
|
6520
|
+
function renderChangeList(review) {
|
|
6521
|
+
const changes = [...review.changes].sort((a, b) => b.tokens - a.tokens);
|
|
6522
|
+
if (changes.length === 0) {
|
|
6523
|
+
return `<p class="note">Nothing to change in ${esc(review.label)}.</p>`;
|
|
6524
|
+
}
|
|
6525
|
+
const counts = { remove: 0, move: 0, add: 0 };
|
|
6526
|
+
let tokens = 0;
|
|
6527
|
+
for (const c of changes) {
|
|
6528
|
+
counts[c.kind] += 1;
|
|
6529
|
+
if (c.kind !== "add") tokens += c.tokens;
|
|
6530
|
+
}
|
|
6531
|
+
const parts = [];
|
|
6532
|
+
if (counts.remove > 0) parts.push(`${num5(counts.remove)} to remove`);
|
|
6533
|
+
if (counts.move > 0) parts.push(`${num5(counts.move)} to move out`);
|
|
6534
|
+
if (counts.add > 0) parts.push(`${num5(counts.add)} to add`);
|
|
6535
|
+
const saving = tokens > 0 ? ` Removing and moving those takes about ${num5(tokens)} tokens off every turn.` : "";
|
|
6536
|
+
const items = changes.map((c) => {
|
|
6537
|
+
const kind = CHANGE_KIND[c.kind];
|
|
6538
|
+
const dest = c.destination ? ` <span class="note">to ${esc(c.destination)}</span>` : "";
|
|
6539
|
+
const size = c.tokens > 0 ? `<span class="pill">~${num5(c.tokens)} tokens</span>` : "";
|
|
6540
|
+
return `<li><div class="ch-head"><span class="tag ${kind.cls}">${kind.label}</span> <b>${esc(c.instruction)}</b>${dest} ${size}</div><p class="note">${esc(c.heading)}: ${esc(c.reason)}</p></li>`;
|
|
6541
|
+
}).join("");
|
|
6542
|
+
return `<p class="note" style="margin-top:0"><b>${parts.join(", ")}.</b>${saving}</p><ol class="changes">${items}</ol>`;
|
|
6543
|
+
}
|
|
6004
6544
|
function renderAnnotatedFile(review) {
|
|
6005
6545
|
const legend = `<p class="legend"><b>Legend</b><span class="sw r"></span>remove<span class="sw m"></span>move out<span class="sw a"></span>add</p>`;
|
|
6006
6546
|
if (review.missing) {
|
|
@@ -6010,12 +6550,13 @@ function renderAnnotatedFile(review) {
|
|
|
6010
6550
|
}
|
|
6011
6551
|
return legend + `<p class="note">${esc(review.label)} does not exist yet. Proposed content:</p>` + renderLines(adds, 0);
|
|
6012
6552
|
}
|
|
6013
|
-
|
|
6553
|
+
const annotated = legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
|
|
6554
|
+
return renderChangeList(review) + `<details class="filedrop"><summary>Show ${esc(review.label)} line by line (${num5(review.lines.length)} ${plural2(review.lines.length, "line")})</summary>${annotated}</details>`;
|
|
6014
6555
|
}
|
|
6015
6556
|
function reviewCountLine(review) {
|
|
6016
6557
|
const n = review.changes.length;
|
|
6017
6558
|
if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
|
|
6018
|
-
return `<b>${
|
|
6559
|
+
return `<b>${num5(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
|
|
6019
6560
|
}
|
|
6020
6561
|
var INDEX_STYLE = `
|
|
6021
6562
|
.rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
|
|
@@ -6036,28 +6577,30 @@ function indexTokens(tokens) {
|
|
|
6036
6577
|
if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
|
|
6037
6578
|
return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
|
|
6038
6579
|
}
|
|
6039
|
-
function indexStatus(appliedAt) {
|
|
6580
|
+
function indexStatus(appliedAt, mode) {
|
|
6040
6581
|
if (!appliedAt) return `<span class="state off">not applied</span>`;
|
|
6041
|
-
|
|
6582
|
+
const what = mode === "settings" ? " + permissions" : mode === "include" ? ", no permissions" : "";
|
|
6583
|
+
return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}${esc(what)}</span>`;
|
|
6042
6584
|
}
|
|
6043
|
-
function
|
|
6044
|
-
return `<
|
|
6585
|
+
function applyButtons(slug) {
|
|
6586
|
+
return `<div class="acts"><button type="submit" name="action" value="include:${esc(slug)}" class="go" title="Writes .claude/costclaw.md, adds one import line to this project's CLAUDE.md, and copies the playbook and work order into .claude/costclaw/.">Apply</button><button type="submit" name="action" value="settings:${esc(slug)}" title="Everything Apply does, and also merges the suggested permission allowlist into this project's settings, backing up the original first.">Apply + permissions</button><button type="submit" name="action" value="remove:${esc(slug)}" title="Removes the costclaw include and the import line.">Undo</button></div>`;
|
|
6045
6587
|
}
|
|
6046
6588
|
function indexActions(row, serve) {
|
|
6047
6589
|
const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
|
|
6048
6590
|
if (!serve) {
|
|
6049
6591
|
return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
|
|
6050
6592
|
}
|
|
6051
|
-
return `<
|
|
6593
|
+
return applyButtons(row.slug) + `<p class="note" style="margin-top:6px"><b>Apply</b> writes <span class="mono">.claude/costclaw.md</span>, adds one <span class="mono">@.claude/costclaw.md</span> line to this project's CLAUDE.md, and copies the playbook and work order into <span class="mono">.claude/costclaw/</span>. Every line you wrote stays. <b>Apply + permissions</b> does all of that <em>and</em> merges the suggested allowlist into this project's settings, so it is the same button plus one step. ${details}</p>`;
|
|
6052
6594
|
}
|
|
6053
|
-
function
|
|
6054
|
-
|
|
6595
|
+
function renderStartHere(review, projectCount) {
|
|
6596
|
+
const covers = projectCount === 1 ? "your global CLAUDE.md and this project" : `your global CLAUDE.md and all ${num5(projectCount)} projects`;
|
|
6597
|
+
return `<div class="paths"><div class="path best"><span class="badge">Recommended</span><h3>Hand it to your own Claude</h3><p>It knows your project and costclaw does not. It opens each file, makes the changes, and asks you before writing anything. One paste covers ${esc(covers)}.</p><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="8" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run:</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code></div><div class="path"><h3>Or let costclaw write the files</h3><p>No model involved, so it only does the part that needs no judgement: a generated include file plus one import line per project. It never edits a line you wrote.</p><p class="note">Use the Apply buttons on the project rows below. Start with the top row: that is where the money is.</p></div></div><p class="note">costclaw never calls a model. The prompt above is deterministic text built from your own audit, so nothing here has been through an LLM.</p>`;
|
|
6055
6598
|
}
|
|
6056
6599
|
function renderGlobalPanel(review) {
|
|
6057
6600
|
const t = review.tokens;
|
|
6058
6601
|
const importCount = review.importCount;
|
|
6059
|
-
const imported = importCount > 0 ? ` plus ${
|
|
6060
|
-
const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${
|
|
6602
|
+
const imported = importCount > 0 ? ` plus ${num5(importCount)} imported ${plural2(importCount, "file")}` : "";
|
|
6603
|
+
const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${num5(t.total)} tokens on every turn of every project, about ${num5(t.afterChanges)} after these changes. ${reviewCountLine(review)}.</p>`;
|
|
6061
6604
|
return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
|
|
6062
6605
|
}
|
|
6063
6606
|
function renderProjectPanels(input, review) {
|
|
@@ -6066,7 +6609,7 @@ function renderProjectPanels(input, review) {
|
|
|
6066
6609
|
const r = review.projects.get(row.slug);
|
|
6067
6610
|
if (!r) return;
|
|
6068
6611
|
out.push(
|
|
6069
|
-
`<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${
|
|
6612
|
+
`<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${num5(r.changes.length)} proposed ${plural2(r.changes.length, "change")}</summary><div class="panel" style="margin-top:10px"><p class="revhead">${reviewCountLine(r)}. About ${num5(r.tokens.total)} tokens per turn, about ${num5(r.tokens.afterChanges)} after these changes.</p>` + renderAnnotatedFile(r) + `<div style="margin-top:14px">${indexActions(row, input.serve)}</div></div></details>`
|
|
6070
6613
|
);
|
|
6071
6614
|
});
|
|
6072
6615
|
return out.join("");
|
|
@@ -6075,9 +6618,19 @@ function renderOptimizeIndex(input) {
|
|
|
6075
6618
|
const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
|
|
6076
6619
|
const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
|
|
6077
6620
|
const rows = input.rows.map(
|
|
6078
|
-
(r) => `<tr><td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt)}</td><td>${indexActions(r, input.serve)}</td></tr>`
|
|
6621
|
+
(r) => `<tr>` + (input.serve ? `<td class="pick"><input type="checkbox" name="slug" value="${esc(r.slug)}" checked aria-label="Include ${esc(r.slug)}"></td>` : "") + `<td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt, r.appliedMode)}</td><td>${indexActions(r, input.serve)}</td></tr>`
|
|
6079
6622
|
).join("");
|
|
6080
|
-
const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr
|
|
6623
|
+
const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr>` + (input.serve ? `<th class="pick" title="Uncheck a project to leave it out of Apply everything">Include</th>` : "") + `<th>Project</th><th class="num">Valuation estimate</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
|
6624
|
+
const serve = input.serve;
|
|
6625
|
+
const applied = input.rows.filter((r) => r.appliedAt).length;
|
|
6626
|
+
const priorRun = serve?.lastRun;
|
|
6627
|
+
const oneButton = serve ? `<div class="path best oneclick"><span class="badge">One click</span><h3>Apply everything</h3><p>Writes the generated include and one import line into ${num5(input.rows.length)} ${plural2(input.rows.length, "project")}. It never edits a line you wrote, and the Revert button puts it all back.</p><div class="acts"><button type="submit" name="action" value="apply-all" class="go big">Apply everything</button>` + // Only one Revert on the page: the What changed panel owns it right after
|
|
6628
|
+
// a run, and this card carries it when a previous session left files behind.
|
|
6629
|
+
(applied > 0 && !priorRun ? `<button type="submit" name="action" value="revert-all">Revert everything</button>` : "") + `</div><label class="opt"><input type="checkbox" name="settings" value="1" checked> also merge the suggested permission allowlist (backs up your settings first)</label><p class="note">Uncheck any project in the table below to leave it out.</p></div>` : "";
|
|
6630
|
+
const run = priorRun;
|
|
6631
|
+
const changed = run ? `<h2>What changed<span class="n">${run.reverted ? "reverted" : "written just now"}</span></h2><div class="panel changed">` + run.changes.map(
|
|
6632
|
+
(c) => `<div class="chg"><b>${esc(c.slug)}</b><ul>` + c.lines.map((l) => `<li>${esc(l)}</li>`).join("") + `</ul></div>`
|
|
6633
|
+
).join("") + (run.reverted ? `<p class="note">Everything costclaw added has been removed.</p>` : `<div class="acts" style="margin-top:12px"><button type="submit" name="action" value="revert-all" class="go">Revert everything</button></div><p class="note">Reverts every project checked in the table below.</p>`) + `</div>` : "";
|
|
6081
6634
|
const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
|
|
6082
6635
|
const done = input.serve ? `<div class="acts" style="margin:0 0 22px"><form method="post" action="/done"><input type="hidden" name="token" value="${esc(input.serve.token)}"><button type="submit">Done</button></form></div>` : "";
|
|
6083
6636
|
const how = input.serve ? `<p class="note">Apply writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md. Every line you wrote stays where it is. Remove undoes both.</p>` : `<p class="note">Run the line on a project's row to apply it. It writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md; every line you wrote stays where it is. Undo with <code>--remove</code>.</p>`;
|
|
@@ -6094,20 +6647,25 @@ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
|
|
|
6094
6647
|
<div class="wrap">
|
|
6095
6648
|
<header><p class="kicker">CostClaw optimize · generated locally · nothing left your machine</p>
|
|
6096
6649
|
<h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
|
|
6097
|
-
<p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation · ${esc(usd5(recoverable))}
|
|
6650
|
+
<p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation · ${esc(usd5(recoverable))} recoverable ·
|
|
6098
6651
|
artifacts in ${esc(input.root)}/</p></header>
|
|
6099
6652
|
|
|
6100
6653
|
${banner}${done}
|
|
6101
|
-
${
|
|
6102
|
-
${
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
${
|
|
6654
|
+
${serve ? `<form method="post" action="/apply">
|
|
6655
|
+
<input type="hidden" name="token" value="${esc(serve.token)}">` : ""}
|
|
6656
|
+
${changed}
|
|
6657
|
+
${oneButton}
|
|
6658
|
+
${input.review ? `<h2>${serve ? "Or hand it to your own Claude" : "Start here"}<span class="n">${serve ? "it knows your project" : "two ways to do this, pick one"}</span></h2>
|
|
6659
|
+
${renderStartHere(input.review, input.rows.length)}` : ""}
|
|
6106
6660
|
|
|
6107
6661
|
<h2>Your projects<span class="n">ranked by spend</span></h2>
|
|
6108
6662
|
${body}
|
|
6109
6663
|
${how}
|
|
6110
|
-
${
|
|
6664
|
+
${serve ? `</form>` : ""}
|
|
6665
|
+
${input.review ? `<h2>What the prompt will change<span class="n">the evidence behind it</span></h2>
|
|
6666
|
+
<h3>Global CLAUDE.md<span class="n">loaded on every turn of every project</span></h3>
|
|
6667
|
+
${renderGlobalPanel(input.review.global)}
|
|
6668
|
+
${renderProjectPanels(input, input.review)}` : ""}
|
|
6111
6669
|
|
|
6112
6670
|
<footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
|
|
6113
6671
|
Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
|
|
@@ -6120,7 +6678,7 @@ Nothing was written inside any project. No network calls, no telemetry, no model
|
|
|
6120
6678
|
|
|
6121
6679
|
// src/project-scan.ts
|
|
6122
6680
|
import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
|
|
6123
|
-
import { join as join8, basename } from "path";
|
|
6681
|
+
import { join as join8, basename as basename2 } from "path";
|
|
6124
6682
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
6125
6683
|
"node_modules",
|
|
6126
6684
|
".git",
|
|
@@ -6594,7 +7152,7 @@ function parseReadme(text2) {
|
|
|
6594
7152
|
return { name, description };
|
|
6595
7153
|
}
|
|
6596
7154
|
async function scanProject(dir) {
|
|
6597
|
-
const profile = emptyProfile(
|
|
7155
|
+
const profile = emptyProfile(basename2(dir));
|
|
6598
7156
|
const { files, dirs } = await listEntries(dir);
|
|
6599
7157
|
if (files.includes("package.json")) {
|
|
6600
7158
|
const pkg = parseJson(await readText(join8(dir, "package.json")));
|
|
@@ -6617,13 +7175,13 @@ async function scanProject(dir) {
|
|
|
6617
7175
|
}
|
|
6618
7176
|
}
|
|
6619
7177
|
}
|
|
6620
|
-
if (profile.description === null || profile.name ===
|
|
7178
|
+
if (profile.description === null || profile.name === basename2(dir)) {
|
|
6621
7179
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
6622
7180
|
if (readmeName) {
|
|
6623
7181
|
const text2 = await readText(join8(dir, readmeName));
|
|
6624
7182
|
if (text2 !== null) {
|
|
6625
7183
|
const parsed = parseReadme(text2);
|
|
6626
|
-
if (profile.name ===
|
|
7184
|
+
if (profile.name === basename2(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
6627
7185
|
if (profile.description === null && parsed.description !== null) {
|
|
6628
7186
|
profile.description = parsed.description;
|
|
6629
7187
|
}
|
|
@@ -6643,7 +7201,7 @@ async function scanProject(dir) {
|
|
|
6643
7201
|
import { createServer } from "http";
|
|
6644
7202
|
import { randomBytes } from "crypto";
|
|
6645
7203
|
import { readFile as readFile8 } from "fs/promises";
|
|
6646
|
-
import { extname, resolve as
|
|
7204
|
+
import { extname, resolve as resolve4, sep as sep2 } from "path";
|
|
6647
7205
|
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
6648
7206
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
6649
7207
|
var DASHBOARD_NAME = "DASHBOARD.html";
|
|
@@ -6668,11 +7226,24 @@ function safeArtifactPath(root, urlPath) {
|
|
|
6668
7226
|
return null;
|
|
6669
7227
|
}
|
|
6670
7228
|
if (decoded.includes("\0")) return null;
|
|
6671
|
-
const resolvedRoot =
|
|
6672
|
-
const full =
|
|
7229
|
+
const resolvedRoot = resolve4(root);
|
|
7230
|
+
const full = resolve4(resolvedRoot, "." + decoded);
|
|
6673
7231
|
if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
|
|
6674
7232
|
return full;
|
|
6675
7233
|
}
|
|
7234
|
+
function parseFormMulti(body) {
|
|
7235
|
+
const out = {};
|
|
7236
|
+
for (const pair of body.split("&")) {
|
|
7237
|
+
if (pair === "") continue;
|
|
7238
|
+
const eq = pair.indexOf("=");
|
|
7239
|
+
const rawKey = eq < 0 ? pair : pair.slice(0, eq);
|
|
7240
|
+
const rawValue = eq < 0 ? "" : pair.slice(eq + 1);
|
|
7241
|
+
const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
|
|
7242
|
+
const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
|
|
7243
|
+
(out[key] ??= []).push(value);
|
|
7244
|
+
}
|
|
7245
|
+
return out;
|
|
7246
|
+
}
|
|
6676
7247
|
function rowsFromManifest(manifest) {
|
|
6677
7248
|
return manifest.projects.map((e) => ({
|
|
6678
7249
|
slug: e.slug,
|
|
@@ -6682,6 +7253,7 @@ function rowsFromManifest(manifest) {
|
|
|
6682
7253
|
recoverableUsd: e.recoverableUsd,
|
|
6683
7254
|
tokens: e.tokens,
|
|
6684
7255
|
...e.appliedAt ? { appliedAt: e.appliedAt } : {},
|
|
7256
|
+
...e.appliedMode ? { appliedMode: e.appliedMode } : {},
|
|
6685
7257
|
applyCommand: `costclaw apply ${e.projectDir}`
|
|
6686
7258
|
}));
|
|
6687
7259
|
}
|
|
@@ -6720,6 +7292,7 @@ async function startApplyServer(opts) {
|
|
|
6720
7292
|
const token = randomBytes(16).toString("hex");
|
|
6721
7293
|
const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
|
|
6722
7294
|
const manifest = opts.manifest;
|
|
7295
|
+
let lastRun = null;
|
|
6723
7296
|
let closedAlready = false;
|
|
6724
7297
|
let resolveClosed;
|
|
6725
7298
|
const closedPromise = new Promise((res) => {
|
|
@@ -6747,7 +7320,11 @@ async function startApplyServer(opts) {
|
|
|
6747
7320
|
generatedAt: manifest.generatedAt,
|
|
6748
7321
|
root: opts.root,
|
|
6749
7322
|
rows: rowsFromManifest(manifest),
|
|
6750
|
-
serve: {
|
|
7323
|
+
serve: {
|
|
7324
|
+
token,
|
|
7325
|
+
...msg ? { message: msg } : {},
|
|
7326
|
+
...lastRun ? { lastRun } : {}
|
|
7327
|
+
}
|
|
6751
7328
|
});
|
|
6752
7329
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
6753
7330
|
res.end(html);
|
|
@@ -6760,31 +7337,69 @@ async function startApplyServer(opts) {
|
|
|
6760
7337
|
sendText(res, 400, "Payload too large");
|
|
6761
7338
|
return;
|
|
6762
7339
|
}
|
|
6763
|
-
const form =
|
|
6764
|
-
if (form["token"] !== token) {
|
|
7340
|
+
const form = parseFormMulti(body);
|
|
7341
|
+
if (form["token"]?.[0] !== token) {
|
|
6765
7342
|
sendText(res, 403, "Forbidden");
|
|
6766
7343
|
return;
|
|
6767
7344
|
}
|
|
6768
|
-
const
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
|
|
6772
|
-
|
|
6773
|
-
|
|
6774
|
-
|
|
6775
|
-
|
|
6776
|
-
|
|
7345
|
+
const raw = form["action"]?.[0] ?? "";
|
|
7346
|
+
const bulk = raw === "apply-all" || raw === "revert-all";
|
|
7347
|
+
const withSettings = (form["settings"]?.[0] ?? "") !== "";
|
|
7348
|
+
const targets = [];
|
|
7349
|
+
if (bulk) {
|
|
7350
|
+
const picked = new Set(form["slug"] ?? []);
|
|
7351
|
+
for (const entry of manifest.projects) {
|
|
7352
|
+
if (!picked.has(entry.slug)) continue;
|
|
7353
|
+
if (raw === "revert-all") {
|
|
7354
|
+
if (entry.appliedAt) targets.push({ entry, action: "remove" });
|
|
7355
|
+
} else {
|
|
7356
|
+
targets.push({ entry, action: withSettings ? "settings" : "include" });
|
|
7357
|
+
}
|
|
7358
|
+
}
|
|
7359
|
+
if (targets.length === 0) {
|
|
7360
|
+
res.writeHead(303, { Location: `/?msg=${encodeURIComponent("Nothing selected.")}` });
|
|
7361
|
+
res.end();
|
|
7362
|
+
return;
|
|
7363
|
+
}
|
|
7364
|
+
} else {
|
|
7365
|
+
const sep3 = raw.indexOf(":");
|
|
7366
|
+
const verb2 = sep3 < 0 ? raw : raw.slice(0, sep3);
|
|
7367
|
+
const slug = sep3 < 0 ? form["slug"]?.[0] ?? "" : raw.slice(sep3 + 1);
|
|
7368
|
+
if (!isApplyAction(verb2)) {
|
|
7369
|
+
sendText(res, 400, "Unknown action");
|
|
7370
|
+
return;
|
|
7371
|
+
}
|
|
7372
|
+
const entry = manifest.projects.find((p) => p.slug === slug);
|
|
7373
|
+
if (!entry) {
|
|
7374
|
+
sendText(res, 400, "Unknown project");
|
|
7375
|
+
return;
|
|
7376
|
+
}
|
|
7377
|
+
targets.push({ entry, action: verb2 });
|
|
6777
7378
|
}
|
|
6778
|
-
|
|
6779
|
-
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
|
|
6783
|
-
|
|
6784
|
-
|
|
6785
|
-
|
|
6786
|
-
|
|
7379
|
+
const changes = [];
|
|
7380
|
+
const errors = [];
|
|
7381
|
+
for (const { entry, action } of targets) {
|
|
7382
|
+
try {
|
|
7383
|
+
const lines = await opts.apply(entry, action);
|
|
7384
|
+
if (action === "remove") {
|
|
7385
|
+
delete entry.appliedAt;
|
|
7386
|
+
delete entry.appliedMode;
|
|
7387
|
+
} else {
|
|
7388
|
+
entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7389
|
+
entry.appliedMode = action;
|
|
7390
|
+
}
|
|
7391
|
+
changes.push({ slug: entry.slug, lines });
|
|
7392
|
+
} catch (err) {
|
|
7393
|
+
const text2 = `Error: ${err instanceof Error ? err.message : String(err)}`;
|
|
7394
|
+
errors.push(text2);
|
|
7395
|
+
changes.push({ slug: entry.slug, lines: [text2] });
|
|
7396
|
+
}
|
|
6787
7397
|
}
|
|
7398
|
+
if (opts.onManifestChange) await opts.onManifestChange(manifest);
|
|
7399
|
+
lastRun = { reverted: targets[0]?.action === "remove", changes };
|
|
7400
|
+
const ok = targets.length - errors.length;
|
|
7401
|
+
const verb = lastRun.reverted ? "Reverted" : "Applied";
|
|
7402
|
+
const msg = errors.length === targets.length ? errors[0] : errors.length > 0 ? `${verb} ${ok} of ${targets.length}. ${errors[0]}` : `${verb} ${ok} ${ok === 1 ? "project" : "projects"}.`;
|
|
6788
7403
|
res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg)}` });
|
|
6789
7404
|
res.end();
|
|
6790
7405
|
}
|
|
@@ -6866,7 +7481,7 @@ async function startApplyServer(opts) {
|
|
|
6866
7481
|
|
|
6867
7482
|
// src/optimize-manifest.ts
|
|
6868
7483
|
import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
|
|
6869
|
-
import { join as join9, resolve as
|
|
7484
|
+
import { join as join9, resolve as resolve5 } from "path";
|
|
6870
7485
|
var MANIFEST_NAME = "index.json";
|
|
6871
7486
|
function defaultOptimizeRoot(home) {
|
|
6872
7487
|
return join9(home, ".costclaw", "optimize");
|
|
@@ -6900,7 +7515,7 @@ async function writeManifest(root, m) {
|
|
|
6900
7515
|
await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
|
|
6901
7516
|
}
|
|
6902
7517
|
function normalizePath(p) {
|
|
6903
|
-
const r =
|
|
7518
|
+
const r = resolve5(p);
|
|
6904
7519
|
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
6905
7520
|
}
|
|
6906
7521
|
function findEntry(m, projectDir) {
|
|
@@ -6937,7 +7552,7 @@ var DEFAULT_LIMIT = 10;
|
|
|
6937
7552
|
function usd6(n) {
|
|
6938
7553
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
6939
7554
|
}
|
|
6940
|
-
function
|
|
7555
|
+
function num6(n) {
|
|
6941
7556
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
6942
7557
|
}
|
|
6943
7558
|
function describeDetection(project) {
|
|
@@ -6974,7 +7589,7 @@ function projectRecoverable(report, slug) {
|
|
|
6974
7589
|
return row ? row.usd : null;
|
|
6975
7590
|
}
|
|
6976
7591
|
async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
6977
|
-
const slug =
|
|
7592
|
+
const slug = basename3(resolve6(projectDir));
|
|
6978
7593
|
let currentClaudeMd = ctx.claudeMdOverride;
|
|
6979
7594
|
let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
|
|
6980
7595
|
if (currentClaudeMd === void 0) {
|
|
@@ -7055,11 +7670,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7055
7670
|
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
7056
7671
|
const dir = after > before ? "larger" : "smaller";
|
|
7057
7672
|
lines.push(
|
|
7058
|
-
`Your CLAUDE.md: an estimated ${
|
|
7673
|
+
`Your CLAUDE.md: an estimated ${num6(before)} tokens to ${num6(after)} (${pct2}% ${dir}), paid on every turn.`
|
|
7059
7674
|
);
|
|
7060
7675
|
if (result.carriedTokens >= after / 2) {
|
|
7061
7676
|
lines.push(
|
|
7062
|
-
`About ${
|
|
7677
|
+
`About ${num6(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
7063
7678
|
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
7064
7679
|
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
7065
7680
|
);
|
|
@@ -7074,7 +7689,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7074
7689
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
7075
7690
|
if (review.changes.length > 0) {
|
|
7076
7691
|
const n = review.changes.length;
|
|
7077
|
-
lines.push(`Review: ${
|
|
7692
|
+
lines.push(`Review: ${num6(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
|
|
7078
7693
|
}
|
|
7079
7694
|
lines.push(`Artifacts: ${artifactsDir}`);
|
|
7080
7695
|
lines.push(`Apply: ${applyCommand}`);
|
|
@@ -7082,7 +7697,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7082
7697
|
return {
|
|
7083
7698
|
entry: {
|
|
7084
7699
|
slug,
|
|
7085
|
-
dir:
|
|
7700
|
+
dir: basename3(artifactsDir),
|
|
7086
7701
|
projectDir,
|
|
7087
7702
|
artifactsDir,
|
|
7088
7703
|
spendUsd: spend ?? 0,
|
|
@@ -7197,7 +7812,8 @@ async function runOptimize(opts) {
|
|
|
7197
7812
|
const previous = await readManifest(manifestRoot);
|
|
7198
7813
|
const merged = entries.map((e) => {
|
|
7199
7814
|
const old = previous ? findEntry(previous, e.projectDir) : void 0;
|
|
7200
|
-
|
|
7815
|
+
if (!old?.appliedAt) return e;
|
|
7816
|
+
return { ...e, appliedAt: old.appliedAt, ...old.appliedMode ? { appliedMode: old.appliedMode } : {} };
|
|
7201
7817
|
});
|
|
7202
7818
|
if (single && previous) {
|
|
7203
7819
|
const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
|
|
@@ -7245,6 +7861,7 @@ async function runOptimize(opts) {
|
|
|
7245
7861
|
recoverableUsd: e.recoverableUsd,
|
|
7246
7862
|
tokens: e.tokens,
|
|
7247
7863
|
...e.appliedAt ? { appliedAt: e.appliedAt } : {},
|
|
7864
|
+
...e.appliedMode ? { appliedMode: e.appliedMode } : {},
|
|
7248
7865
|
applyCommand: `costclaw apply ${e.projectDir}`
|
|
7249
7866
|
}));
|
|
7250
7867
|
const html = renderOptimizeIndex({
|
|
@@ -7273,7 +7890,7 @@ async function runOptimize(opts) {
|
|
|
7273
7890
|
const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
|
|
7274
7891
|
lines.push("");
|
|
7275
7892
|
lines.push(
|
|
7276
|
-
`Your CLAUDE.md review: ${
|
|
7893
|
+
`Your CLAUDE.md review: ${num6(globalReview.changes.length)} ${globalReview.changes.length === 1 ? "change" : "changes"} to ${globalLabel}, ${num6(projectChanges)} across your ${outcomes.length === 1 ? "project" : "projects"}.`
|
|
7277
7894
|
);
|
|
7278
7895
|
lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
|
|
7279
7896
|
lines.push(` claude "Follow ${upgradeAllPath}"`);
|
|
@@ -7326,7 +7943,7 @@ async function runOptimize(opts) {
|
|
|
7326
7943
|
|
|
7327
7944
|
// src/badge-command.ts
|
|
7328
7945
|
import { writeFile as writeFile7 } from "fs/promises";
|
|
7329
|
-
import { resolve as
|
|
7946
|
+
import { resolve as resolve7 } from "path";
|
|
7330
7947
|
|
|
7331
7948
|
// src/badge.ts
|
|
7332
7949
|
var HEIGHT2 = 20;
|
|
@@ -7350,7 +7967,7 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
|
7350
7967
|
async function runBadge(opts) {
|
|
7351
7968
|
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
7352
7969
|
const svg = renderBadge(record);
|
|
7353
|
-
const target =
|
|
7970
|
+
const target = resolve7(opts.out || DEFAULT_BADGE_FILE);
|
|
7354
7971
|
await writeFile7(target, svg, "utf8");
|
|
7355
7972
|
return { output: `Badge written to ${target}`, record, target };
|
|
7356
7973
|
}
|
|
@@ -7554,7 +8171,7 @@ function parseApplyFlags(args) {
|
|
|
7554
8171
|
};
|
|
7555
8172
|
}
|
|
7556
8173
|
function cliVersion() {
|
|
7557
|
-
return true ? "0.
|
|
8174
|
+
return true ? "0.13.1" : "0.0.0-dev";
|
|
7558
8175
|
}
|
|
7559
8176
|
function isHelpRequest(command, args) {
|
|
7560
8177
|
if (command === void 0) return false;
|