costclaw 0.12.4 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -72
- package/dist/index.js +745 -189
- 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 = "";
|
|
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");
|
|
2001
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 {
|
|
@@ -2960,11 +3292,12 @@ function claudeMdReceiptLine(claudeMdTokens) {
|
|
|
2960
3292
|
const grew = delta > 0;
|
|
2961
3293
|
const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
|
|
2962
3294
|
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 ${
|
|
3295
|
+
return `Your optimized CLAUDE.md goes from an estimated ${num3(before)} tokens to ${num3(after)}${pct2}. ${tail}`;
|
|
2964
3296
|
}
|
|
2965
3297
|
function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
|
|
2966
3298
|
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
|
|
2967
3299
|
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
3300
|
+
const coldStart = coldStartExposureUsd(report);
|
|
2968
3301
|
const parts = [];
|
|
2969
3302
|
parts.push("# CostClaw fix playbook");
|
|
2970
3303
|
const projectName = project?.name?.trim();
|
|
@@ -2973,9 +3306,9 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
|
|
|
2973
3306
|
parts.push(
|
|
2974
3307
|
[
|
|
2975
3308
|
...projectLine ? [projectLine, ""] : [],
|
|
2976
|
-
`
|
|
3309
|
+
`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
3310
|
"",
|
|
2978
|
-
"This is the ranked plan from your audit. Priority suggestions are ordered by
|
|
3311
|
+
"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
3312
|
].join("\n")
|
|
2980
3313
|
);
|
|
2981
3314
|
const receipt = claudeMdReceiptLine(claudeMdTokens);
|
|
@@ -3103,12 +3436,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3103
3436
|
if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
|
|
3104
3437
|
const rows = worklist.map((s) => {
|
|
3105
3438
|
const n2 = s.volatileLines;
|
|
3106
|
-
const dated = n2 > 0 ? `, ${
|
|
3107
|
-
return `- ${s.heading}: est. ${
|
|
3439
|
+
const dated = n2 > 0 ? `, ${num3(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
|
|
3440
|
+
return `- ${s.heading}: est. ${num3(s.tokens)} tokens${dated}.`;
|
|
3108
3441
|
});
|
|
3109
3442
|
const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
|
|
3110
3443
|
const rest = carried.carriedList.length - worklist.length;
|
|
3111
|
-
const tail = rest > 0 ? [`The remaining ${
|
|
3444
|
+
const tail = rest > 0 ? [`The remaining ${num3(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num3(carried.carriedTokens - shown)} tokens.`] : [];
|
|
3112
3445
|
const before = claudeMdTokens.before;
|
|
3113
3446
|
const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
|
|
3114
3447
|
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 +3449,7 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3116
3449
|
[
|
|
3117
3450
|
`## Task ${n++}: Reclaim the carried sections`,
|
|
3118
3451
|
"",
|
|
3119
|
-
`Your CLAUDE.md carries an estimated ${
|
|
3452
|
+
`Your CLAUDE.md carries an estimated ${num3(carried.carriedTokens)} tokens of your`,
|
|
3120
3453
|
"own prose, paid on every turn of every session.",
|
|
3121
3454
|
`costclaw does not rewrite your prose, so it passed all of it through untouched:`,
|
|
3122
3455
|
`${consequence} Doing the actual trimming is this task,`,
|
|
@@ -3226,15 +3559,43 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
3226
3559
|
parts.push(verify.join("\n"));
|
|
3227
3560
|
return clean(parts.join("\n\n").trimEnd() + "\n");
|
|
3228
3561
|
}
|
|
3562
|
+
var CARRIED_BUDGET_FRACTION = 0.6;
|
|
3563
|
+
function clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore) {
|
|
3564
|
+
if (claudeMdBefore == null) return requestedBudget;
|
|
3565
|
+
const empty = { ...carried, workflow: null, architecture: null, other: [] };
|
|
3566
|
+
const floorMd = buildClaudeMd(input, recoverable, [], { placeholders: 0 }, empty, []);
|
|
3567
|
+
const floorTokens = Math.round(floorMd.trim().length / 4);
|
|
3568
|
+
const room = claudeMdBefore - floorTokens;
|
|
3569
|
+
if (room <= 0) return requestedBudget;
|
|
3570
|
+
return Math.min(requestedBudget, room);
|
|
3571
|
+
}
|
|
3572
|
+
function tierCounts(sections) {
|
|
3573
|
+
const counts = { rule: 0, fact: 0, prose: 0 };
|
|
3574
|
+
for (const section of sections) {
|
|
3575
|
+
for (const unit of splitUnits(section)) counts[classifyUnit(unit)]++;
|
|
3576
|
+
}
|
|
3577
|
+
return counts;
|
|
3578
|
+
}
|
|
3229
3579
|
function optimize(input) {
|
|
3230
3580
|
const recoverable = cacheMissExposureUsd(input.report);
|
|
3231
3581
|
const notes = [];
|
|
3232
3582
|
const stats = { placeholders: 0 };
|
|
3233
3583
|
const carried = carriedSections(input.currentClaudeMd);
|
|
3234
3584
|
const dispositions = [];
|
|
3235
|
-
const
|
|
3585
|
+
const claudeMdBefore = input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null;
|
|
3586
|
+
const requestedBudget = input.maxTokens ?? Math.round(carried.carriedTokens * CARRIED_BUDGET_FRACTION);
|
|
3587
|
+
const budgetTokens = clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore);
|
|
3588
|
+
const selection = selectUnits(carried.carriedList, budgetTokens);
|
|
3589
|
+
const keptByHeading = new Map(selection.kept.map((s) => [s.heading, s]));
|
|
3590
|
+
const carriedForBuild = {
|
|
3591
|
+
...carried,
|
|
3592
|
+
workflow: carried.workflowHeading ? keptByHeading.get(carried.workflowHeading)?.body ?? null : null,
|
|
3593
|
+
architecture: carried.architectureHeading ? keptByHeading.get(carried.architectureHeading)?.body ?? null : null,
|
|
3594
|
+
other: carried.other.map((s) => keptByHeading.get(s.heading)).filter((s) => s != null)
|
|
3595
|
+
};
|
|
3596
|
+
const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carriedForBuild, dispositions);
|
|
3236
3597
|
const claudeMdTokens = {
|
|
3237
|
-
before:
|
|
3598
|
+
before: claudeMdBefore,
|
|
3238
3599
|
after: Math.round(optimizedClaudeMd.trim().length / 4)
|
|
3239
3600
|
};
|
|
3240
3601
|
const carriedTokens = carried.carriedTokens;
|
|
@@ -3242,6 +3603,21 @@ function optimize(input) {
|
|
|
3242
3603
|
const settingsJson = buildSettings(input.project);
|
|
3243
3604
|
const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
|
|
3244
3605
|
const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
|
|
3606
|
+
const totalByTier = tierCounts(carried.carriedList);
|
|
3607
|
+
const droppedByTier = { rule: 0, fact: 0, prose: 0 };
|
|
3608
|
+
for (const d of selection.dropped) droppedByTier[d.kind]++;
|
|
3609
|
+
const keptByTier = {
|
|
3610
|
+
rule: totalByTier.rule - droppedByTier.rule,
|
|
3611
|
+
fact: totalByTier.fact - droppedByTier.fact,
|
|
3612
|
+
prose: totalByTier.prose - droppedByTier.prose
|
|
3613
|
+
};
|
|
3614
|
+
const selectionResult = {
|
|
3615
|
+
budgetTokens,
|
|
3616
|
+
keptTokens: selection.kept.reduce((sum, s) => sum + s.tokens, 0),
|
|
3617
|
+
droppedTokens: selection.droppedTokens,
|
|
3618
|
+
keptByTier,
|
|
3619
|
+
droppedByTier
|
|
3620
|
+
};
|
|
3245
3621
|
const cleanNotes = notes.map((n) => clean(n));
|
|
3246
3622
|
const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
|
|
3247
3623
|
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 +3632,8 @@ function optimize(input) {
|
|
|
3256
3632
|
placeholdersRemaining: stats.placeholders,
|
|
3257
3633
|
claudeMdTokens,
|
|
3258
3634
|
carriedTokens,
|
|
3259
|
-
sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
|
|
3635
|
+
sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) })),
|
|
3636
|
+
selection: selectionResult
|
|
3260
3637
|
};
|
|
3261
3638
|
}
|
|
3262
3639
|
return {
|
|
@@ -3270,7 +3647,8 @@ function optimize(input) {
|
|
|
3270
3647
|
placeholdersRemaining: stats.placeholders,
|
|
3271
3648
|
claudeMdTokens,
|
|
3272
3649
|
carriedTokens,
|
|
3273
|
-
sectionDispositions: cleanDispositions
|
|
3650
|
+
sectionDispositions: cleanDispositions,
|
|
3651
|
+
selection: selectionResult
|
|
3274
3652
|
};
|
|
3275
3653
|
}
|
|
3276
3654
|
|
|
@@ -3356,6 +3734,15 @@ function cleanFix(f) {
|
|
|
3356
3734
|
wasteUsd: round2(f.wasteUsd)
|
|
3357
3735
|
};
|
|
3358
3736
|
}
|
|
3737
|
+
function roundIdle(i) {
|
|
3738
|
+
return {
|
|
3739
|
+
usd: round2(i.usd),
|
|
3740
|
+
events: i.events,
|
|
3741
|
+
longIdleUsd: round2(i.longIdleUsd),
|
|
3742
|
+
longIdleEvents: i.longIdleEvents,
|
|
3743
|
+
maxGapMinutes: Math.round(i.maxGapMinutes)
|
|
3744
|
+
};
|
|
3745
|
+
}
|
|
3359
3746
|
function cleanCheck(c) {
|
|
3360
3747
|
return { ...c, basis: sanitizeText(c.basis) };
|
|
3361
3748
|
}
|
|
@@ -3367,7 +3754,7 @@ function buildAudit(input, opts = {}) {
|
|
|
3367
3754
|
const cmd2 = analyzeClaudeMd(input.claudeMd);
|
|
3368
3755
|
const { pillars, overall, band } = scorePillars(report, cmd2, input.questionnaire, input.setup);
|
|
3369
3756
|
const plan = input.plan ?? "api";
|
|
3370
|
-
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd2, plan);
|
|
3757
|
+
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, coldStartUsd, addressableUsd, verdict, fixes } = synthesize(report, pillars, cmd2, plan);
|
|
3371
3758
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
3372
3759
|
return {
|
|
3373
3760
|
schemaVersion: "1",
|
|
@@ -3388,6 +3775,11 @@ function buildAudit(input, opts = {}) {
|
|
|
3388
3775
|
headlineWasteLabel: sanitizeText(headlineWasteLabel),
|
|
3389
3776
|
plan,
|
|
3390
3777
|
headlineWasteShare: round4(headlineWasteShare),
|
|
3778
|
+
coldStartUsd: round2(coldStartUsd),
|
|
3779
|
+
addressableUsd: round2(addressableUsd),
|
|
3780
|
+
cacheWriteCostUsd: round2(cacheWriteCostUsd(report)),
|
|
3781
|
+
verdict: sanitizeText(verdict),
|
|
3782
|
+
idleCacheExpiry: roundIdle(idleCacheExpiry(report)),
|
|
3391
3783
|
usageWindows: roundWindows(computeWindowStats(report)),
|
|
3392
3784
|
burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0, input.timeZone)),
|
|
3393
3785
|
fixes: fixes.map(cleanFix),
|
|
@@ -3536,7 +3928,7 @@ var IMPORT_LINE = "@.claude/costclaw.md";
|
|
|
3536
3928
|
function estTokens(text2) {
|
|
3537
3929
|
return Math.round(text2.length / 4);
|
|
3538
3930
|
}
|
|
3539
|
-
function
|
|
3931
|
+
function num4(n) {
|
|
3540
3932
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3541
3933
|
}
|
|
3542
3934
|
function normalize(line) {
|
|
@@ -3639,7 +4031,7 @@ function markVolatile(lines, sections, b, destDir) {
|
|
|
3639
4031
|
id,
|
|
3640
4032
|
kind: "move",
|
|
3641
4033
|
heading: s.heading,
|
|
3642
|
-
instruction: `Move the ${
|
|
4034
|
+
instruction: `Move the ${num4(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
|
|
3643
4035
|
reason: VOLATILE_WHY,
|
|
3644
4036
|
tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
|
|
3645
4037
|
destination: dest
|
|
@@ -3776,8 +4168,8 @@ function reviewProjectClaudeMd(input) {
|
|
|
3776
4168
|
id,
|
|
3777
4169
|
kind: "remove",
|
|
3778
4170
|
heading: s.heading,
|
|
3779
|
-
instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${
|
|
3780
|
-
reason: `${
|
|
4171
|
+
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.`,
|
|
4172
|
+
reason: `${num4(covered.length)} of ${num4(content.length)} lines appear verbatim in the generated include`,
|
|
3781
4173
|
tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
|
|
3782
4174
|
});
|
|
3783
4175
|
}
|
|
@@ -3901,8 +4293,8 @@ function reviewGlobalClaudeMd(input) {
|
|
|
3901
4293
|
id,
|
|
3902
4294
|
kind: "move",
|
|
3903
4295
|
heading: "(top)",
|
|
3904
|
-
instruction: `Split ${heaviest.label} (about ${
|
|
3905
|
-
reason: `this file plus its imports is about ${
|
|
4296
|
+
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.`,
|
|
4297
|
+
reason: `this file plus its imports is about ${num4(total)} tokens on every turn of every project`,
|
|
3906
4298
|
tokens: 0,
|
|
3907
4299
|
destination: "on-demand docs"
|
|
3908
4300
|
});
|
|
@@ -3922,7 +4314,7 @@ function changeList(review) {
|
|
|
3922
4314
|
const out = [];
|
|
3923
4315
|
review.changes.forEach((c, i) => {
|
|
3924
4316
|
const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
|
|
3925
|
-
const weight = c.tokens > 0 ? `, about ${
|
|
4317
|
+
const weight = c.tokens > 0 ? `, about ${num4(c.tokens)} tokens` : "";
|
|
3926
4318
|
out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
|
|
3927
4319
|
out.push(` Why: ${c.reason}`);
|
|
3928
4320
|
if (c.destination) out.push(` Destination: ${c.destination}`);
|
|
@@ -3936,7 +4328,7 @@ function changeList(review) {
|
|
|
3936
4328
|
return out;
|
|
3937
4329
|
}
|
|
3938
4330
|
function tokenTarget(review, what) {
|
|
3939
|
-
return `- ${what}: about ${
|
|
4331
|
+
return `- ${what}: about ${num4(review.tokens.afterChanges)} tokens per turn after these changes (about ${num4(review.tokens.total)} now).`;
|
|
3940
4332
|
}
|
|
3941
4333
|
function buildUpgradeAll(input) {
|
|
3942
4334
|
const parts = [];
|
|
@@ -3959,7 +4351,7 @@ function buildUpgradeAll(input) {
|
|
|
3959
4351
|
parts.push([
|
|
3960
4352
|
`## Global: ${input.global.path}`,
|
|
3961
4353
|
"",
|
|
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. ${
|
|
4354
|
+
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
4355
|
"",
|
|
3964
4356
|
...changeList(input.global)
|
|
3965
4357
|
].join("\n"));
|
|
@@ -3990,7 +4382,7 @@ function buildUpgradeAll(input) {
|
|
|
3990
4382
|
|
|
3991
4383
|
// src/audit-command.ts
|
|
3992
4384
|
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";
|
|
4385
|
+
import { join as join5, resolve as resolve2 } from "path";
|
|
3994
4386
|
import { homedir as homedir4 } from "os";
|
|
3995
4387
|
|
|
3996
4388
|
// src/open.ts
|
|
@@ -4010,8 +4402,8 @@ function openInBrowser(target) {
|
|
|
4010
4402
|
|
|
4011
4403
|
// src/read-sessions.ts
|
|
4012
4404
|
import { readdir } from "fs/promises";
|
|
4013
|
-
import { readFileSync, openSync, closeSync, readSync } from "fs";
|
|
4014
|
-
import { join, relative, sep } from "path";
|
|
4405
|
+
import { readFileSync, openSync, closeSync, readSync, statSync } from "fs";
|
|
4406
|
+
import { basename, dirname, join, relative, resolve, sep } from "path";
|
|
4015
4407
|
import { homedir } from "os";
|
|
4016
4408
|
function defaultProjectsPath() {
|
|
4017
4409
|
return process.env.CLAUDE_PROJECTS_PATH || join(homedir(), ".claude", "projects");
|
|
@@ -4055,6 +4447,45 @@ function lazyLog(full, meta) {
|
|
|
4055
4447
|
}
|
|
4056
4448
|
var CWD_PROBE_BYTES = 65536;
|
|
4057
4449
|
var CWD_PROBE_LINES = 40;
|
|
4450
|
+
function repoRootFor(startDir) {
|
|
4451
|
+
let dir;
|
|
4452
|
+
try {
|
|
4453
|
+
dir = resolve(startDir);
|
|
4454
|
+
} catch {
|
|
4455
|
+
return null;
|
|
4456
|
+
}
|
|
4457
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
4458
|
+
const dotGit = join(dir, ".git");
|
|
4459
|
+
let stat4;
|
|
4460
|
+
try {
|
|
4461
|
+
stat4 = statSync(dotGit);
|
|
4462
|
+
} catch {
|
|
4463
|
+
const parent2 = dirname(dir);
|
|
4464
|
+
if (parent2 === dir) return null;
|
|
4465
|
+
dir = parent2;
|
|
4466
|
+
continue;
|
|
4467
|
+
}
|
|
4468
|
+
if (stat4.isDirectory()) return dir;
|
|
4469
|
+
if (stat4.isFile()) {
|
|
4470
|
+
try {
|
|
4471
|
+
const pointer = readFileSync(dotGit, "utf8").trim();
|
|
4472
|
+
const match = /^gitdir:\s*(.+)$/m.exec(pointer);
|
|
4473
|
+
const gitDir = match?.[1]?.trim();
|
|
4474
|
+
if (gitDir) {
|
|
4475
|
+
const parts = resolve(gitDir).split(/[\\/]+/);
|
|
4476
|
+
const idx = parts.lastIndexOf(".git");
|
|
4477
|
+
if (idx > 0) return parts.slice(0, idx).join(sep);
|
|
4478
|
+
}
|
|
4479
|
+
} catch {
|
|
4480
|
+
}
|
|
4481
|
+
return dir;
|
|
4482
|
+
}
|
|
4483
|
+
const parent = dirname(dir);
|
|
4484
|
+
if (parent === dir) return null;
|
|
4485
|
+
dir = parent;
|
|
4486
|
+
}
|
|
4487
|
+
return null;
|
|
4488
|
+
}
|
|
4058
4489
|
function projectNameFromLogs(files) {
|
|
4059
4490
|
for (const full of files.slice(0, 3)) {
|
|
4060
4491
|
let fd;
|
|
@@ -4109,8 +4540,10 @@ async function readSessions(rootPath) {
|
|
|
4109
4540
|
}
|
|
4110
4541
|
const files = await collectJsonl(projPath);
|
|
4111
4542
|
const probe = projectNameFromLogs(files);
|
|
4112
|
-
const
|
|
4113
|
-
|
|
4543
|
+
const repoRoot = probe ? repoRootFor(probe.cwd) : null;
|
|
4544
|
+
const resolvedSlug = repoRoot ? basename(repoRoot) : probe?.slug;
|
|
4545
|
+
const projectSlug = resolvedSlug || dir.name;
|
|
4546
|
+
if (probe && !projectDirs.has(projectSlug)) projectDirs.set(projectSlug, repoRoot ?? probe.cwd);
|
|
4114
4547
|
for (const full of files) {
|
|
4115
4548
|
const rel = relative(projPath, full).split(sep).join("/");
|
|
4116
4549
|
const name = `${dir.name}/${rel}`;
|
|
@@ -4284,6 +4717,14 @@ function unassessedLine(pillars) {
|
|
|
4284
4717
|
});
|
|
4285
4718
|
return `Not yet scored: ${parts.join(" ")}`;
|
|
4286
4719
|
}
|
|
4720
|
+
function weakestGap(p) {
|
|
4721
|
+
let worst = null;
|
|
4722
|
+
for (const c of p.checks) {
|
|
4723
|
+
if (!c.assessed || c.score == null || !c.gap) continue;
|
|
4724
|
+
if (!worst || c.score < worst.score) worst = c;
|
|
4725
|
+
}
|
|
4726
|
+
return worst;
|
|
4727
|
+
}
|
|
4287
4728
|
function formatAudit(record, meta, color = false) {
|
|
4288
4729
|
const a = ansi(color);
|
|
4289
4730
|
const m = record.usageMetrics;
|
|
@@ -4304,8 +4745,12 @@ function formatAudit(record, meta, color = false) {
|
|
|
4304
4745
|
lines.push(a.dim("-".repeat(WRAP_WIDTH)));
|
|
4305
4746
|
lines.push("");
|
|
4306
4747
|
lines.push(
|
|
4307
|
-
subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd2(record.headlineWasteUsd)}
|
|
4748
|
+
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
4749
|
);
|
|
4750
|
+
if (record.verdict) {
|
|
4751
|
+
lines.push("");
|
|
4752
|
+
pushProse(lines, record.verdict);
|
|
4753
|
+
}
|
|
4309
4754
|
const receipt = sinceOptimizeLine(meta);
|
|
4310
4755
|
if (receipt) pushProse(lines, receipt, 0, a.dim);
|
|
4311
4756
|
lines.push("");
|
|
@@ -4319,17 +4764,24 @@ function formatAudit(record, meta, color = false) {
|
|
|
4319
4764
|
[
|
|
4320
4765
|
{ k: "Pricing snapshot", v: m.pricingSnapshotDate },
|
|
4321
4766
|
...mix ? [{ k: "Model spend", v: mix }] : []
|
|
4322
|
-
]
|
|
4767
|
+
],
|
|
4768
|
+
// Named explicitly because this figure used to sit inside the headline as
|
|
4769
|
+
// if it were waste. It is the cache paying for itself.
|
|
4770
|
+
...record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? [[{ k: "Cache writes that earned their reads (working cost, not waste)", v: usd2(record.cacheWriteCostUsd) }]] : []
|
|
4323
4771
|
];
|
|
4324
4772
|
for (const row of statRows(statBlock, a)) lines.push(row);
|
|
4325
|
-
|
|
4326
|
-
if (
|
|
4773
|
+
const cautions = accuracyNotes(record);
|
|
4774
|
+
if (cautions.length === 1) pushProse(lines, `Pricing caution: ${cautions[0]}`, 0, a.dim);
|
|
4775
|
+
else if (cautions.length > 1) {
|
|
4776
|
+
pushProse(lines, `Pricing caution: ${cautions[0]} (${cautions.length - 1} more in --json)`, 0, a.dim);
|
|
4777
|
+
}
|
|
4778
|
+
if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid recoverable-waste share; its percentage is unavailable.", 0, a.dim);
|
|
4327
4779
|
const w = record.usageWindows;
|
|
4328
4780
|
if (subscription) {
|
|
4329
4781
|
lines.push("");
|
|
4330
4782
|
pushProse(
|
|
4331
4783
|
lines,
|
|
4332
|
-
`Plan: ${record.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.
|
|
4784
|
+
`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
4785
|
0,
|
|
4334
4786
|
a.dim
|
|
4335
4787
|
);
|
|
@@ -4387,17 +4839,24 @@ function formatAudit(record, meta, color = false) {
|
|
|
4387
4839
|
);
|
|
4388
4840
|
for (const p of record.pillarScores) {
|
|
4389
4841
|
lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
|
|
4842
|
+
const weak = weakestGap(p);
|
|
4843
|
+
if (!weak) continue;
|
|
4844
|
+
lines.push(` ${a.dim("Weakest:")} ${weak.label} (${weak.score})`);
|
|
4845
|
+
pushProse(lines, weak.basis, 4, a.dim);
|
|
4846
|
+
if (weak.action) pushProse(lines, `Do this: ${weak.action}`, 4);
|
|
4847
|
+
lines.push("");
|
|
4390
4848
|
}
|
|
4391
4849
|
lines.push("");
|
|
4392
4850
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
|
|
4393
4851
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
4394
|
-
lines.push(a.bold("Top changes ranked by
|
|
4852
|
+
lines.push(a.bold("Top changes, ranked by what they recover:"));
|
|
4395
4853
|
if (dollarFixes.length === 0) {
|
|
4396
|
-
lines.push(" No
|
|
4854
|
+
lines.push(" No recoverable waste was found. See the issues below.");
|
|
4397
4855
|
} else {
|
|
4398
4856
|
for (const [i, f] of dollarFixes.entries()) {
|
|
4399
4857
|
if (i > 0) lines.push("");
|
|
4400
4858
|
lines.push(` - [${a.brand(usd2(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
|
|
4859
|
+
if (f.problem) pushProse(lines, f.problem, 6);
|
|
4401
4860
|
pushProse(lines, f.action, 6);
|
|
4402
4861
|
if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
|
|
4403
4862
|
}
|
|
@@ -4420,7 +4879,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
4420
4879
|
lines.push(a.dim(gapLine));
|
|
4421
4880
|
}
|
|
4422
4881
|
lines.push("");
|
|
4423
|
-
const methodology = "Methodology: amounts are list-price estimates from logged token fields using the current pricing snapshot.
|
|
4882
|
+
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
4883
|
const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
|
|
4425
4884
|
pushProse(lines, methodology + provenance, 0, a.dim);
|
|
4426
4885
|
return lines.join("\n");
|
|
@@ -4503,6 +4962,14 @@ function burnClockChart(bc) {
|
|
|
4503
4962
|
}).join("");
|
|
4504
4963
|
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
4964
|
}
|
|
4965
|
+
function weakestGap2(p) {
|
|
4966
|
+
let worst = null;
|
|
4967
|
+
for (const c of p.checks) {
|
|
4968
|
+
if (!c.assessed || c.score == null || !c.gap) continue;
|
|
4969
|
+
if (!worst || c.score < worst.score) worst = c;
|
|
4970
|
+
}
|
|
4971
|
+
return worst;
|
|
4972
|
+
}
|
|
4506
4973
|
function pillarBars(pillars) {
|
|
4507
4974
|
return pillars.map((p) => {
|
|
4508
4975
|
const name = esc(p.name);
|
|
@@ -4511,7 +4978,9 @@ function pillarBars(pillars) {
|
|
|
4511
4978
|
}
|
|
4512
4979
|
const score = p.score;
|
|
4513
4980
|
const color = bandColorForScore(score);
|
|
4514
|
-
|
|
4981
|
+
const weak = weakestGap2(p);
|
|
4982
|
+
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>` : "";
|
|
4983
|
+
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
4984
|
}).join("");
|
|
4516
4985
|
}
|
|
4517
4986
|
function dollarFixCard(f) {
|
|
@@ -4543,13 +5012,13 @@ function nextStepsSection(record, meta) {
|
|
|
4543
5012
|
));
|
|
4544
5013
|
}
|
|
4545
5014
|
const waste = record.headlineWasteUsd;
|
|
4546
|
-
const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of
|
|
5015
|
+
const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of recoverable waste at current API list prices. ` : "";
|
|
4547
5016
|
if (licensed) {
|
|
4548
5017
|
const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
|
|
4549
5018
|
steps.push(step(
|
|
4550
5019
|
n++,
|
|
4551
5020
|
"Apply the fixes with optimize",
|
|
4552
|
-
`<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize
|
|
5021
|
+
`<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
5022
|
));
|
|
4554
5023
|
} else {
|
|
4555
5024
|
steps.push(step(
|
|
@@ -4646,6 +5115,11 @@ h2 {
|
|
|
4646
5115
|
.score-head .big { font-size: 30px; font-weight: 700; letter-spacing: -0.01em; }
|
|
4647
5116
|
.score-head .band { font-size: 15px; color: var(--umber); font-weight: 600; }
|
|
4648
5117
|
.pillar { display: flex; align-items: center; gap: var(--s3); margin: var(--s2) 0; }
|
|
5118
|
+
.p-detail { margin: 0 0 var(--s3) 0; padding: var(--s2) var(--s3); border-left: 2px solid var(--line); }
|
|
5119
|
+
.p-weak { font-size: 13px; font-weight: 600; }
|
|
5120
|
+
.p-basis { margin: 4px 0 0 0; font-size: 13px; color: var(--muted); }
|
|
5121
|
+
.p-action { margin: 4px 0 0 0; font-size: 13px; }
|
|
5122
|
+
.verdict { margin: var(--s2) 0 0 0; font-size: 14px; line-height: 1.5; }
|
|
4649
5123
|
.p-name { flex: 0 0 190px; font-size: 14px; }
|
|
4650
5124
|
.p-track { flex: 1; height: 14px; background: var(--track); border-radius: 7px; overflow: hidden; }
|
|
4651
5125
|
.p-fill { display: block; height: 100%; border-radius: 7px; }
|
|
@@ -4748,7 +5222,7 @@ function renderHtml(record, meta) {
|
|
|
4748
5222
|
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
5223
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
4750
5224
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
4751
|
-
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No
|
|
5225
|
+
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
5226
|
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
4753
5227
|
const bc = record.burnClock;
|
|
4754
5228
|
const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
|
|
@@ -4781,6 +5255,7 @@ ${metaBlock}
|
|
|
4781
5255
|
<div class="banner">
|
|
4782
5256
|
<div class="label">${esc(record.headlineWasteLabel)}</div>
|
|
4783
5257
|
${bannerAmount}
|
|
5258
|
+
${record.verdict ? `<p class="verdict">${esc(record.verdict)}</p>` : ""}
|
|
4784
5259
|
</div>
|
|
4785
5260
|
${planNote}
|
|
4786
5261
|
<div class="stats">
|
|
@@ -4788,6 +5263,7 @@ ${planNote}
|
|
|
4788
5263
|
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
4789
5264
|
<div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
4790
5265
|
${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
|
|
5266
|
+
${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
5267
|
</div>
|
|
4792
5268
|
${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
|
|
4793
5269
|
${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
|
|
@@ -4805,7 +5281,7 @@ ${burnSection}
|
|
|
4805
5281
|
<p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
|
|
4806
5282
|
${pillarBars(record.pillarScores)}
|
|
4807
5283
|
|
|
4808
|
-
<h2>Top changes ranked by
|
|
5284
|
+
<h2>Top changes, ranked by what they recover</h2>
|
|
4809
5285
|
${dollarSection}
|
|
4810
5286
|
${otherSection}
|
|
4811
5287
|
${skippedNote}
|
|
@@ -5171,7 +5647,7 @@ async function loadAuditInputs(opts) {
|
|
|
5171
5647
|
let claudeMdSource = null;
|
|
5172
5648
|
if (opts.claudeMdPath) {
|
|
5173
5649
|
claudeMd = await readFile4(opts.claudeMdPath, "utf8");
|
|
5174
|
-
claudeMdSource =
|
|
5650
|
+
claudeMdSource = resolve2(opts.claudeMdPath);
|
|
5175
5651
|
} else {
|
|
5176
5652
|
const fallback = join5(opts.home ?? homedir4(), ".claude", "CLAUDE.md");
|
|
5177
5653
|
try {
|
|
@@ -5227,14 +5703,14 @@ async function runAudit(opts) {
|
|
|
5227
5703
|
const notices = [];
|
|
5228
5704
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
5229
5705
|
if (opts.html) {
|
|
5230
|
-
const target =
|
|
5706
|
+
const target = resolve2(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
5231
5707
|
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license });
|
|
5232
5708
|
await writeFile3(target, doc, "utf8");
|
|
5233
5709
|
openInBrowser(target);
|
|
5234
5710
|
notices.push(`HTML report written to ${target}`);
|
|
5235
5711
|
}
|
|
5236
5712
|
if (opts.card) {
|
|
5237
|
-
const target =
|
|
5713
|
+
const target = resolve2(opts.cardPath || DEFAULT_CARD_FILE);
|
|
5238
5714
|
const svg = renderCard(record);
|
|
5239
5715
|
await writeFile3(target, svg, "utf8");
|
|
5240
5716
|
notices.push(`Score card written to ${target}`);
|
|
@@ -5249,24 +5725,24 @@ async function runAudit(opts) {
|
|
|
5249
5725
|
|
|
5250
5726
|
// src/optimize-command.ts
|
|
5251
5727
|
import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
|
|
5252
|
-
import { basename as
|
|
5728
|
+
import { basename as basename3, join as join10, resolve as resolve6 } from "path";
|
|
5253
5729
|
import { homedir as homedir5 } from "os";
|
|
5254
5730
|
|
|
5255
5731
|
// src/claude-md-imports.ts
|
|
5256
5732
|
import { readFile as readFile5 } from "fs/promises";
|
|
5257
|
-
import { dirname, isAbsolute, join as join6, resolve as
|
|
5733
|
+
import { dirname as dirname2, isAbsolute, join as join6, resolve as resolve3 } from "path";
|
|
5258
5734
|
var IMPORT_RE = /^@(\S+)\s*$/;
|
|
5259
5735
|
async function resolveClaudeMdImports(claudeMdPath, text2, home) {
|
|
5260
5736
|
const out = { imports: [], notes: [] };
|
|
5261
5737
|
if (!claudeMdPath || !text2) return out;
|
|
5262
|
-
const base =
|
|
5738
|
+
const base = dirname2(resolve3(claudeMdPath));
|
|
5263
5739
|
const seen = /* @__PURE__ */ new Set();
|
|
5264
5740
|
for (const line of text2.split(/\r?\n/)) {
|
|
5265
5741
|
const m = line.match(IMPORT_RE);
|
|
5266
5742
|
const raw = m?.[1];
|
|
5267
5743
|
if (!raw) continue;
|
|
5268
5744
|
const expanded = raw === "~" || raw.startsWith("~/") ? join6(home, raw.slice(1)) : raw;
|
|
5269
|
-
const full = isAbsolute(expanded) ?
|
|
5745
|
+
const full = isAbsolute(expanded) ? resolve3(expanded) : resolve3(base, expanded);
|
|
5270
5746
|
if (seen.has(full)) continue;
|
|
5271
5747
|
seen.add(full);
|
|
5272
5748
|
try {
|
|
@@ -5280,7 +5756,7 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
|
|
|
5280
5756
|
|
|
5281
5757
|
// src/apply-command.ts
|
|
5282
5758
|
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
|
|
5759
|
+
import { join as join7, dirname as dirname3 } from "path";
|
|
5284
5760
|
var IMPORT_LINE2 = "@.claude/costclaw.md";
|
|
5285
5761
|
var INCLUDE_REL = ".claude/costclaw.md";
|
|
5286
5762
|
var APPLY_DIR_REL = ".claude/costclaw";
|
|
@@ -5507,7 +5983,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
5507
5983
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
5508
5984
|
const merged = { ...existing, permissions: mergedPerms };
|
|
5509
5985
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
5510
|
-
await mkdir4(
|
|
5986
|
+
await mkdir4(dirname3(target), { recursive: true });
|
|
5511
5987
|
await writeFile4(backup, existingText, "utf8");
|
|
5512
5988
|
await writeFile4(target, mergedText, "utf8");
|
|
5513
5989
|
return [
|
|
@@ -5543,7 +6019,7 @@ function approxTokens(n) {
|
|
|
5543
6019
|
function plural2(n, noun) {
|
|
5544
6020
|
return n === 1 ? noun : `${noun}s`;
|
|
5545
6021
|
}
|
|
5546
|
-
function
|
|
6022
|
+
function num5(n) {
|
|
5547
6023
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
5548
6024
|
}
|
|
5549
6025
|
var STYLE2 = `
|
|
@@ -5597,6 +6073,8 @@ ul.warn li:last-child{border-bottom:0}
|
|
|
5597
6073
|
ul.warn b{font-weight:650}
|
|
5598
6074
|
.pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
|
|
5599
6075
|
color:var(--ink2);margin-left:8px;vertical-align:1px}
|
|
6076
|
+
.pill.own-apply{border-color:var(--accent);color:var(--accent);font-weight:650}
|
|
6077
|
+
.pill.own-you{font-weight:650}
|
|
5600
6078
|
.files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
|
|
5601
6079
|
.file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
|
|
5602
6080
|
display:flex;flex-direction:column;gap:6px}
|
|
@@ -5639,18 +6117,23 @@ pre.diff .ctx{color:var(--ink2);display:block}
|
|
|
5639
6117
|
margin:0 0 8px;font-weight:600}
|
|
5640
6118
|
`;
|
|
5641
6119
|
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" }
|
|
6120
|
+
carried: { cls: "keep", label: "carried", meaning: "kept word for word from your file" },
|
|
6121
|
+
filled: { cls: "fill", label: "filled", meaning: "an empty section completed from your project" },
|
|
6122
|
+
replaced: { cls: "repl", label: "replaced", meaning: "rewritten from what the scan found on disk" },
|
|
6123
|
+
dropped: { cls: "drop", label: "left out", meaning: "not copied over, reason in the next column" },
|
|
6124
|
+
placeholder: { cls: "hole", label: "placeholder", meaning: "still a blank for you to fill in" }
|
|
5647
6125
|
};
|
|
6126
|
+
function tagLegend(sections) {
|
|
6127
|
+
const used = new Set(sections.map((s) => s.disposition));
|
|
6128
|
+
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("");
|
|
6129
|
+
return items ? `<ul class="taglegend">${items}</ul>` : "";
|
|
6130
|
+
}
|
|
5648
6131
|
function renderSectionsTable(sections) {
|
|
5649
6132
|
const rows = sections.map((s) => {
|
|
5650
6133
|
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>`;
|
|
6134
|
+
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
6135
|
}).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
|
|
6136
|
+
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
6137
|
}
|
|
5655
6138
|
var DIFF_LCS_LIMIT = 3e3;
|
|
5656
6139
|
function diffLines(before, after) {
|
|
@@ -5835,6 +6318,16 @@ function toolWarnings(report) {
|
|
|
5835
6318
|
}
|
|
5836
6319
|
return out.sort((a, b) => b.sessions - a.sessions);
|
|
5837
6320
|
}
|
|
6321
|
+
var APPLY_WRITES = /* @__PURE__ */ new Set([
|
|
6322
|
+
"check_permission_allowlist",
|
|
6323
|
+
"check_cmd_size",
|
|
6324
|
+
"check_cmd_structure",
|
|
6325
|
+
"check_cmd_stability",
|
|
6326
|
+
"check_cmd_scope"
|
|
6327
|
+
]);
|
|
6328
|
+
function ownerPill(fixId) {
|
|
6329
|
+
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>`;
|
|
6330
|
+
}
|
|
5838
6331
|
function renderSetupWarnings(fixes, report) {
|
|
5839
6332
|
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
5840
6333
|
const tool = toolWarnings(report);
|
|
@@ -5842,15 +6335,16 @@ function renderSetupWarnings(fixes, report) {
|
|
|
5842
6335
|
const single = tool.filter((t) => t.sessions === 1);
|
|
5843
6336
|
const items = [];
|
|
5844
6337
|
for (const f of warnFixes) {
|
|
5845
|
-
items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span
|
|
6338
|
+
items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span>${ownerPill(f.id)}</li>`);
|
|
5846
6339
|
}
|
|
5847
6340
|
for (const t of multi) {
|
|
5848
6341
|
const sentence = t.action ? ` ${esc(t.action)}` : "";
|
|
5849
6342
|
items.push(
|
|
5850
|
-
`<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span
|
|
6343
|
+
`<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span>${ownerPill("")}</li>`
|
|
5851
6344
|
);
|
|
5852
6345
|
}
|
|
5853
|
-
const
|
|
6346
|
+
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>` : "";
|
|
6347
|
+
const list = items.length > 0 ? `${ownerNote}<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
|
|
5854
6348
|
let disclosure = "";
|
|
5855
6349
|
if (single.length > 0) {
|
|
5856
6350
|
const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
|
|
@@ -5882,7 +6376,7 @@ function renderCarriedDisclosure(sections, carriedTokens) {
|
|
|
5882
6376
|
const carried = sections.filter((s) => s.disposition === "carried");
|
|
5883
6377
|
if (carried.length === 0) return "";
|
|
5884
6378
|
const names = carried.map((s) => esc(s.name)).join(" · ");
|
|
5885
|
-
const weight = carriedTokens > 0 ? `, about ${
|
|
6379
|
+
const weight = carriedTokens > 0 ? `, about ${num5(carriedTokens)} tokens` : "";
|
|
5886
6380
|
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
6381
|
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
6382
|
}
|
|
@@ -5913,7 +6407,7 @@ ${renderReceipt(input)}
|
|
|
5913
6407
|
<h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
|
|
5914
6408
|
<div class="panel">${renderComparisonTabs(input)}</div>
|
|
5915
6409
|
${input.review ? `
|
|
5916
|
-
<h2>What to change in your CLAUDE.md<span class="n">${
|
|
6410
|
+
<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>
|
|
5917
6411
|
<div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
|
|
5918
6412
|
|
|
5919
6413
|
<h2>Fixes, ranked by what they recover</h2>
|
|
@@ -5952,6 +6446,17 @@ pre.review .mark-move{background:color-mix(in srgb,var(--warn) 14%,transparent)}
|
|
|
5952
6446
|
pre.review .mark-add{background:color-mix(in srgb,var(--good) 14%,transparent)}
|
|
5953
6447
|
pre.review .skip{color:var(--ink2);font-style:italic}
|
|
5954
6448
|
.legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
|
|
6449
|
+
.taglegend{list-style:none;padding:0;margin:0 0 12px;display:flex;flex-wrap:wrap;gap:6px 16px;font-size:.78rem;color:var(--ink2)}
|
|
6450
|
+
.taglegend li{display:flex;align-items:center;gap:6px}
|
|
6451
|
+
.changes{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:10px}
|
|
6452
|
+
.changes li{line-height:1.45}
|
|
6453
|
+
.ch-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px}
|
|
6454
|
+
.changes .note{margin:2px 0 0}
|
|
6455
|
+
.tag.ch-remove{border-color:#c0504d;color:#c0504d}
|
|
6456
|
+
.tag.ch-move{border-color:#b8860b;color:#b8860b}
|
|
6457
|
+
.tag.ch-add{border-color:var(--accent);color:var(--accent)}
|
|
6458
|
+
.filedrop{margin-top:14px}
|
|
6459
|
+
.filedrop summary{cursor:pointer;font-size:.82rem;color:var(--ink2)}
|
|
5955
6460
|
.legend b{font-weight:650}
|
|
5956
6461
|
.legend .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 12px}
|
|
5957
6462
|
.legend .sw.r{background:color-mix(in srgb,var(--bad) 50%,transparent)}
|
|
@@ -5981,7 +6486,7 @@ function renderLines(lines, keepRunMax) {
|
|
|
5981
6486
|
const tail = run.slice(run.length - half);
|
|
5982
6487
|
for (const i of head) out.push(lineHtml(lines[i], i + 1));
|
|
5983
6488
|
out.push(
|
|
5984
|
-
`<span class="ln skip"><span class="g"></span>... ${
|
|
6489
|
+
`<span class="ln skip"><span class="g"></span>... ${num5(run.length - head.length - tail.length)} unchanged lines ...</span>`
|
|
5985
6490
|
);
|
|
5986
6491
|
for (const i of tail) out.push(lineHtml(lines[i], i + 1));
|
|
5987
6492
|
} else {
|
|
@@ -6001,6 +6506,35 @@ function renderLines(lines, keepRunMax) {
|
|
|
6001
6506
|
flush();
|
|
6002
6507
|
return `<pre class="review">${out.join("")}</pre>`;
|
|
6003
6508
|
}
|
|
6509
|
+
var CHANGE_KIND = {
|
|
6510
|
+
remove: { label: "remove", cls: "ch-remove" },
|
|
6511
|
+
move: { label: "move out", cls: "ch-move" },
|
|
6512
|
+
add: { label: "add", cls: "ch-add" }
|
|
6513
|
+
};
|
|
6514
|
+
function renderChangeList(review) {
|
|
6515
|
+
const changes = [...review.changes].sort((a, b) => b.tokens - a.tokens);
|
|
6516
|
+
if (changes.length === 0) {
|
|
6517
|
+
return `<p class="note">Nothing to change in ${esc(review.label)}.</p>`;
|
|
6518
|
+
}
|
|
6519
|
+
const counts = { remove: 0, move: 0, add: 0 };
|
|
6520
|
+
let tokens = 0;
|
|
6521
|
+
for (const c of changes) {
|
|
6522
|
+
counts[c.kind] += 1;
|
|
6523
|
+
if (c.kind !== "add") tokens += c.tokens;
|
|
6524
|
+
}
|
|
6525
|
+
const parts = [];
|
|
6526
|
+
if (counts.remove > 0) parts.push(`${num5(counts.remove)} to remove`);
|
|
6527
|
+
if (counts.move > 0) parts.push(`${num5(counts.move)} to move out`);
|
|
6528
|
+
if (counts.add > 0) parts.push(`${num5(counts.add)} to add`);
|
|
6529
|
+
const saving = tokens > 0 ? ` Removing and moving those takes about ${num5(tokens)} tokens off every turn.` : "";
|
|
6530
|
+
const items = changes.map((c) => {
|
|
6531
|
+
const kind = CHANGE_KIND[c.kind];
|
|
6532
|
+
const dest = c.destination ? ` <span class="note">to ${esc(c.destination)}</span>` : "";
|
|
6533
|
+
const size = c.tokens > 0 ? `<span class="pill">~${num5(c.tokens)} tokens</span>` : "";
|
|
6534
|
+
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>`;
|
|
6535
|
+
}).join("");
|
|
6536
|
+
return `<p class="note" style="margin-top:0"><b>${parts.join(", ")}.</b>${saving}</p><ol class="changes">${items}</ol>`;
|
|
6537
|
+
}
|
|
6004
6538
|
function renderAnnotatedFile(review) {
|
|
6005
6539
|
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
6540
|
if (review.missing) {
|
|
@@ -6010,12 +6544,13 @@ function renderAnnotatedFile(review) {
|
|
|
6010
6544
|
}
|
|
6011
6545
|
return legend + `<p class="note">${esc(review.label)} does not exist yet. Proposed content:</p>` + renderLines(adds, 0);
|
|
6012
6546
|
}
|
|
6013
|
-
|
|
6547
|
+
const annotated = legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
|
|
6548
|
+
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
6549
|
}
|
|
6015
6550
|
function reviewCountLine(review) {
|
|
6016
6551
|
const n = review.changes.length;
|
|
6017
6552
|
if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
|
|
6018
|
-
return `<b>${
|
|
6553
|
+
return `<b>${num5(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
|
|
6019
6554
|
}
|
|
6020
6555
|
var INDEX_STYLE = `
|
|
6021
6556
|
.rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
|
|
@@ -6040,15 +6575,36 @@ function indexStatus(appliedAt) {
|
|
|
6040
6575
|
if (!appliedAt) return `<span class="state off">not applied</span>`;
|
|
6041
6576
|
return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
|
|
6042
6577
|
}
|
|
6043
|
-
function actionForm(token, slug, action, label, primary) {
|
|
6044
|
-
return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}>${esc(label)}</button></form>`;
|
|
6578
|
+
function actionForm(token, slug, action, label, primary, hint = "") {
|
|
6579
|
+
return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}${hint ? ` title="${esc(hint)}"` : ""}>${esc(label)}</button></form>`;
|
|
6045
6580
|
}
|
|
6046
6581
|
function indexActions(row, serve) {
|
|
6047
6582
|
const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
|
|
6048
6583
|
if (!serve) {
|
|
6049
6584
|
return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
|
|
6050
6585
|
}
|
|
6051
|
-
return `<div class="acts">` + actionForm(
|
|
6586
|
+
return `<div class="acts">` + actionForm(
|
|
6587
|
+
serve.token,
|
|
6588
|
+
row.slug,
|
|
6589
|
+
"include",
|
|
6590
|
+
"Apply CLAUDE.md",
|
|
6591
|
+
true,
|
|
6592
|
+
"Writes .claude/costclaw.md and adds one import line to this project's CLAUDE.md. Every line you wrote stays."
|
|
6593
|
+
) + actionForm(
|
|
6594
|
+
serve.token,
|
|
6595
|
+
row.slug,
|
|
6596
|
+
"settings",
|
|
6597
|
+
"Apply permissions",
|
|
6598
|
+
false,
|
|
6599
|
+
"Merges the suggested permission allowlist into this project's settings file. Nothing is removed."
|
|
6600
|
+
) + actionForm(
|
|
6601
|
+
serve.token,
|
|
6602
|
+
row.slug,
|
|
6603
|
+
"remove",
|
|
6604
|
+
"Undo",
|
|
6605
|
+
false,
|
|
6606
|
+
"Removes the costclaw include and the import line this page added."
|
|
6607
|
+
) + `</div><p class="note" style="margin-top:6px"><strong>Apply CLAUDE.md</strong> writes <span class="mono">.claude/costclaw.md</span> and one import line. <strong>Apply permissions</strong> merges the allowlist into your settings file. They are independent, both are additive, and <strong>Undo</strong> reverses the first. ${details}</p>`;
|
|
6052
6608
|
}
|
|
6053
6609
|
function renderPromptPanel(review) {
|
|
6054
6610
|
return `<div class="panel"><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="14" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run the line below. It covers your global CLAUDE.md and every project on this page, so there is one prompt, not one per project.</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code><p class="note">costclaw never calls a model: this work order is deterministic text built from your own audit. Your agent does the editing, with your approval.</p></div>`;
|
|
@@ -6056,8 +6612,8 @@ function renderPromptPanel(review) {
|
|
|
6056
6612
|
function renderGlobalPanel(review) {
|
|
6057
6613
|
const t = review.tokens;
|
|
6058
6614
|
const importCount = review.importCount;
|
|
6059
|
-
const imported = importCount > 0 ? ` plus ${
|
|
6060
|
-
const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${
|
|
6615
|
+
const imported = importCount > 0 ? ` plus ${num5(importCount)} imported ${plural2(importCount, "file")}` : "";
|
|
6616
|
+
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
6617
|
return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
|
|
6062
6618
|
}
|
|
6063
6619
|
function renderProjectPanels(input, review) {
|
|
@@ -6066,7 +6622,7 @@ function renderProjectPanels(input, review) {
|
|
|
6066
6622
|
const r = review.projects.get(row.slug);
|
|
6067
6623
|
if (!r) return;
|
|
6068
6624
|
out.push(
|
|
6069
|
-
`<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${
|
|
6625
|
+
`<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
6626
|
);
|
|
6071
6627
|
});
|
|
6072
6628
|
return out.join("");
|
|
@@ -6120,7 +6676,7 @@ Nothing was written inside any project. No network calls, no telemetry, no model
|
|
|
6120
6676
|
|
|
6121
6677
|
// src/project-scan.ts
|
|
6122
6678
|
import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
|
|
6123
|
-
import { join as join8, basename } from "path";
|
|
6679
|
+
import { join as join8, basename as basename2 } from "path";
|
|
6124
6680
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
6125
6681
|
"node_modules",
|
|
6126
6682
|
".git",
|
|
@@ -6594,7 +7150,7 @@ function parseReadme(text2) {
|
|
|
6594
7150
|
return { name, description };
|
|
6595
7151
|
}
|
|
6596
7152
|
async function scanProject(dir) {
|
|
6597
|
-
const profile = emptyProfile(
|
|
7153
|
+
const profile = emptyProfile(basename2(dir));
|
|
6598
7154
|
const { files, dirs } = await listEntries(dir);
|
|
6599
7155
|
if (files.includes("package.json")) {
|
|
6600
7156
|
const pkg = parseJson(await readText(join8(dir, "package.json")));
|
|
@@ -6617,13 +7173,13 @@ async function scanProject(dir) {
|
|
|
6617
7173
|
}
|
|
6618
7174
|
}
|
|
6619
7175
|
}
|
|
6620
|
-
if (profile.description === null || profile.name ===
|
|
7176
|
+
if (profile.description === null || profile.name === basename2(dir)) {
|
|
6621
7177
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
6622
7178
|
if (readmeName) {
|
|
6623
7179
|
const text2 = await readText(join8(dir, readmeName));
|
|
6624
7180
|
if (text2 !== null) {
|
|
6625
7181
|
const parsed = parseReadme(text2);
|
|
6626
|
-
if (profile.name ===
|
|
7182
|
+
if (profile.name === basename2(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
6627
7183
|
if (profile.description === null && parsed.description !== null) {
|
|
6628
7184
|
profile.description = parsed.description;
|
|
6629
7185
|
}
|
|
@@ -6643,7 +7199,7 @@ async function scanProject(dir) {
|
|
|
6643
7199
|
import { createServer } from "http";
|
|
6644
7200
|
import { randomBytes } from "crypto";
|
|
6645
7201
|
import { readFile as readFile8 } from "fs/promises";
|
|
6646
|
-
import { extname, resolve as
|
|
7202
|
+
import { extname, resolve as resolve4, sep as sep2 } from "path";
|
|
6647
7203
|
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
6648
7204
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
6649
7205
|
var DASHBOARD_NAME = "DASHBOARD.html";
|
|
@@ -6668,8 +7224,8 @@ function safeArtifactPath(root, urlPath) {
|
|
|
6668
7224
|
return null;
|
|
6669
7225
|
}
|
|
6670
7226
|
if (decoded.includes("\0")) return null;
|
|
6671
|
-
const resolvedRoot =
|
|
6672
|
-
const full =
|
|
7227
|
+
const resolvedRoot = resolve4(root);
|
|
7228
|
+
const full = resolve4(resolvedRoot, "." + decoded);
|
|
6673
7229
|
if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
|
|
6674
7230
|
return full;
|
|
6675
7231
|
}
|
|
@@ -6866,7 +7422,7 @@ async function startApplyServer(opts) {
|
|
|
6866
7422
|
|
|
6867
7423
|
// src/optimize-manifest.ts
|
|
6868
7424
|
import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
|
|
6869
|
-
import { join as join9, resolve as
|
|
7425
|
+
import { join as join9, resolve as resolve5 } from "path";
|
|
6870
7426
|
var MANIFEST_NAME = "index.json";
|
|
6871
7427
|
function defaultOptimizeRoot(home) {
|
|
6872
7428
|
return join9(home, ".costclaw", "optimize");
|
|
@@ -6900,7 +7456,7 @@ async function writeManifest(root, m) {
|
|
|
6900
7456
|
await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
|
|
6901
7457
|
}
|
|
6902
7458
|
function normalizePath(p) {
|
|
6903
|
-
const r =
|
|
7459
|
+
const r = resolve5(p);
|
|
6904
7460
|
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
6905
7461
|
}
|
|
6906
7462
|
function findEntry(m, projectDir) {
|
|
@@ -6937,7 +7493,7 @@ var DEFAULT_LIMIT = 10;
|
|
|
6937
7493
|
function usd6(n) {
|
|
6938
7494
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
6939
7495
|
}
|
|
6940
|
-
function
|
|
7496
|
+
function num6(n) {
|
|
6941
7497
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
6942
7498
|
}
|
|
6943
7499
|
function describeDetection(project) {
|
|
@@ -6974,7 +7530,7 @@ function projectRecoverable(report, slug) {
|
|
|
6974
7530
|
return row ? row.usd : null;
|
|
6975
7531
|
}
|
|
6976
7532
|
async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
6977
|
-
const slug =
|
|
7533
|
+
const slug = basename3(resolve6(projectDir));
|
|
6978
7534
|
let currentClaudeMd = ctx.claudeMdOverride;
|
|
6979
7535
|
let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
|
|
6980
7536
|
if (currentClaudeMd === void 0) {
|
|
@@ -7055,11 +7611,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7055
7611
|
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
7056
7612
|
const dir = after > before ? "larger" : "smaller";
|
|
7057
7613
|
lines.push(
|
|
7058
|
-
`Your CLAUDE.md: an estimated ${
|
|
7614
|
+
`Your CLAUDE.md: an estimated ${num6(before)} tokens to ${num6(after)} (${pct2}% ${dir}), paid on every turn.`
|
|
7059
7615
|
);
|
|
7060
7616
|
if (result.carriedTokens >= after / 2) {
|
|
7061
7617
|
lines.push(
|
|
7062
|
-
`About ${
|
|
7618
|
+
`About ${num6(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
7063
7619
|
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
7064
7620
|
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
7065
7621
|
);
|
|
@@ -7074,7 +7630,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7074
7630
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
7075
7631
|
if (review.changes.length > 0) {
|
|
7076
7632
|
const n = review.changes.length;
|
|
7077
|
-
lines.push(`Review: ${
|
|
7633
|
+
lines.push(`Review: ${num6(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
|
|
7078
7634
|
}
|
|
7079
7635
|
lines.push(`Artifacts: ${artifactsDir}`);
|
|
7080
7636
|
lines.push(`Apply: ${applyCommand}`);
|
|
@@ -7082,7 +7638,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
7082
7638
|
return {
|
|
7083
7639
|
entry: {
|
|
7084
7640
|
slug,
|
|
7085
|
-
dir:
|
|
7641
|
+
dir: basename3(artifactsDir),
|
|
7086
7642
|
projectDir,
|
|
7087
7643
|
artifactsDir,
|
|
7088
7644
|
spendUsd: spend ?? 0,
|
|
@@ -7273,7 +7829,7 @@ async function runOptimize(opts) {
|
|
|
7273
7829
|
const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
|
|
7274
7830
|
lines.push("");
|
|
7275
7831
|
lines.push(
|
|
7276
|
-
`Your CLAUDE.md review: ${
|
|
7832
|
+
`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
7833
|
);
|
|
7278
7834
|
lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
|
|
7279
7835
|
lines.push(` claude "Follow ${upgradeAllPath}"`);
|
|
@@ -7326,7 +7882,7 @@ async function runOptimize(opts) {
|
|
|
7326
7882
|
|
|
7327
7883
|
// src/badge-command.ts
|
|
7328
7884
|
import { writeFile as writeFile7 } from "fs/promises";
|
|
7329
|
-
import { resolve as
|
|
7885
|
+
import { resolve as resolve7 } from "path";
|
|
7330
7886
|
|
|
7331
7887
|
// src/badge.ts
|
|
7332
7888
|
var HEIGHT2 = 20;
|
|
@@ -7350,7 +7906,7 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
|
7350
7906
|
async function runBadge(opts) {
|
|
7351
7907
|
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
7352
7908
|
const svg = renderBadge(record);
|
|
7353
|
-
const target =
|
|
7909
|
+
const target = resolve7(opts.out || DEFAULT_BADGE_FILE);
|
|
7354
7910
|
await writeFile7(target, svg, "utf8");
|
|
7355
7911
|
return { output: `Badge written to ${target}`, record, target };
|
|
7356
7912
|
}
|
|
@@ -7554,7 +8110,7 @@ function parseApplyFlags(args) {
|
|
|
7554
8110
|
};
|
|
7555
8111
|
}
|
|
7556
8112
|
function cliVersion() {
|
|
7557
|
-
return true ? "0.
|
|
8113
|
+
return true ? "0.13.0" : "0.0.0-dev";
|
|
7558
8114
|
}
|
|
7559
8115
|
function isHelpRequest(command, args) {
|
|
7560
8116
|
if (command === void 0) return false;
|