costclaw 0.1.0 → 0.2.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/dist/index.js +1669 -60
- package/package.json +12 -5
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/audit-command.ts
|
|
4
|
-
import { readFile as
|
|
4
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
5
5
|
|
|
6
6
|
// ../../packages/engine/src/types.ts
|
|
7
7
|
function emptyTotals() {
|
|
@@ -49,8 +49,20 @@ function cacheHitRate(totals) {
|
|
|
49
49
|
if (!denom) return 0;
|
|
50
50
|
return num(totals.cache_read_tokens) / denom;
|
|
51
51
|
}
|
|
52
|
+
function costForTotals(model, totals) {
|
|
53
|
+
const p = priceFor(model);
|
|
54
|
+
return (totals.input_tokens * p.input + totals.output_tokens * p.output + totals.cache_creation_tokens * p.cache_write + totals.cache_read_tokens * p.cache_read) / 1e6;
|
|
55
|
+
}
|
|
56
|
+
function isOpus(model) {
|
|
57
|
+
if (!model) return false;
|
|
58
|
+
return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
|
|
59
|
+
}
|
|
52
60
|
|
|
53
61
|
// ../../packages/engine/src/sanitize.ts
|
|
62
|
+
var EM_OR_EN = /[—–]/;
|
|
63
|
+
function hasEmDash(text) {
|
|
64
|
+
return EM_OR_EN.test(text);
|
|
65
|
+
}
|
|
54
66
|
function sanitizeText(input) {
|
|
55
67
|
let out = input;
|
|
56
68
|
out = out.replace(/[‘’‚‛]/g, "'");
|
|
@@ -134,7 +146,10 @@ function parseSession(text, opts = {}) {
|
|
|
134
146
|
cache_savings_usd: 0,
|
|
135
147
|
toolUsage: {},
|
|
136
148
|
toolEvents: [],
|
|
137
|
-
skippedLines: 0
|
|
149
|
+
skippedLines: 0,
|
|
150
|
+
kind: opts.kind ?? "main",
|
|
151
|
+
parentSessionId: opts.parentSessionId ?? null,
|
|
152
|
+
turnCache: []
|
|
138
153
|
};
|
|
139
154
|
const seen = /* @__PURE__ */ new Set();
|
|
140
155
|
const modelCounts = /* @__PURE__ */ new Map();
|
|
@@ -181,6 +196,10 @@ function parseSession(text, opts = {}) {
|
|
|
181
196
|
s.totals.cache_read_tokens += Number(usage.cache_read_input_tokens) || 0;
|
|
182
197
|
s.cost_usd += costForUsage(model, usage);
|
|
183
198
|
s.cache_savings_usd += cacheSavingsForUsage(model, usage);
|
|
199
|
+
s.turnCache.push({
|
|
200
|
+
read: Number(usage.cache_read_input_tokens) || 0,
|
|
201
|
+
miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
|
|
202
|
+
});
|
|
184
203
|
}
|
|
185
204
|
}
|
|
186
205
|
}
|
|
@@ -236,15 +255,17 @@ function buildProjects(sessions) {
|
|
|
236
255
|
savings += s.cache_savings_usd;
|
|
237
256
|
}
|
|
238
257
|
const sorted = [...list].sort((a, b) => b.cost_usd - a.cost_usd);
|
|
258
|
+
const main2 = list.filter((s) => s.kind === "main");
|
|
239
259
|
projects.push({
|
|
240
260
|
slug,
|
|
241
261
|
sessions: sorted,
|
|
242
|
-
sessionsCount:
|
|
262
|
+
sessionsCount: main2.length,
|
|
263
|
+
delegatedSessionsCount: list.length - main2.length,
|
|
243
264
|
totals,
|
|
244
265
|
cost_usd: cost,
|
|
245
266
|
cache_savings_usd: savings,
|
|
246
267
|
cacheHitRate: cacheHitRate(totals),
|
|
247
|
-
modelPrimary: mostFrequent(
|
|
268
|
+
modelPrimary: mostFrequent(main2.map((s) => s.modelPrimary))
|
|
248
269
|
});
|
|
249
270
|
}
|
|
250
271
|
return projects.sort((a, b) => b.cost_usd - a.cost_usd);
|
|
@@ -255,22 +276,28 @@ function buildSummary(projects) {
|
|
|
255
276
|
let cost = 0;
|
|
256
277
|
let savings = 0;
|
|
257
278
|
let sessionsCount = 0;
|
|
279
|
+
let delegatedSessionsCount = 0;
|
|
280
|
+
let mainCostUsd = 0;
|
|
258
281
|
let durationHours = 0;
|
|
259
282
|
for (const p of projects) {
|
|
260
283
|
addTotals(totals, p.totals);
|
|
261
284
|
cost += p.cost_usd;
|
|
262
285
|
savings += p.cache_savings_usd;
|
|
263
286
|
sessionsCount += p.sessionsCount;
|
|
287
|
+
delegatedSessionsCount += p.delegatedSessionsCount;
|
|
264
288
|
for (const s of p.sessions) {
|
|
265
289
|
const key = s.modelPrimary || "unknown";
|
|
266
290
|
modelBreakdown[key] = (modelBreakdown[key] ?? 0) + s.cost_usd;
|
|
291
|
+
if (s.kind === "main") mainCostUsd += s.cost_usd;
|
|
267
292
|
if (s.durationMinutes && s.durationMinutes > 0) durationHours += s.durationMinutes / 60;
|
|
268
293
|
}
|
|
269
294
|
}
|
|
270
295
|
return {
|
|
271
296
|
projectsCount: projects.length,
|
|
272
297
|
sessionsCount,
|
|
298
|
+
delegatedSessionsCount,
|
|
273
299
|
cost_usd: cost,
|
|
300
|
+
mainCostUsd,
|
|
274
301
|
cache_savings_usd: savings,
|
|
275
302
|
totals,
|
|
276
303
|
modelBreakdown,
|
|
@@ -286,6 +313,29 @@ var HOT_PROJECT_SHARE = 0.6;
|
|
|
286
313
|
var HEAVY_TOOL_FIRES = 100;
|
|
287
314
|
var SHORT_SESSION_MAX_MINUTES = 10;
|
|
288
315
|
var SHORT_SESSION_MIN_COST = 5;
|
|
316
|
+
var MARATHON_MIN_TURNS = 40;
|
|
317
|
+
var MARATHON_MIN_COST = 2;
|
|
318
|
+
var DECAY_DROP = 0.25;
|
|
319
|
+
var LATE_FLOOR = 0.5;
|
|
320
|
+
var MISROUTE_MAX_TURNS = 12;
|
|
321
|
+
var MISROUTE_MAX_MINUTES = 15;
|
|
322
|
+
var MISROUTE_MAX_BASH = 3;
|
|
323
|
+
var MISROUTE_MAX_OUTPUT = 4e3;
|
|
324
|
+
var MISROUTE_MIN_EXPOSURE = 0.5;
|
|
325
|
+
var MISROUTE_BASELINE = "claude-sonnet-4-6";
|
|
326
|
+
var WORKFLOW_MIN_COST = 5;
|
|
327
|
+
var WORKFLOW_WARN_SHARE = 0.5;
|
|
328
|
+
function thirdHit(turns, lo, hi) {
|
|
329
|
+
let read = 0;
|
|
330
|
+
let total = 0;
|
|
331
|
+
for (let i = lo; i < hi; i++) {
|
|
332
|
+
const t = turns[i];
|
|
333
|
+
if (!t) continue;
|
|
334
|
+
read += t.read;
|
|
335
|
+
total += t.read + t.miss;
|
|
336
|
+
}
|
|
337
|
+
return { read, total };
|
|
338
|
+
}
|
|
289
339
|
function severityForSavings(savings) {
|
|
290
340
|
if (savings >= 50) return "critical";
|
|
291
341
|
if (savings >= 10) return "warn";
|
|
@@ -294,15 +344,15 @@ function severityForSavings(savings) {
|
|
|
294
344
|
function ruleBadCacheHit(ctx) {
|
|
295
345
|
const out = [];
|
|
296
346
|
for (const proj of ctx.projects) {
|
|
297
|
-
const sorted = [...proj.sessions].sort((a, b) => (a.startedAt || "").localeCompare(b.startedAt || ""));
|
|
347
|
+
const sorted = [...proj.sessions].filter((s) => s.kind === "main").sort((a, b) => (a.startedAt || "").localeCompare(b.startedAt || ""));
|
|
298
348
|
if (sorted.length < STREAK) continue;
|
|
299
349
|
const tail = sorted.slice(-STREAK);
|
|
300
350
|
if (!tail.every((s) => cacheHitRate(s.totals) < HIT_FLOOR)) continue;
|
|
301
351
|
const last = tail[tail.length - 1];
|
|
302
352
|
if (!last) continue;
|
|
303
|
-
const p = priceFor(proj.modelPrimary);
|
|
304
353
|
let savings = 0;
|
|
305
354
|
for (const s of tail) {
|
|
355
|
+
const p = priceFor(s.modelPrimary);
|
|
306
356
|
savings += (s.totals.cache_creation_tokens + s.totals.input_tokens) * (p.input - p.cache_read) / 1e6;
|
|
307
357
|
}
|
|
308
358
|
out.push({
|
|
@@ -340,21 +390,31 @@ function ruleHotProject(ctx) {
|
|
|
340
390
|
function ruleHeavyToolLoops(ctx) {
|
|
341
391
|
const out = [];
|
|
342
392
|
for (const proj of ctx.projects) {
|
|
393
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
343
394
|
for (const s of proj.sessions) {
|
|
395
|
+
if (s.kind !== "main") continue;
|
|
344
396
|
for (const [tool, fires] of Object.entries(s.toolUsage)) {
|
|
345
397
|
if (fires < HEAVY_TOOL_FIRES) continue;
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
description: `${tool} fired ${fires} times in a single session, a sign of a stuck loop or unscoped search.`,
|
|
352
|
-
suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
|
|
353
|
-
estimatedMonthlySavingsUsd: 0,
|
|
354
|
-
evidence: { tool, fires, sessionUuid: s.sessionUuid }
|
|
355
|
-
});
|
|
398
|
+
const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
|
|
399
|
+
entry.sessionsAffected += 1;
|
|
400
|
+
entry.maxFires = Math.max(entry.maxFires, fires);
|
|
401
|
+
if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
|
|
402
|
+
byTool.set(tool, entry);
|
|
356
403
|
}
|
|
357
404
|
}
|
|
405
|
+
for (const [tool, e] of byTool) {
|
|
406
|
+
const n = e.sessionsAffected;
|
|
407
|
+
out.push({
|
|
408
|
+
ruleId: "HEAVY_TOOL_LOOPS",
|
|
409
|
+
severity: "warn",
|
|
410
|
+
project: proj.slug,
|
|
411
|
+
title: `Heavy ${tool} usage in ${n} session${n === 1 ? "" : "s"}`,
|
|
412
|
+
description: `${tool} fired up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of a stuck loop or unscoped search.`,
|
|
413
|
+
suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
|
|
414
|
+
estimatedMonthlySavingsUsd: 0,
|
|
415
|
+
evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
|
|
416
|
+
});
|
|
417
|
+
}
|
|
358
418
|
}
|
|
359
419
|
return out;
|
|
360
420
|
}
|
|
@@ -362,6 +422,7 @@ function ruleShortSessionBloat(ctx) {
|
|
|
362
422
|
const out = [];
|
|
363
423
|
for (const proj of ctx.projects) {
|
|
364
424
|
for (const s of proj.sessions) {
|
|
425
|
+
if (s.kind !== "main") continue;
|
|
365
426
|
if (s.durationMinutes == null) continue;
|
|
366
427
|
if (s.durationMinutes >= SHORT_SESSION_MAX_MINUTES) continue;
|
|
367
428
|
if (s.cost_usd < SHORT_SESSION_MIN_COST) continue;
|
|
@@ -379,11 +440,105 @@ function ruleShortSessionBloat(ctx) {
|
|
|
379
440
|
}
|
|
380
441
|
return out;
|
|
381
442
|
}
|
|
443
|
+
function ruleMarathonSession(ctx) {
|
|
444
|
+
const out = [];
|
|
445
|
+
for (const proj of ctx.projects) {
|
|
446
|
+
for (const s of proj.sessions) {
|
|
447
|
+
if (s.kind !== "main") continue;
|
|
448
|
+
const n = s.turnCache.length;
|
|
449
|
+
if (n < MARATHON_MIN_TURNS) continue;
|
|
450
|
+
if (s.cost_usd < MARATHON_MIN_COST) continue;
|
|
451
|
+
const third = Math.floor(n / 3);
|
|
452
|
+
if (third === 0) continue;
|
|
453
|
+
const early = thirdHit(s.turnCache, 0, third);
|
|
454
|
+
const late = thirdHit(s.turnCache, n - third, n);
|
|
455
|
+
if (late.total === 0) continue;
|
|
456
|
+
const earlyHit = early.total > 0 ? early.read / early.total : 0;
|
|
457
|
+
const lateHit = late.total > 0 ? late.read / late.total : 0;
|
|
458
|
+
if (earlyHit - lateHit < DECAY_DROP) continue;
|
|
459
|
+
if (lateHit >= LATE_FLOOR) continue;
|
|
460
|
+
const expectedReads = late.total * earlyHit;
|
|
461
|
+
const shortfall = Math.max(0, expectedReads - late.read);
|
|
462
|
+
const p = priceFor(s.modelPrimary);
|
|
463
|
+
const savings = shortfall * (p.input - p.cache_read) / 1e6;
|
|
464
|
+
out.push({
|
|
465
|
+
ruleId: "MARATHON_SESSION",
|
|
466
|
+
severity: severityForSavings(savings),
|
|
467
|
+
project: proj.slug,
|
|
468
|
+
title: "A long session lost its cache",
|
|
469
|
+
description: `A session ran ${n} model turns; cache hit fell from ${Math.round(earlyHit * 100)}% early to ${Math.round(lateHit * 100)}% at the end, so later turns re-paid for context.`,
|
|
470
|
+
suggestedAction: "Compact or start a fresh session between tasks so the context stays small and cacheable.",
|
|
471
|
+
estimatedMonthlySavingsUsd: savings,
|
|
472
|
+
evidence: { turns: n, earlyHit, lateHit, sessionUuid: s.sessionUuid }
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
function ruleModelMisroute(ctx) {
|
|
479
|
+
const out = [];
|
|
480
|
+
for (const proj of ctx.projects) {
|
|
481
|
+
for (const s of proj.sessions) {
|
|
482
|
+
if (s.kind !== "main") continue;
|
|
483
|
+
if (!isOpus(s.modelPrimary)) continue;
|
|
484
|
+
if (s.turnCache.length > MISROUTE_MAX_TURNS) continue;
|
|
485
|
+
if (s.durationMinutes == null || s.durationMinutes > MISROUTE_MAX_MINUTES) continue;
|
|
486
|
+
const tu = s.toolUsage;
|
|
487
|
+
if ((tu.Edit ?? 0) + (tu.Write ?? 0) + (tu.NotebookEdit ?? 0) > 0) continue;
|
|
488
|
+
if ((tu.Bash ?? 0) > MISROUTE_MAX_BASH) continue;
|
|
489
|
+
if (s.totals.output_tokens > MISROUTE_MAX_OUTPUT) continue;
|
|
490
|
+
const exposure = s.cost_usd - costForTotals(MISROUTE_BASELINE, s.totals);
|
|
491
|
+
if (exposure < MISROUTE_MIN_EXPOSURE) continue;
|
|
492
|
+
out.push({
|
|
493
|
+
ruleId: "MODEL_MISROUTE",
|
|
494
|
+
severity: severityForSavings(exposure),
|
|
495
|
+
project: proj.slug,
|
|
496
|
+
title: "Opus used for a small task",
|
|
497
|
+
description: `An Opus session ran ${s.turnCache.length} turns in ${s.durationMinutes.toFixed(1)} minutes with light tool use and a small output; a cheaper model would have served it.`,
|
|
498
|
+
suggestedAction: "Use a cheaper model such as Sonnet for short, simple sessions, and reserve Opus for hard problems.",
|
|
499
|
+
estimatedMonthlySavingsUsd: exposure,
|
|
500
|
+
evidence: { model: s.modelPrimary, turns: s.turnCache.length, minutes: s.durationMinutes, outputTokens: s.totals.output_tokens, exposureUsd: exposure, sessionUuid: s.sessionUuid }
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return out;
|
|
505
|
+
}
|
|
506
|
+
function ruleWorkflowCost(ctx) {
|
|
507
|
+
const out = [];
|
|
508
|
+
for (const proj of ctx.projects) {
|
|
509
|
+
const delegated = proj.sessions.filter((s) => s.kind !== "main");
|
|
510
|
+
if (delegated.length === 0) continue;
|
|
511
|
+
let cost = 0;
|
|
512
|
+
let subagentRuns = 0;
|
|
513
|
+
let workflowRuns = 0;
|
|
514
|
+
for (const s of delegated) {
|
|
515
|
+
cost += s.cost_usd;
|
|
516
|
+
if (s.kind === "workflow") workflowRuns += 1;
|
|
517
|
+
else subagentRuns += 1;
|
|
518
|
+
}
|
|
519
|
+
if (cost < WORKFLOW_MIN_COST) continue;
|
|
520
|
+
const share = proj.cost_usd > 0 ? cost / proj.cost_usd : 0;
|
|
521
|
+
out.push({
|
|
522
|
+
ruleId: "WORKFLOW_COST",
|
|
523
|
+
severity: share >= WORKFLOW_WARN_SHARE ? "warn" : "info",
|
|
524
|
+
project: proj.slug,
|
|
525
|
+
title: "Workflow and subagent runs add up",
|
|
526
|
+
description: `Delegated runs (workflows and subagents) cost $${cost.toFixed(2)} in ${proj.slug}, ${Math.round(share * 100)}% of its spend.`,
|
|
527
|
+
suggestedAction: "Scope and budget workflow and subagent runs; they are a power tool, not a default.",
|
|
528
|
+
estimatedMonthlySavingsUsd: 0,
|
|
529
|
+
evidence: { delegatedCostUsd: cost, share, subagentRuns, workflowRuns }
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
382
534
|
var RULES = [
|
|
383
535
|
{ id: "BAD_CACHE_HIT", run: ruleBadCacheHit },
|
|
384
536
|
{ id: "HOT_PROJECT", run: ruleHotProject },
|
|
385
537
|
{ id: "HEAVY_TOOL_LOOPS", run: ruleHeavyToolLoops },
|
|
386
|
-
{ id: "SHORT_SESSION_BLOAT", run: ruleShortSessionBloat }
|
|
538
|
+
{ id: "SHORT_SESSION_BLOAT", run: ruleShortSessionBloat },
|
|
539
|
+
{ id: "MARATHON_SESSION", run: ruleMarathonSession },
|
|
540
|
+
{ id: "MODEL_MISROUTE", run: ruleModelMisroute },
|
|
541
|
+
{ id: "WORKFLOW_COST", run: ruleWorkflowCost }
|
|
387
542
|
];
|
|
388
543
|
function runOptimizer(ctx) {
|
|
389
544
|
const findings = [];
|
|
@@ -408,7 +563,13 @@ function runOptimizer(ctx) {
|
|
|
408
563
|
|
|
409
564
|
// ../../packages/engine/src/report.ts
|
|
410
565
|
function analyzeUploads(files) {
|
|
411
|
-
const sessions = files.map(
|
|
566
|
+
const sessions = files.map(
|
|
567
|
+
(f) => parseSession(f.text, {
|
|
568
|
+
projectSlug: f.projectSlug ?? null,
|
|
569
|
+
kind: f.kind ?? "main",
|
|
570
|
+
parentSessionId: f.parentSessionId ?? null
|
|
571
|
+
})
|
|
572
|
+
);
|
|
412
573
|
const projects = buildProjects(sessions);
|
|
413
574
|
const summary = buildSummary(projects);
|
|
414
575
|
const findings = runOptimizer({ projects, summary });
|
|
@@ -417,8 +578,11 @@ function analyzeUploads(files) {
|
|
|
417
578
|
function cacheMissExposureUsd(report) {
|
|
418
579
|
let total = 0;
|
|
419
580
|
for (const proj of report.projects) {
|
|
420
|
-
const
|
|
421
|
-
|
|
581
|
+
for (const s of proj.sessions) {
|
|
582
|
+
if (s.kind !== "main") continue;
|
|
583
|
+
const p = priceFor(s.modelPrimary);
|
|
584
|
+
total += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
|
|
585
|
+
}
|
|
422
586
|
}
|
|
423
587
|
return total;
|
|
424
588
|
}
|
|
@@ -691,6 +855,7 @@ function aggregateTools(report) {
|
|
|
691
855
|
let bash = 0;
|
|
692
856
|
for (const p of report.projects) {
|
|
693
857
|
for (const s of p.sessions) {
|
|
858
|
+
if (s.kind !== "main") continue;
|
|
694
859
|
for (const [tool, n] of Object.entries(s.toolUsage)) {
|
|
695
860
|
total += n;
|
|
696
861
|
if (tool === "Bash") bash += n;
|
|
@@ -707,7 +872,7 @@ function hasAnyDuration(report) {
|
|
|
707
872
|
}
|
|
708
873
|
return false;
|
|
709
874
|
}
|
|
710
|
-
function buildChecks(report, cmd, answers) {
|
|
875
|
+
function buildChecks(report, cmd, answers, setup) {
|
|
711
876
|
const checks = [];
|
|
712
877
|
const s = report.summary;
|
|
713
878
|
checks.push(
|
|
@@ -772,7 +937,10 @@ function buildChecks(report, cmd, answers) {
|
|
|
772
937
|
checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
|
|
773
938
|
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
|
|
774
939
|
const thrashSessions = new Set(
|
|
775
|
-
heavyLoops.
|
|
940
|
+
heavyLoops.flatMap((f) => {
|
|
941
|
+
const uuids = f.evidence?.["sessionUuids"];
|
|
942
|
+
return Array.isArray(uuids) ? uuids.filter((v) => typeof v === "string") : [];
|
|
943
|
+
})
|
|
776
944
|
).size;
|
|
777
945
|
const thrashShare = s.sessionsCount > 0 ? thrashSessions / s.sessionsCount : 0;
|
|
778
946
|
const thrashPct = Math.round(thrashShare * 100);
|
|
@@ -804,8 +972,49 @@ function buildChecks(report, cmd, answers) {
|
|
|
804
972
|
)
|
|
805
973
|
);
|
|
806
974
|
checks.push(questionnaireCheck("session_scope", "Session scoping", answers));
|
|
807
|
-
|
|
808
|
-
|
|
975
|
+
const marathon = report.findings.filter((f) => f.ruleId === "MARATHON_SESSION");
|
|
976
|
+
const marathonSessions = new Set(
|
|
977
|
+
marathon.map((f) => f.evidence?.["sessionUuid"]).filter((v) => typeof v === "string")
|
|
978
|
+
).size;
|
|
979
|
+
const marathonShare = s.sessionsCount > 0 ? marathonSessions / s.sessionsCount : 0;
|
|
980
|
+
const marathonPct = Math.round(marathonShare * 100);
|
|
981
|
+
checks.push(
|
|
982
|
+
makeCheck(
|
|
983
|
+
"session_marathon",
|
|
984
|
+
"session_mgmt",
|
|
985
|
+
"Session length",
|
|
986
|
+
s.sessionsCount > 0 ? clamp2(100 - marathonShare * 180) : null,
|
|
987
|
+
s.sessionsCount === 0 ? "No sessions to assess." : marathonSessions === 0 ? "No long session ran until the cache stopped helping." : `${marathonSessions} of ${s.sessionsCount} sessions (${marathonPct}%) ran long until the cache stopped helping.`,
|
|
988
|
+
"metrics"
|
|
989
|
+
)
|
|
990
|
+
);
|
|
991
|
+
if (setup) {
|
|
992
|
+
const permScore = setup.hasPermissionConfig ? clamp2(60 + Math.min(setup.permissionAllowCount, 8) * 5) : 25;
|
|
993
|
+
checks.push(
|
|
994
|
+
makeCheck(
|
|
995
|
+
"permission_allowlist",
|
|
996
|
+
"tooling",
|
|
997
|
+
"Permission allowlist",
|
|
998
|
+
permScore,
|
|
999
|
+
setup.hasPermissionConfig ? `Your settings define ${setup.permissionAllowCount} allow and ${setup.permissionDenyCount} deny rules, which cut approval round trips.` : "No permission allowlist was found in your settings.",
|
|
1000
|
+
"metrics"
|
|
1001
|
+
)
|
|
1002
|
+
);
|
|
1003
|
+
const mcpScore = setup.mcpServerCount === 0 ? 100 : clamp2(100 - Math.max(0, setup.mcpServerCount - 2) * 15);
|
|
1004
|
+
checks.push(
|
|
1005
|
+
makeCheck(
|
|
1006
|
+
"mcp_scoped",
|
|
1007
|
+
"tooling",
|
|
1008
|
+
"MCP and tool scope",
|
|
1009
|
+
mcpScore,
|
|
1010
|
+
setup.mcpServerCount === 0 ? "No MCP servers are configured, so there is no tool-definition context overhead." : `${setup.mcpServerCount} MCP server${setup.mcpServerCount === 1 ? "" : "s"} configured; every loaded tool definition is context you pay for each turn.`,
|
|
1011
|
+
"metrics"
|
|
1012
|
+
)
|
|
1013
|
+
);
|
|
1014
|
+
} else {
|
|
1015
|
+
checks.push(questionnaireCheck("mcp_scoped", "MCP and tool scope", answers));
|
|
1016
|
+
checks.push(questionnaireCheck("permission_allowlist", "Permission allowlist", answers));
|
|
1017
|
+
}
|
|
809
1018
|
const tools = aggregateTools(report);
|
|
810
1019
|
const bashShare = tools.total > 0 ? tools.bash / tools.total : 0;
|
|
811
1020
|
checks.push(
|
|
@@ -819,7 +1028,7 @@ function buildChecks(report, cmd, answers) {
|
|
|
819
1028
|
)
|
|
820
1029
|
);
|
|
821
1030
|
const exposure = cacheMissExposureUsd(report);
|
|
822
|
-
const spend = s.
|
|
1031
|
+
const spend = s.mainCostUsd;
|
|
823
1032
|
const exposureShare = spend > 0 ? exposure / spend : 0;
|
|
824
1033
|
checks.push(
|
|
825
1034
|
makeCheck(
|
|
@@ -831,12 +1040,33 @@ function buildChecks(report, cmd, answers) {
|
|
|
831
1040
|
"metrics"
|
|
832
1041
|
)
|
|
833
1042
|
);
|
|
1043
|
+
let opusMain = 0;
|
|
1044
|
+
for (const p of report.projects) {
|
|
1045
|
+
for (const sess of p.sessions) {
|
|
1046
|
+
if (sess.kind === "main" && isOpus(sess.modelPrimary)) opusMain += 1;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
const misroute = report.findings.filter((f) => f.ruleId === "MODEL_MISROUTE");
|
|
1050
|
+
const misrouteSessions = new Set(
|
|
1051
|
+
misroute.map((f) => f.evidence?.["sessionUuid"]).filter((v) => typeof v === "string")
|
|
1052
|
+
).size;
|
|
1053
|
+
const misrouteShare = opusMain > 0 ? misrouteSessions / opusMain : 0;
|
|
1054
|
+
checks.push(
|
|
1055
|
+
makeCheck(
|
|
1056
|
+
"model_routing",
|
|
1057
|
+
"cost_discipline",
|
|
1058
|
+
"Model routing",
|
|
1059
|
+
opusMain > 0 ? clamp2(100 - misrouteShare * 180) : null,
|
|
1060
|
+
opusMain === 0 ? "No Opus sessions to assess for model routing." : misrouteSessions === 0 ? "No Opus session looked like a job a cheaper model could do." : `${misrouteSessions} of ${opusMain} Opus sessions looked like work a cheaper model could have done.`,
|
|
1061
|
+
"metrics"
|
|
1062
|
+
)
|
|
1063
|
+
);
|
|
834
1064
|
checks.push(questionnaireCheck("cost_monitor", "Spend monitoring", answers));
|
|
835
1065
|
checks.push(questionnaireCheck("model_choice", "Model fit", answers));
|
|
836
1066
|
return checks;
|
|
837
1067
|
}
|
|
838
|
-
function scorePillars(report, cmd, answers) {
|
|
839
|
-
const checks = buildChecks(report, cmd, answers);
|
|
1068
|
+
function scorePillars(report, cmd, answers, setup) {
|
|
1069
|
+
const checks = buildChecks(report, cmd, answers, setup);
|
|
840
1070
|
const pillars = PILLAR_ORDER.map((id) => {
|
|
841
1071
|
const cfg = PILLARS[id];
|
|
842
1072
|
const pillarChecks = checks.filter((c) => c.pillar === id);
|
|
@@ -931,13 +1161,23 @@ function synthesize(report, pillars, cmd) {
|
|
|
931
1161
|
const fixes = [];
|
|
932
1162
|
const covered = /* @__PURE__ */ new Set();
|
|
933
1163
|
const round22 = (n) => Math.round(n * 100) / 100;
|
|
934
|
-
const
|
|
1164
|
+
const usd4 = (n) => {
|
|
1165
|
+
const fixed = round22(n).toFixed(2);
|
|
1166
|
+
const dot = fixed.indexOf(".");
|
|
1167
|
+
const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1168
|
+
return `$${whole}${fixed.slice(dot)}`;
|
|
1169
|
+
};
|
|
935
1170
|
const sevForUsd = (n) => n >= 50 ? "critical" : n >= 10 ? "warn" : "info";
|
|
1171
|
+
const sWord = (k) => k === 1 ? "session" : "sessions";
|
|
936
1172
|
const exposureMaterial = exposure >= 1 && (spend === 0 || exposure / spend >= 0.05);
|
|
937
1173
|
if (exposureMaterial) {
|
|
938
1174
|
const ranked = report.projects.map((p) => {
|
|
939
|
-
|
|
940
|
-
const
|
|
1175
|
+
let contrib = 0;
|
|
1176
|
+
for (const sess of p.sessions) {
|
|
1177
|
+
if (sess.kind !== "main") continue;
|
|
1178
|
+
const rate = priceFor(sess.modelPrimary);
|
|
1179
|
+
contrib += (sess.totals.input_tokens + sess.totals.cache_creation_tokens) * (rate.input - rate.cache_read) / 1e6;
|
|
1180
|
+
}
|
|
941
1181
|
return { slug: p.slug, contrib };
|
|
942
1182
|
}).filter((r) => r.contrib > 0).sort((a, b) => b.contrib - a.contrib);
|
|
943
1183
|
const worst = ranked.slice(0, 3).map((r) => r.slug);
|
|
@@ -949,7 +1189,7 @@ function synthesize(report, pillars, cmd) {
|
|
|
949
1189
|
severity: sevForUsd(exposure),
|
|
950
1190
|
wasteUsd: round22(exposure),
|
|
951
1191
|
problem: sanitizeText(
|
|
952
|
-
`Up to ${
|
|
1192
|
+
`Up to ${usd4(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
|
|
953
1193
|
),
|
|
954
1194
|
action: sanitizeText(
|
|
955
1195
|
"Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
|
|
@@ -962,30 +1202,48 @@ function synthesize(report, pillars, cmd) {
|
|
|
962
1202
|
}
|
|
963
1203
|
const heavyByTool = /* @__PURE__ */ new Map();
|
|
964
1204
|
let shortCount = 0;
|
|
1205
|
+
let misrouteUsd = 0;
|
|
1206
|
+
const misrouteSet = /* @__PURE__ */ new Set();
|
|
1207
|
+
let marathonUsd = 0;
|
|
1208
|
+
const marathonSet = /* @__PURE__ */ new Set();
|
|
1209
|
+
let workflowUsd = 0;
|
|
965
1210
|
for (const f of report.findings) {
|
|
966
1211
|
if (f.ruleId === "HEAVY_TOOL_LOOPS" && f.evidence) {
|
|
967
1212
|
const tool = String(f.evidence["tool"] ?? "a tool");
|
|
968
|
-
const entry = heavyByTool.get(tool) ?? {
|
|
969
|
-
|
|
970
|
-
if (typeof sid === "string") entry.sessions.add(sid);
|
|
1213
|
+
const entry = heavyByTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0 };
|
|
1214
|
+
entry.sessionsAffected += Number(f.evidence["sessionsAffected"]) || 0;
|
|
971
1215
|
entry.maxFires = Math.max(entry.maxFires, Number(f.evidence["fires"]) || 0);
|
|
972
1216
|
heavyByTool.set(tool, entry);
|
|
973
1217
|
covered.add("tool_thrash");
|
|
974
1218
|
} else if (f.ruleId === "SHORT_SESSION_BLOAT") {
|
|
975
1219
|
shortCount += 1;
|
|
976
1220
|
covered.add("short_session_bloat");
|
|
1221
|
+
} else if (f.ruleId === "MODEL_MISROUTE") {
|
|
1222
|
+
misrouteUsd += Number(f.evidence?.["exposureUsd"]) || f.estimatedMonthlySavingsUsd || 0;
|
|
1223
|
+
const sid = f.evidence?.["sessionUuid"];
|
|
1224
|
+
if (typeof sid === "string") misrouteSet.add(sid);
|
|
1225
|
+
covered.add("model_choice");
|
|
1226
|
+
covered.add("model_routing");
|
|
1227
|
+
} else if (f.ruleId === "MARATHON_SESSION") {
|
|
1228
|
+
marathonUsd += f.estimatedMonthlySavingsUsd || 0;
|
|
1229
|
+
const sid = f.evidence?.["sessionUuid"];
|
|
1230
|
+
if (typeof sid === "string") marathonSet.add(sid);
|
|
1231
|
+
covered.add("session_marathon");
|
|
1232
|
+
covered.add("session_scope");
|
|
1233
|
+
} else if (f.ruleId === "WORKFLOW_COST") {
|
|
1234
|
+
workflowUsd += Number(f.evidence?.["delegatedCostUsd"]) || 0;
|
|
977
1235
|
}
|
|
978
1236
|
}
|
|
979
1237
|
for (const [tool, e] of heavyByTool) {
|
|
980
|
-
const n = Math.max(e.
|
|
1238
|
+
const n = Math.max(e.sessionsAffected, 1);
|
|
981
1239
|
fixes.push({
|
|
982
1240
|
id: `heavy_tool_${tool}`,
|
|
983
|
-
title: `Heavy ${tool} usage in ${n}
|
|
1241
|
+
title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
|
|
984
1242
|
pillar: "prompting",
|
|
985
1243
|
pillarName: PILLARS.prompting.name,
|
|
986
1244
|
severity: "warn",
|
|
987
1245
|
wasteUsd: 0,
|
|
988
|
-
problem: sanitizeText(`${tool} fired ${e.maxFires}+ times in a single session across ${n}
|
|
1246
|
+
problem: sanitizeText(`${tool} fired ${e.maxFires}+ times in a single session across ${n} ${sWord(n)}, a sign of stuck loops or unscoped work.`),
|
|
989
1247
|
action: sanitizeText(`Add a guard or narrow tasks so ${tool} is not called in a tight loop.`),
|
|
990
1248
|
basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold.")
|
|
991
1249
|
});
|
|
@@ -993,16 +1251,57 @@ function synthesize(report, pillars, cmd) {
|
|
|
993
1251
|
if (shortCount > 0) {
|
|
994
1252
|
fixes.push({
|
|
995
1253
|
id: "short_sessions",
|
|
996
|
-
title: `${shortCount} short
|
|
1254
|
+
title: `${shortCount} short ${sWord(shortCount)} cost more than expected`,
|
|
997
1255
|
pillar: "session_mgmt",
|
|
998
1256
|
pillarName: PILLARS.session_mgmt.name,
|
|
999
1257
|
severity: "warn",
|
|
1000
1258
|
wasteUsd: 0,
|
|
1001
|
-
problem: sanitizeText(`${shortCount} short
|
|
1259
|
+
problem: sanitizeText(`${shortCount} short ${sWord(shortCount)} carried a large context for a small task.`),
|
|
1002
1260
|
action: sanitizeText("Start a fresh, tightly scoped session for short tasks instead of carrying a big context."),
|
|
1003
1261
|
basis: sanitizeText("Sessions under the short-duration threshold with above-floor cost.")
|
|
1004
1262
|
});
|
|
1005
1263
|
}
|
|
1264
|
+
if (misrouteSet.size > 0) {
|
|
1265
|
+
const n = misrouteSet.size;
|
|
1266
|
+
fixes.push({
|
|
1267
|
+
id: "model_misroute",
|
|
1268
|
+
title: `Use a cheaper model for ${n} small ${sWord(n)}`,
|
|
1269
|
+
pillar: "cost_discipline",
|
|
1270
|
+
pillarName: PILLARS.cost_discipline.name,
|
|
1271
|
+
severity: sevForUsd(misrouteUsd),
|
|
1272
|
+
wasteUsd: round22(misrouteUsd),
|
|
1273
|
+
problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd4(misrouteUsd)} more than a cheaper model would have.`),
|
|
1274
|
+
action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
|
|
1275
|
+
basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
if (marathonSet.size > 0) {
|
|
1279
|
+
const n = marathonSet.size;
|
|
1280
|
+
fixes.push({
|
|
1281
|
+
id: "marathon_sessions",
|
|
1282
|
+
title: `Compact ${n} long ${sWord(n)} that lost the cache`,
|
|
1283
|
+
pillar: "session_mgmt",
|
|
1284
|
+
pillarName: PILLARS.session_mgmt.name,
|
|
1285
|
+
severity: sevForUsd(marathonUsd),
|
|
1286
|
+
wasteUsd: round22(marathonUsd),
|
|
1287
|
+
problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd4(marathonUsd)} for context in the later turns.`),
|
|
1288
|
+
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1289
|
+
basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
if (workflowUsd > 0) {
|
|
1293
|
+
fixes.push({
|
|
1294
|
+
id: "workflow_cost",
|
|
1295
|
+
title: "Scope workflow and subagent runs",
|
|
1296
|
+
pillar: "cost_discipline",
|
|
1297
|
+
pillarName: PILLARS.cost_discipline.name,
|
|
1298
|
+
severity: "info",
|
|
1299
|
+
wasteUsd: 0,
|
|
1300
|
+
problem: sanitizeText(`Workflow and subagent runs cost about ${usd4(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
|
|
1301
|
+
action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
|
|
1302
|
+
basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1006
1305
|
for (const p of pillars) {
|
|
1007
1306
|
for (const c of p.checks) {
|
|
1008
1307
|
if (!c.gap || covered.has(c.id)) continue;
|
|
@@ -1034,6 +1333,466 @@ function synthesize(report, pillars, cmd) {
|
|
|
1034
1333
|
};
|
|
1035
1334
|
}
|
|
1036
1335
|
|
|
1336
|
+
// ../../packages/engine/src/optimize.ts
|
|
1337
|
+
function usd(n) {
|
|
1338
|
+
const rounded = Math.round(n * 100) / 100;
|
|
1339
|
+
const neg = rounded < 0;
|
|
1340
|
+
const fixed = Math.abs(rounded).toFixed(2);
|
|
1341
|
+
const dot = fixed.indexOf(".");
|
|
1342
|
+
const whole = fixed.slice(0, dot);
|
|
1343
|
+
const cents = fixed.slice(dot);
|
|
1344
|
+
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1345
|
+
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
1346
|
+
}
|
|
1347
|
+
function clean(text) {
|
|
1348
|
+
return sanitizeText(text);
|
|
1349
|
+
}
|
|
1350
|
+
function weakCostDiscipline(scores) {
|
|
1351
|
+
const p = scores.find((s) => s.id === "cost_discipline");
|
|
1352
|
+
return p != null && p.assessed && p.score != null && p.score < GAP_THRESHOLD;
|
|
1353
|
+
}
|
|
1354
|
+
function hasHeavyToolFindings(report) {
|
|
1355
|
+
return report.findings.some((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
|
|
1356
|
+
}
|
|
1357
|
+
var VOLATILE_MARKER = /\b\d{4}-\d{2}-\d{2}\b|\b(updated|last update|as of|changelog|todo|fixme|wip|in progress|currently)\b/i;
|
|
1358
|
+
function carriedIntro(currentClaudeMd) {
|
|
1359
|
+
if (!currentClaudeMd) return { title: null, intro: null, introDropped: false };
|
|
1360
|
+
const raw = currentClaudeMd.trim();
|
|
1361
|
+
if (!raw) return { title: null, intro: null, introDropped: false };
|
|
1362
|
+
const lines = raw.split(/\r?\n/);
|
|
1363
|
+
const first = lines[0] ?? "";
|
|
1364
|
+
const titleMatch = first.match(/^#\s+(.+?)\s*$/);
|
|
1365
|
+
const title = titleMatch ? titleMatch[1].trim() : null;
|
|
1366
|
+
let intro = null;
|
|
1367
|
+
let introDropped = false;
|
|
1368
|
+
if (title) {
|
|
1369
|
+
const rest = [];
|
|
1370
|
+
for (let i = 1; i < lines.length; i++) {
|
|
1371
|
+
const line = (lines[i] ?? "").trim();
|
|
1372
|
+
if (rest.length === 0 && line === "") continue;
|
|
1373
|
+
if (line === "" || line.startsWith("#")) break;
|
|
1374
|
+
rest.push(line);
|
|
1375
|
+
}
|
|
1376
|
+
if (rest.length > 0) {
|
|
1377
|
+
const candidate = rest.join(" ");
|
|
1378
|
+
if (VOLATILE_MARKER.test(candidate)) {
|
|
1379
|
+
introDropped = true;
|
|
1380
|
+
} else {
|
|
1381
|
+
intro = candidate;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
return { title, intro, introDropped };
|
|
1386
|
+
}
|
|
1387
|
+
function stackOneLiner(stack) {
|
|
1388
|
+
const items = stack.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1389
|
+
if (items.length === 0) return null;
|
|
1390
|
+
let joined;
|
|
1391
|
+
if (items.length === 1) {
|
|
1392
|
+
joined = items[0];
|
|
1393
|
+
} else if (items.length === 2) {
|
|
1394
|
+
joined = `${items[0]} and ${items[1]}`;
|
|
1395
|
+
} else {
|
|
1396
|
+
joined = `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
|
|
1397
|
+
}
|
|
1398
|
+
return `A ${joined} project.`;
|
|
1399
|
+
}
|
|
1400
|
+
function buildClaudeMd(input, recoverable, notes) {
|
|
1401
|
+
const { currentClaudeMd, project } = input;
|
|
1402
|
+
const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
|
|
1403
|
+
const recoverableLine = recoverable >= 1 ? ` - Your audit valued cache-miss exposure at ${usd(recoverable)}. Keeping this file small and stable is part of recovering it; the matching PLAYBOOK.md has the rest.` : " - Keeping this file small and stable keeps the cached prefix cheap to reuse each turn.";
|
|
1404
|
+
const parts = [];
|
|
1405
|
+
parts.push(
|
|
1406
|
+
[
|
|
1407
|
+
"<!--",
|
|
1408
|
+
" CLAUDE.md scaffold generated by CostClaw (https://costclaw.io).",
|
|
1409
|
+
"",
|
|
1410
|
+
" How to use this file:",
|
|
1411
|
+
" - Replace every placeholder comment with your project's real details, then",
|
|
1412
|
+
" delete any line that does not earn its place.",
|
|
1413
|
+
" - Keep it lean. Current Anthropic guidance is under about 200 lines. For each",
|
|
1414
|
+
' line ask "would removing this make the agent make a mistake?" If not, cut it.',
|
|
1415
|
+
" - Only include what the agent cannot infer from the code: commands it cannot",
|
|
1416
|
+
" guess, conventions that differ from the language defaults, and non-obvious",
|
|
1417
|
+
" gotchas. Skip anything self-evident.",
|
|
1418
|
+
"",
|
|
1419
|
+
" Why this matters for cost:",
|
|
1420
|
+
" - Claude Code reads CLAUDE.md once at the start of a session and re-reads it",
|
|
1421
|
+
" from the prompt cache on every later turn at roughly a tenth of the input",
|
|
1422
|
+
" price. A small, stable file is cheap to cache and reuse; a bloated, churny",
|
|
1423
|
+
" one inflates every turn.",
|
|
1424
|
+
" - Keep volatile content (dates, TODOs, status notes, version numbers) out of",
|
|
1425
|
+
" this file. Put churn in a scratch note the agent opens on demand, or a",
|
|
1426
|
+
" path-scoped rule under .claude/rules/.",
|
|
1427
|
+
recoverableLine,
|
|
1428
|
+
" - Things that must happen every time (lint before commit, blocking a path)",
|
|
1429
|
+
" belong in a hook, not here: CLAUDE.md is context the agent usually follows,",
|
|
1430
|
+
" not an enforced rule.",
|
|
1431
|
+
"-->"
|
|
1432
|
+
].join("\n")
|
|
1433
|
+
);
|
|
1434
|
+
const filled = [];
|
|
1435
|
+
const projectName = project?.name?.trim() || null;
|
|
1436
|
+
const titleText = projectName ?? title ?? "Project name";
|
|
1437
|
+
if (projectName) {
|
|
1438
|
+
filled.push("Title");
|
|
1439
|
+
} else if (title) {
|
|
1440
|
+
notes.push(`Carried across the project title from your CLAUDE.md: "${title}".`);
|
|
1441
|
+
} else {
|
|
1442
|
+
notes.push("No project title was detectable, so the title is a placeholder.");
|
|
1443
|
+
}
|
|
1444
|
+
const projectDesc = project?.description?.trim() || null;
|
|
1445
|
+
const synthesized = project ? stackOneLiner(project.stack) : null;
|
|
1446
|
+
const descLine = projectDesc ?? synthesized ?? intro ?? "<!-- one line: the stack and what this project does, e.g. Node and Postgres API on Render -->";
|
|
1447
|
+
if (projectDesc) {
|
|
1448
|
+
filled.push("Description");
|
|
1449
|
+
} else if (synthesized) {
|
|
1450
|
+
filled.push("Stack");
|
|
1451
|
+
} else if (intro) {
|
|
1452
|
+
notes.push("Carried across your one-line project description.");
|
|
1453
|
+
} else if (introDropped) {
|
|
1454
|
+
notes.push(
|
|
1455
|
+
"Left your existing description out because it carried volatile markers (a date or status note) that would churn the cache."
|
|
1456
|
+
);
|
|
1457
|
+
}
|
|
1458
|
+
parts.push([`# ${titleText}`, "", descLine].join("\n"));
|
|
1459
|
+
const commands = project?.commands ?? [];
|
|
1460
|
+
if (commands.length > 0) {
|
|
1461
|
+
const lines = ["## Commands", ""];
|
|
1462
|
+
for (const c of commands) lines.push(`- \`${c.command}\` ${c.label}`);
|
|
1463
|
+
if (project?.preCommit) lines.push(`- IMPORTANT: ${project.preCommit}.`);
|
|
1464
|
+
parts.push(lines.join("\n"));
|
|
1465
|
+
filled.push("Commands");
|
|
1466
|
+
} else {
|
|
1467
|
+
parts.push(
|
|
1468
|
+
[
|
|
1469
|
+
"## Commands",
|
|
1470
|
+
"",
|
|
1471
|
+
"<!--",
|
|
1472
|
+
" The commands the agent cannot guess. Include test, lint, typecheck, build,",
|
|
1473
|
+
" the dev server, and how to run a SINGLE test. Put the exact pre-commit gate",
|
|
1474
|
+
" here. Example:",
|
|
1475
|
+
" - `npm run dev` starts the dev server on port 3000",
|
|
1476
|
+
" - `npm test -- src/users.test.ts` runs one test file",
|
|
1477
|
+
" - IMPORTANT: run `npm run lint && npm run typecheck` before committing",
|
|
1478
|
+
"-->",
|
|
1479
|
+
"- <!-- install or first-run setup -->",
|
|
1480
|
+
"- <!-- run / dev server -->",
|
|
1481
|
+
"- <!-- run the tests, and how to run ONE test -->",
|
|
1482
|
+
"- <!-- lint and typecheck -->",
|
|
1483
|
+
"- IMPORTANT: run <!-- your checks --> before committing."
|
|
1484
|
+
].join("\n")
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
const structure = project?.structure ?? [];
|
|
1488
|
+
if (structure.length > 0) {
|
|
1489
|
+
const lines = ["## Project structure", ""];
|
|
1490
|
+
for (const d of structure) {
|
|
1491
|
+
const note = d.note.trim();
|
|
1492
|
+
lines.push(note ? `- \`${d.path}\` ${note}` : `- \`${d.path}\``);
|
|
1493
|
+
}
|
|
1494
|
+
parts.push(lines.join("\n"));
|
|
1495
|
+
filled.push("Project structure");
|
|
1496
|
+
} else {
|
|
1497
|
+
parts.push(
|
|
1498
|
+
[
|
|
1499
|
+
"## Project structure",
|
|
1500
|
+
"",
|
|
1501
|
+
"<!--",
|
|
1502
|
+
" Where things live, as a short map. Five to ten bullets, not a file-by-file",
|
|
1503
|
+
" tour (the agent can read the tree). Example:",
|
|
1504
|
+
" - `src/routes/` request handlers",
|
|
1505
|
+
" - `src/db/` schema and queries",
|
|
1506
|
+
"-->",
|
|
1507
|
+
"- `<!-- path -->` <!-- what lives here -->",
|
|
1508
|
+
"- `<!-- path -->` <!-- what lives here -->"
|
|
1509
|
+
].join("\n")
|
|
1510
|
+
);
|
|
1511
|
+
}
|
|
1512
|
+
const codeStyle = project?.codeStyle ?? [];
|
|
1513
|
+
if (codeStyle.length > 0) {
|
|
1514
|
+
const lines = ["## Code style", ""];
|
|
1515
|
+
for (const s of codeStyle) lines.push(`- ${s}`);
|
|
1516
|
+
parts.push(lines.join("\n"));
|
|
1517
|
+
filled.push("Code style");
|
|
1518
|
+
} else {
|
|
1519
|
+
parts.push(
|
|
1520
|
+
[
|
|
1521
|
+
"## Code style",
|
|
1522
|
+
"",
|
|
1523
|
+
"<!--",
|
|
1524
|
+
" Only rules that DIFFER from the language defaults or that the agent keeps",
|
|
1525
|
+
" getting wrong. Delete this section if your defaults are standard. Example:",
|
|
1526
|
+
" - ES modules, never CommonJS require",
|
|
1527
|
+
" - TypeScript strict; never use `any`",
|
|
1528
|
+
" - Use the logger in `src/log.ts`, never console.log",
|
|
1529
|
+
"-->",
|
|
1530
|
+
"- <!-- a convention the agent should follow -->"
|
|
1531
|
+
].join("\n")
|
|
1532
|
+
);
|
|
1533
|
+
}
|
|
1534
|
+
const testing = project?.testing ?? [];
|
|
1535
|
+
if (testing.length > 0) {
|
|
1536
|
+
const lines = ["## Testing", ""];
|
|
1537
|
+
for (const t of testing) lines.push(`- ${t}`);
|
|
1538
|
+
parts.push(lines.join("\n"));
|
|
1539
|
+
filled.push("Testing");
|
|
1540
|
+
} else {
|
|
1541
|
+
parts.push(
|
|
1542
|
+
[
|
|
1543
|
+
"## Testing",
|
|
1544
|
+
"",
|
|
1545
|
+
"<!--",
|
|
1546
|
+
" The test runner, how to run a single test (prefer single tests for speed),",
|
|
1547
|
+
" the mocking policy, and where tests live.",
|
|
1548
|
+
"-->",
|
|
1549
|
+
"- <!-- test runner, and the command to run ONE test -->",
|
|
1550
|
+
"- <!-- mocking and fixtures policy; where tests live -->"
|
|
1551
|
+
].join("\n")
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
parts.push(
|
|
1555
|
+
[
|
|
1556
|
+
"## Workflow",
|
|
1557
|
+
"",
|
|
1558
|
+
"<!--",
|
|
1559
|
+
" Repository etiquette: branch naming, commit message rules, which branch PRs",
|
|
1560
|
+
" target, merge vs rebase.",
|
|
1561
|
+
"-->",
|
|
1562
|
+
"- <!-- branch naming and commit conventions -->",
|
|
1563
|
+
"- Typecheck and run the tests after a set of changes, before calling it done."
|
|
1564
|
+
].join("\n")
|
|
1565
|
+
);
|
|
1566
|
+
parts.push(
|
|
1567
|
+
[
|
|
1568
|
+
"## Architecture and gotchas",
|
|
1569
|
+
"",
|
|
1570
|
+
"<!--",
|
|
1571
|
+
" The highest-leverage prose: non-obvious, project-specific facts and footguns.",
|
|
1572
|
+
" Grow this over time. Whenever the agent makes the same mistake twice, add a",
|
|
1573
|
+
" line here. Example:",
|
|
1574
|
+
" - Migrations are not auto-run: run `npm run migrate` after pulling.",
|
|
1575
|
+
" - Auth tokens refresh in `src/auth/refresh.ts`, not per-request.",
|
|
1576
|
+
"-->",
|
|
1577
|
+
"- <!-- a non-obvious fact or footgun the agent should know -->"
|
|
1578
|
+
].join("\n")
|
|
1579
|
+
);
|
|
1580
|
+
const envVars = (project?.envVars ?? []).map((v) => v.trim()).filter((v) => v.length > 0);
|
|
1581
|
+
if (envVars.length > 0) {
|
|
1582
|
+
const names = envVars.map((v) => `\`${v}\``).join(", ");
|
|
1583
|
+
parts.push(
|
|
1584
|
+
[
|
|
1585
|
+
"## Environment",
|
|
1586
|
+
"",
|
|
1587
|
+
`- Required env vars: ${names} (see \`.env.example\`).`
|
|
1588
|
+
].join("\n")
|
|
1589
|
+
);
|
|
1590
|
+
filled.push("Environment");
|
|
1591
|
+
} else {
|
|
1592
|
+
parts.push(
|
|
1593
|
+
[
|
|
1594
|
+
"## Environment",
|
|
1595
|
+
"",
|
|
1596
|
+
"<!--",
|
|
1597
|
+
" Required environment variable NAMES only, never values or secrets. Services",
|
|
1598
|
+
" that must be running locally.",
|
|
1599
|
+
"-->",
|
|
1600
|
+
"- Required env vars: <!-- NAME, NAME --> (see `.env.example`).",
|
|
1601
|
+
"- <!-- services to run locally, e.g. a local database -->"
|
|
1602
|
+
].join("\n")
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
parts.push(
|
|
1606
|
+
[
|
|
1607
|
+
"<!--",
|
|
1608
|
+
" Maintaining this file:",
|
|
1609
|
+
" - Treat it like code: prune it when it grows, and add a line only when a real",
|
|
1610
|
+
" mistake shows the agent needed it.",
|
|
1611
|
+
" - For content that is only sometimes relevant, use a Claude Code skill (loaded",
|
|
1612
|
+
" on demand) or a path-scoped rule under .claude/rules/ instead of this",
|
|
1613
|
+
" always-loaded file.",
|
|
1614
|
+
" - To support other agent tools without duplicating content, you can start this",
|
|
1615
|
+
" file with `@AGENTS.md` and keep Claude-specific rules below.",
|
|
1616
|
+
"-->"
|
|
1617
|
+
].join("\n")
|
|
1618
|
+
);
|
|
1619
|
+
if (project) {
|
|
1620
|
+
if (filled.length > 0) {
|
|
1621
|
+
notes.push(
|
|
1622
|
+
`Filled ${joinAnd(filled)} from your project; Architecture and gotchas is left as a placeholder for you to grow.`
|
|
1623
|
+
);
|
|
1624
|
+
} else {
|
|
1625
|
+
notes.push(
|
|
1626
|
+
"Your project had no detectable facts, so every section is a placeholder and nothing was invented."
|
|
1627
|
+
);
|
|
1628
|
+
}
|
|
1629
|
+
} else if (!currentClaudeMd) {
|
|
1630
|
+
notes.push(
|
|
1631
|
+
"No existing CLAUDE.md was provided, so the project sections are placeholders and no facts were invented."
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
return clean(parts.join("\n\n").trimEnd() + "\n");
|
|
1635
|
+
}
|
|
1636
|
+
function joinAnd(items) {
|
|
1637
|
+
if (items.length === 0) return "";
|
|
1638
|
+
if (items.length === 1) return items[0];
|
|
1639
|
+
if (items.length === 2) return `${items[0]} and ${items[1]}`;
|
|
1640
|
+
return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
|
|
1641
|
+
}
|
|
1642
|
+
function renderDollarFix(fix, n) {
|
|
1643
|
+
return [
|
|
1644
|
+
`## ${n}. ${fix.title}`,
|
|
1645
|
+
"",
|
|
1646
|
+
`**Recoverable: ${usd(fix.wasteUsd)}**`,
|
|
1647
|
+
"",
|
|
1648
|
+
`Why: ${fix.problem}`,
|
|
1649
|
+
"",
|
|
1650
|
+
`Do this: ${fix.action}`
|
|
1651
|
+
].join("\n");
|
|
1652
|
+
}
|
|
1653
|
+
function practices(report, scores, recoverable) {
|
|
1654
|
+
const blocks = [];
|
|
1655
|
+
if (recoverable >= 1) {
|
|
1656
|
+
blocks.push(
|
|
1657
|
+
[
|
|
1658
|
+
"### Prompt cache discipline",
|
|
1659
|
+
"",
|
|
1660
|
+
"- Start each session the same way. CLAUDE.md and your first reads form a stable prefix that Claude Code caches; reuse it and those input tokens cost about a tenth of full price, rebuild it and you pay full price again.",
|
|
1661
|
+
"- Keep CLAUDE.md small and free of volatile content (dates, TODOs, status notes). It is read once per session and re-read from cache every turn, so size and churn drive the cost, not the order of sections.",
|
|
1662
|
+
"- Pick your model and effort level at the start of a session and avoid switching mid-task. Each model and effort level has its own cache, so a switch recomputes the whole request.",
|
|
1663
|
+
"- Use /clear between unrelated tasks instead of carrying a stale, expensive context forward."
|
|
1664
|
+
].join("\n")
|
|
1665
|
+
);
|
|
1666
|
+
}
|
|
1667
|
+
if (hasHeavyToolFindings(report)) {
|
|
1668
|
+
blocks.push(
|
|
1669
|
+
[
|
|
1670
|
+
"### Tool loops and stop conditions",
|
|
1671
|
+
"",
|
|
1672
|
+
"- Your audit found sessions that fired one tool 100 or more times, usually an unscoped search or a stuck edit loop.",
|
|
1673
|
+
"- State a stop condition before any search or edit loop, and narrow the task before acting.",
|
|
1674
|
+
"- Prefer the dedicated Grep, Glob, and Read tools over shelling out the same command repeatedly."
|
|
1675
|
+
].join("\n")
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
if (weakCostDiscipline(scores)) {
|
|
1679
|
+
blocks.push(
|
|
1680
|
+
[
|
|
1681
|
+
"### Session and model discipline",
|
|
1682
|
+
"",
|
|
1683
|
+
"- Scope each session to one task and reset between unrelated tasks so a growing context does not ride along.",
|
|
1684
|
+
"- Batch related changes into one focused session instead of many short, context-heavy ones.",
|
|
1685
|
+
"- Watch token spend during long sessions so a runaway is caught early, not at the monthly bill."
|
|
1686
|
+
].join("\n")
|
|
1687
|
+
);
|
|
1688
|
+
}
|
|
1689
|
+
if (blocks.length === 0) return "";
|
|
1690
|
+
return ["## Practices behind these fixes", "", blocks.join("\n\n")].join("\n");
|
|
1691
|
+
}
|
|
1692
|
+
function countSessions(report, ruleId) {
|
|
1693
|
+
return new Set(
|
|
1694
|
+
report.findings.filter((f) => f.ruleId === ruleId).map((f) => f.evidence?.["sessionUuid"]).filter((v) => typeof v === "string")
|
|
1695
|
+
).size;
|
|
1696
|
+
}
|
|
1697
|
+
function tokenDiscipline(report) {
|
|
1698
|
+
const misroute = countSessions(report, "MODEL_MISROUTE");
|
|
1699
|
+
const marathon = countSessions(report, "MARATHON_SESSION");
|
|
1700
|
+
const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short Opus session${misroute === 1 ? "" : "s"} a cheaper model would have served. ` : "";
|
|
1701
|
+
const compactLead = marathon > 0 ? `Your audit found ${marathon} long session${marathon === 1 ? "" : "s"} whose cache decayed. ` : "";
|
|
1702
|
+
return [
|
|
1703
|
+
"## Token discipline",
|
|
1704
|
+
"",
|
|
1705
|
+
"These levers are not in your logs, so CostClaw cannot price them, but they are the highest-leverage habits for keeping spend down.",
|
|
1706
|
+
"",
|
|
1707
|
+
"### Route effort per task",
|
|
1708
|
+
"- `/effort low` for quick lookups and formatting, `medium` for routine edits, `high` for daily coding (the default), `xhigh` for complex multi-step work and agents, `max` for the hardest architecture.",
|
|
1709
|
+
"- Leaving everything on one high level pays for reasoning you do not need. Match the level to the task.",
|
|
1710
|
+
"",
|
|
1711
|
+
"### Match the model to the task",
|
|
1712
|
+
`- ${modelLead}Use a cheaper model such as Sonnet for routine edits, a fast model such as Haiku for throwaway questions, and reserve Opus for hard reasoning.`,
|
|
1713
|
+
"",
|
|
1714
|
+
"### Use fast mode for bulk work",
|
|
1715
|
+
"- `/fast` pays off when the model already knows what to do: large refactors, documentation, and test generation.",
|
|
1716
|
+
"- Avoid it for debugging, architecture decisions, and security review, where depth matters more than speed.",
|
|
1717
|
+
"",
|
|
1718
|
+
"### Compact long sessions",
|
|
1719
|
+
`- ${compactLead}Run \`/compact\` before a session's context outgrows the cache, and \`/clear\` between unrelated tasks. Keep a session scoped to one task.`,
|
|
1720
|
+
"",
|
|
1721
|
+
"### Defaults that stick",
|
|
1722
|
+
"- Set `ANTHROPIC_MODEL` and `CLAUDE_CODE_EFFORT_LEVEL` in your shell profile so every session starts on the right model and effort without a per-session step."
|
|
1723
|
+
].join("\n");
|
|
1724
|
+
}
|
|
1725
|
+
function buildPlaybook(report, fixes, scores, recoverable) {
|
|
1726
|
+
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
|
|
1727
|
+
const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
|
|
1728
|
+
const parts = [];
|
|
1729
|
+
parts.push("# CostClaw fix playbook");
|
|
1730
|
+
parts.push(
|
|
1731
|
+
[
|
|
1732
|
+
`Total recoverable spend: ${usd(recoverable)} (cache-miss exposure).`,
|
|
1733
|
+
"",
|
|
1734
|
+
"This is the ranked plan from your audit. The priority fixes are ordered by the dollars they recover; the setup warnings follow. CostClaw generates the plan; working through it is what recovers the spend."
|
|
1735
|
+
].join("\n")
|
|
1736
|
+
);
|
|
1737
|
+
dollarFixes.forEach((fix, i) => parts.push(renderDollarFix(fix, i + 1)));
|
|
1738
|
+
if (warnFixes.length > 0) {
|
|
1739
|
+
const warnLines = [
|
|
1740
|
+
"## Setup warnings",
|
|
1741
|
+
"",
|
|
1742
|
+
"These carry no direct dollar figure, but each one wastes tokens or time.",
|
|
1743
|
+
""
|
|
1744
|
+
];
|
|
1745
|
+
for (const f of warnFixes) warnLines.push(`- **${f.title}**: ${f.action}`);
|
|
1746
|
+
parts.push(warnLines.join("\n"));
|
|
1747
|
+
}
|
|
1748
|
+
const ref = practices(report, scores, recoverable);
|
|
1749
|
+
if (ref) parts.push(ref);
|
|
1750
|
+
parts.push(tokenDiscipline(report));
|
|
1751
|
+
return clean(parts.join("\n\n").trimEnd() + "\n");
|
|
1752
|
+
}
|
|
1753
|
+
var SAFE_COMMAND_LABELS = /* @__PURE__ */ new Set(["install", "test", "lint", "typecheck", "build", "format"]);
|
|
1754
|
+
var BASE_ALLOW = ["Read", "Grep", "Glob", "Bash(git status:*)", "Bash(git diff:*)", "Bash(git log:*)"];
|
|
1755
|
+
var BASE_DENY = [
|
|
1756
|
+
"Bash(rm *)",
|
|
1757
|
+
"Bash(rm -rf:*)",
|
|
1758
|
+
"Bash(sudo:*)",
|
|
1759
|
+
"Bash(git push:*)",
|
|
1760
|
+
"Read(.env)",
|
|
1761
|
+
"Read(.env.*)",
|
|
1762
|
+
"Read(**/*.pem)",
|
|
1763
|
+
"Read(**/*.key)",
|
|
1764
|
+
"Read(~/.ssh/**)"
|
|
1765
|
+
];
|
|
1766
|
+
function buildSettings(project) {
|
|
1767
|
+
const projectAllow = /* @__PURE__ */ new Set();
|
|
1768
|
+
for (const c of project?.commands ?? []) {
|
|
1769
|
+
if (!SAFE_COMMAND_LABELS.has(c.label)) continue;
|
|
1770
|
+
const cmd = c.command.trim();
|
|
1771
|
+
if (!cmd || cmd.includes("<")) continue;
|
|
1772
|
+
projectAllow.add(`Bash(${cmd}:*)`);
|
|
1773
|
+
}
|
|
1774
|
+
const allow = [...BASE_ALLOW, ...[...projectAllow].sort()];
|
|
1775
|
+
const settings = { permissions: { allow, deny: [...BASE_DENY] } };
|
|
1776
|
+
return clean(JSON.stringify(settings, null, 2) + "\n");
|
|
1777
|
+
}
|
|
1778
|
+
function optimize(input) {
|
|
1779
|
+
const recoverable = cacheMissExposureUsd(input.report);
|
|
1780
|
+
const notes = [];
|
|
1781
|
+
const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes);
|
|
1782
|
+
const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable);
|
|
1783
|
+
const settingsJson = buildSettings(input.project);
|
|
1784
|
+
const cleanNotes = notes.map((n) => clean(n));
|
|
1785
|
+
if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || cleanNotes.some(hasEmDash)) {
|
|
1786
|
+
return {
|
|
1787
|
+
optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
|
|
1788
|
+
playbook: sanitizeText(playbook),
|
|
1789
|
+
settingsJson: sanitizeText(settingsJson),
|
|
1790
|
+
notes: cleanNotes.map(sanitizeText)
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes };
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1037
1796
|
// ../../packages/engine/src/audit.ts
|
|
1038
1797
|
import { randomUUID } from "crypto";
|
|
1039
1798
|
function round2(n) {
|
|
@@ -1051,7 +1810,7 @@ function toUsageMetrics(report) {
|
|
|
1051
1810
|
cacheHitRate: round4(p.cacheHitRate),
|
|
1052
1811
|
modelPrimary: p.modelPrimary
|
|
1053
1812
|
}));
|
|
1054
|
-
const topSessions = report.projects.flatMap((p) => p.sessions.map((sess) => ({ projectSlug: p.slug, sess }))).sort((a, b) => b.sess.cost_usd - a.sess.cost_usd).slice(0, 8).map(({ projectSlug, sess }) => ({
|
|
1813
|
+
const topSessions = report.projects.flatMap((p) => p.sessions.filter((sess) => sess.kind === "main").map((sess) => ({ projectSlug: p.slug, sess }))).sort((a, b) => b.sess.cost_usd - a.sess.cost_usd).slice(0, 8).map(({ projectSlug, sess }) => ({
|
|
1055
1814
|
projectSlug,
|
|
1056
1815
|
sessionUuid: sess.sessionUuid,
|
|
1057
1816
|
costUsd: round2(sess.cost_usd),
|
|
@@ -1060,7 +1819,7 @@ function toUsageMetrics(report) {
|
|
|
1060
1819
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
1061
1820
|
}));
|
|
1062
1821
|
const modelBreakdown = {};
|
|
1063
|
-
for (const [model,
|
|
1822
|
+
for (const [model, usd4] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd4);
|
|
1064
1823
|
return {
|
|
1065
1824
|
spendUsd: round2(s.cost_usd),
|
|
1066
1825
|
cacheSavingsUsd: round2(s.cache_savings_usd),
|
|
@@ -1094,7 +1853,7 @@ function cleanPillar(p) {
|
|
|
1094
1853
|
function buildAudit(input, opts = {}) {
|
|
1095
1854
|
const report = analyzeUploads(input.logs);
|
|
1096
1855
|
const cmd = analyzeClaudeMd(input.claudeMd);
|
|
1097
|
-
const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire);
|
|
1856
|
+
const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire, input.setup);
|
|
1098
1857
|
const { headlineWasteUsd, headlineWasteLabel, fixes } = synthesize(report, pillars, cmd);
|
|
1099
1858
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
1100
1859
|
return {
|
|
@@ -1126,11 +1885,33 @@ var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
|
1126
1885
|
|
|
1127
1886
|
// src/read-sessions.ts
|
|
1128
1887
|
import { readdir, readFile } from "fs/promises";
|
|
1129
|
-
import { join } from "path";
|
|
1888
|
+
import { join, relative, sep } from "path";
|
|
1130
1889
|
import { homedir } from "os";
|
|
1131
1890
|
function defaultProjectsPath() {
|
|
1132
1891
|
return process.env.CLAUDE_PROJECTS_PATH || join(homedir(), ".claude", "projects");
|
|
1133
1892
|
}
|
|
1893
|
+
async function collectJsonl(dir) {
|
|
1894
|
+
const out = [];
|
|
1895
|
+
let entries;
|
|
1896
|
+
try {
|
|
1897
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1898
|
+
} catch {
|
|
1899
|
+
return out;
|
|
1900
|
+
}
|
|
1901
|
+
for (const e of entries) {
|
|
1902
|
+
const full = join(dir, e.name);
|
|
1903
|
+
if (e.isDirectory()) out.push(...await collectJsonl(full));
|
|
1904
|
+
else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(full);
|
|
1905
|
+
}
|
|
1906
|
+
return out;
|
|
1907
|
+
}
|
|
1908
|
+
function classify(rel) {
|
|
1909
|
+
const parts = rel.split("/").filter(Boolean);
|
|
1910
|
+
if (parts.length <= 1) return { kind: "main", parentSessionId: null };
|
|
1911
|
+
const parent = parts[0] ?? null;
|
|
1912
|
+
if (parts.includes("workflows")) return { kind: "workflow", parentSessionId: parent };
|
|
1913
|
+
return { kind: "subagent", parentSessionId: parent };
|
|
1914
|
+
}
|
|
1134
1915
|
async function readSessions(rootPath) {
|
|
1135
1916
|
const logs = [];
|
|
1136
1917
|
const skipped = [];
|
|
@@ -1143,21 +1924,22 @@ async function readSessions(rootPath) {
|
|
|
1143
1924
|
for (const dir of projectDirs) {
|
|
1144
1925
|
if (!dir.isDirectory()) continue;
|
|
1145
1926
|
const projPath = join(rootPath, dir.name);
|
|
1146
|
-
let files;
|
|
1147
1927
|
try {
|
|
1148
|
-
|
|
1928
|
+
await readdir(projPath);
|
|
1149
1929
|
} catch {
|
|
1150
1930
|
skipped.push(dir.name);
|
|
1151
1931
|
continue;
|
|
1152
1932
|
}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
const rel =
|
|
1933
|
+
const files = await collectJsonl(projPath);
|
|
1934
|
+
for (const full of files) {
|
|
1935
|
+
const rel = relative(projPath, full).split(sep).join("/");
|
|
1936
|
+
const name = `${dir.name}/${rel}`;
|
|
1937
|
+
const { kind, parentSessionId } = classify(rel);
|
|
1156
1938
|
try {
|
|
1157
|
-
const text = await readFile(
|
|
1158
|
-
logs.push({ name
|
|
1939
|
+
const text = await readFile(full, "utf8");
|
|
1940
|
+
logs.push({ name, text, kind, parentSessionId, projectSlug: dir.name });
|
|
1159
1941
|
} catch {
|
|
1160
|
-
skipped.push(
|
|
1942
|
+
skipped.push(name);
|
|
1161
1943
|
}
|
|
1162
1944
|
}
|
|
1163
1945
|
}
|
|
@@ -1165,7 +1947,7 @@ async function readSessions(rootPath) {
|
|
|
1165
1947
|
}
|
|
1166
1948
|
|
|
1167
1949
|
// src/format.ts
|
|
1168
|
-
function
|
|
1950
|
+
function usd2(n) {
|
|
1169
1951
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
1170
1952
|
}
|
|
1171
1953
|
function bar(score, width = 20) {
|
|
@@ -1179,9 +1961,9 @@ function formatAudit(record, meta) {
|
|
|
1179
1961
|
lines.push("CostClaw audit");
|
|
1180
1962
|
lines.push(`Source: ${meta.root} (${meta.sessionCount} sessions across ${m.projectsCount} projects)`);
|
|
1181
1963
|
lines.push("");
|
|
1182
|
-
lines.push(`${record.headlineWasteLabel}: ${
|
|
1964
|
+
lines.push(`${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`);
|
|
1183
1965
|
lines.push("");
|
|
1184
|
-
lines.push(`Spend analyzed: ${
|
|
1966
|
+
lines.push(`Spend analyzed: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`);
|
|
1185
1967
|
lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
|
|
1186
1968
|
lines.push("");
|
|
1187
1969
|
lines.push(`Overall setup score: ${record.overallScore} / 100 (${record.band.label})`);
|
|
@@ -1196,7 +1978,7 @@ function formatAudit(record, meta) {
|
|
|
1196
1978
|
lines.push(" No directly recoverable dollars found. See issues below.");
|
|
1197
1979
|
} else {
|
|
1198
1980
|
for (const f of dollarFixes.slice(0, 6)) {
|
|
1199
|
-
lines.push(` - [${
|
|
1981
|
+
lines.push(` - [${usd2(f.wasteUsd)}] ${f.title}`);
|
|
1200
1982
|
lines.push(` ${f.action}`);
|
|
1201
1983
|
}
|
|
1202
1984
|
}
|
|
@@ -1219,8 +2001,53 @@ function formatAudit(record, meta) {
|
|
|
1219
2001
|
return lines.join("\n");
|
|
1220
2002
|
}
|
|
1221
2003
|
|
|
2004
|
+
// src/read-setup.ts
|
|
2005
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
2006
|
+
import { join as join2 } from "path";
|
|
2007
|
+
import { homedir as homedir2 } from "os";
|
|
2008
|
+
async function readJson(path) {
|
|
2009
|
+
try {
|
|
2010
|
+
const parsed = JSON.parse(await readFile2(path, "utf8"));
|
|
2011
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
2012
|
+
} catch {
|
|
2013
|
+
return null;
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
function at(obj, ...path) {
|
|
2017
|
+
let cur = obj;
|
|
2018
|
+
for (const k of path) {
|
|
2019
|
+
if (!cur || typeof cur !== "object") return void 0;
|
|
2020
|
+
cur = cur[k];
|
|
2021
|
+
}
|
|
2022
|
+
return cur;
|
|
2023
|
+
}
|
|
2024
|
+
function arrLen(obj, ...path) {
|
|
2025
|
+
const v = at(obj, ...path);
|
|
2026
|
+
return Array.isArray(v) ? v.length : 0;
|
|
2027
|
+
}
|
|
2028
|
+
function objCount(obj, ...path) {
|
|
2029
|
+
const v = at(obj, ...path);
|
|
2030
|
+
return v && typeof v === "object" && !Array.isArray(v) ? Object.keys(v).length : 0;
|
|
2031
|
+
}
|
|
2032
|
+
async function readSetup(home = homedir2()) {
|
|
2033
|
+
const base = join2(home, ".claude");
|
|
2034
|
+
const settings = await readJson(join2(base, "settings.json"));
|
|
2035
|
+
const local = await readJson(join2(base, "settings.local.json"));
|
|
2036
|
+
const dotClaude = await readJson(join2(home, ".claude.json"));
|
|
2037
|
+
if (!settings && !local && !dotClaude) return void 0;
|
|
2038
|
+
const allow = arrLen(settings, "permissions", "allow") + arrLen(local, "permissions", "allow");
|
|
2039
|
+
const deny = arrLen(settings, "permissions", "deny") + arrLen(local, "permissions", "deny");
|
|
2040
|
+
const mcp = objCount(settings, "mcpServers") + objCount(local, "mcpServers") + objCount(dotClaude, "mcpServers");
|
|
2041
|
+
return {
|
|
2042
|
+
hasPermissionConfig: allow + deny > 0,
|
|
2043
|
+
permissionAllowCount: allow,
|
|
2044
|
+
permissionDenyCount: deny,
|
|
2045
|
+
mcpServerCount: mcp
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
|
|
1222
2049
|
// src/audit-command.ts
|
|
1223
|
-
async function
|
|
2050
|
+
async function loadAuditInputs(opts) {
|
|
1224
2051
|
const root = opts.path || defaultProjectsPath();
|
|
1225
2052
|
const { logs, skipped } = await readSessions(root);
|
|
1226
2053
|
if (logs.length === 0) {
|
|
@@ -1228,13 +2055,739 @@ async function runAudit(opts) {
|
|
|
1228
2055
|
}
|
|
1229
2056
|
let claudeMd;
|
|
1230
2057
|
if (opts.claudeMdPath) {
|
|
1231
|
-
claudeMd = await
|
|
2058
|
+
claudeMd = await readFile3(opts.claudeMdPath, "utf8");
|
|
1232
2059
|
}
|
|
1233
|
-
|
|
2060
|
+
return { logs, claudeMd, root, skipped };
|
|
2061
|
+
}
|
|
2062
|
+
async function runAudit(opts) {
|
|
2063
|
+
const { logs, claudeMd, root, skipped } = await loadAuditInputs(opts);
|
|
2064
|
+
const setup = await readSetup();
|
|
2065
|
+
const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
|
|
1234
2066
|
const output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped });
|
|
1235
2067
|
return { output, record };
|
|
1236
2068
|
}
|
|
1237
2069
|
|
|
2070
|
+
// src/optimize-command.ts
|
|
2071
|
+
import { mkdir, writeFile, readFile as readFile5, stat as stat2 } from "fs/promises";
|
|
2072
|
+
import { join as join4 } from "path";
|
|
2073
|
+
|
|
2074
|
+
// src/project-scan.ts
|
|
2075
|
+
import { readdir as readdir2, readFile as readFile4, stat } from "fs/promises";
|
|
2076
|
+
import { join as join3, basename } from "path";
|
|
2077
|
+
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
2078
|
+
"node_modules",
|
|
2079
|
+
".git",
|
|
2080
|
+
"dist",
|
|
2081
|
+
"build",
|
|
2082
|
+
".next",
|
|
2083
|
+
"out",
|
|
2084
|
+
".venv",
|
|
2085
|
+
"venv",
|
|
2086
|
+
"target",
|
|
2087
|
+
"coverage",
|
|
2088
|
+
".cache"
|
|
2089
|
+
]);
|
|
2090
|
+
var DIR_NOTES = {
|
|
2091
|
+
src: "source code",
|
|
2092
|
+
tests: "test files",
|
|
2093
|
+
test: "test files",
|
|
2094
|
+
__tests__: "test files",
|
|
2095
|
+
app: "application code",
|
|
2096
|
+
lib: "library code",
|
|
2097
|
+
packages: "workspace packages (monorepo)",
|
|
2098
|
+
apps: "workspace apps (monorepo)",
|
|
2099
|
+
docs: "documentation",
|
|
2100
|
+
public: "static assets served as is",
|
|
2101
|
+
scripts: "developer and build scripts"
|
|
2102
|
+
};
|
|
2103
|
+
async function readText(p) {
|
|
2104
|
+
try {
|
|
2105
|
+
return await readFile4(p, "utf8");
|
|
2106
|
+
} catch {
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
async function listEntries(dir) {
|
|
2111
|
+
const files = [];
|
|
2112
|
+
const dirs = [];
|
|
2113
|
+
let entries;
|
|
2114
|
+
try {
|
|
2115
|
+
entries = await readdir2(dir, { withFileTypes: true });
|
|
2116
|
+
} catch {
|
|
2117
|
+
return { files, dirs };
|
|
2118
|
+
}
|
|
2119
|
+
for (const e of entries) {
|
|
2120
|
+
if (e.isDirectory()) {
|
|
2121
|
+
if (!NOISE_DIRS.has(e.name)) dirs.push(e.name);
|
|
2122
|
+
} else if (e.isFile()) {
|
|
2123
|
+
files.push(e.name);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
return { files, dirs };
|
|
2127
|
+
}
|
|
2128
|
+
function pushUnique(arr, value) {
|
|
2129
|
+
if (!arr.includes(value)) arr.push(value);
|
|
2130
|
+
}
|
|
2131
|
+
function parseJson(text) {
|
|
2132
|
+
if (text === null) return null;
|
|
2133
|
+
try {
|
|
2134
|
+
const parsed = JSON.parse(text);
|
|
2135
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
2136
|
+
} catch {
|
|
2137
|
+
return null;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
function parseEnvNames(text) {
|
|
2141
|
+
const names = [];
|
|
2142
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
2143
|
+
const line = raw.trim();
|
|
2144
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
2145
|
+
const eq = line.indexOf("=");
|
|
2146
|
+
if (eq <= 0) continue;
|
|
2147
|
+
let key = line.slice(0, eq).trim();
|
|
2148
|
+
if (key.startsWith("export ")) key = key.slice("export ".length).trim();
|
|
2149
|
+
if (key !== "" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) pushUnique(names, key);
|
|
2150
|
+
}
|
|
2151
|
+
return names;
|
|
2152
|
+
}
|
|
2153
|
+
function standardLabel(name) {
|
|
2154
|
+
if (name === "dev" || name === "start") return "dev";
|
|
2155
|
+
if (name === "test") return "test";
|
|
2156
|
+
if (name === "build") return "build";
|
|
2157
|
+
if (name === "lint") return "lint";
|
|
2158
|
+
if (name === "typecheck" || name === "tsc") return "typecheck";
|
|
2159
|
+
if (name === "format") return "format";
|
|
2160
|
+
return null;
|
|
2161
|
+
}
|
|
2162
|
+
var NODE_STACK = {
|
|
2163
|
+
typescript: "TypeScript",
|
|
2164
|
+
react: "React",
|
|
2165
|
+
next: "Next.js",
|
|
2166
|
+
astro: "Astro",
|
|
2167
|
+
vue: "Vue",
|
|
2168
|
+
svelte: "Svelte",
|
|
2169
|
+
"@sveltejs/kit": "SvelteKit",
|
|
2170
|
+
express: "Express",
|
|
2171
|
+
fastify: "Fastify",
|
|
2172
|
+
"@nestjs/core": "Nest",
|
|
2173
|
+
tailwindcss: "Tailwind",
|
|
2174
|
+
vite: "Vite",
|
|
2175
|
+
vitest: "Vitest",
|
|
2176
|
+
jest: "Jest",
|
|
2177
|
+
mocha: "Mocha",
|
|
2178
|
+
playwright: "Playwright",
|
|
2179
|
+
"@playwright/test": "Playwright",
|
|
2180
|
+
prisma: "Prisma",
|
|
2181
|
+
"@prisma/client": "Prisma",
|
|
2182
|
+
"drizzle-orm": "Drizzle",
|
|
2183
|
+
"@trpc/server": "tRPC"
|
|
2184
|
+
};
|
|
2185
|
+
function emptyProfile(name) {
|
|
2186
|
+
return {
|
|
2187
|
+
name,
|
|
2188
|
+
description: null,
|
|
2189
|
+
stack: [],
|
|
2190
|
+
packageManager: null,
|
|
2191
|
+
monorepo: false,
|
|
2192
|
+
commands: [],
|
|
2193
|
+
preCommit: null,
|
|
2194
|
+
structure: [],
|
|
2195
|
+
codeStyle: [],
|
|
2196
|
+
testing: [],
|
|
2197
|
+
envVars: []
|
|
2198
|
+
};
|
|
2199
|
+
}
|
|
2200
|
+
async function detectStructure(dir, dirs) {
|
|
2201
|
+
const structure = [];
|
|
2202
|
+
for (const name of dirs.sort()) {
|
|
2203
|
+
if (name.startsWith(".")) continue;
|
|
2204
|
+
if (structure.length >= 10) break;
|
|
2205
|
+
const note = DIR_NOTES[name] ?? "";
|
|
2206
|
+
structure.push({ path: `${name}/`, note });
|
|
2207
|
+
}
|
|
2208
|
+
return structure;
|
|
2209
|
+
}
|
|
2210
|
+
async function detectTestsLocation(dir, files, dirs) {
|
|
2211
|
+
if (dirs.includes("tests")) return "tests in tests/";
|
|
2212
|
+
if (dirs.includes("test")) return "tests in test/";
|
|
2213
|
+
if (dirs.includes("__tests__")) return "tests in __tests__/";
|
|
2214
|
+
if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
2215
|
+
if (dirs.includes("src")) {
|
|
2216
|
+
const sub = await listEntries(join3(dir, "src"));
|
|
2217
|
+
if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
|
|
2218
|
+
return "tests alongside source (*.test.* / *.spec.*)";
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
return null;
|
|
2222
|
+
}
|
|
2223
|
+
async function scanNode(dir, files, dirs, pkg, profile) {
|
|
2224
|
+
if (typeof pkg.name === "string" && pkg.name.trim() !== "") profile.name = pkg.name;
|
|
2225
|
+
if (typeof pkg.description === "string" && pkg.description.trim() !== "") {
|
|
2226
|
+
profile.description = pkg.description;
|
|
2227
|
+
}
|
|
2228
|
+
const deps = {
|
|
2229
|
+
...pkg.dependencies ?? {},
|
|
2230
|
+
...pkg.devDependencies ?? {}
|
|
2231
|
+
};
|
|
2232
|
+
const has = (name) => Object.prototype.hasOwnProperty.call(deps, name);
|
|
2233
|
+
let pm = null;
|
|
2234
|
+
if (typeof pkg.packageManager === "string") {
|
|
2235
|
+
const m = pkg.packageManager.match(/^([a-z]+)@/);
|
|
2236
|
+
if (m) pm = m[1];
|
|
2237
|
+
}
|
|
2238
|
+
if (pm === null) {
|
|
2239
|
+
if (files.includes("pnpm-lock.yaml")) pm = "pnpm";
|
|
2240
|
+
else if (files.includes("yarn.lock")) pm = "yarn";
|
|
2241
|
+
else if (files.includes("bun.lockb")) pm = "bun";
|
|
2242
|
+
else if (files.includes("package-lock.json")) pm = "npm";
|
|
2243
|
+
}
|
|
2244
|
+
if (pm === null) pm = "npm";
|
|
2245
|
+
profile.packageManager = pm;
|
|
2246
|
+
profile.monorepo = pkg.workspaces !== void 0;
|
|
2247
|
+
for (const [name, label] of Object.entries(NODE_STACK)) {
|
|
2248
|
+
if (has(name)) pushUnique(profile.stack, label);
|
|
2249
|
+
}
|
|
2250
|
+
pushUnique(profile.stack, "Node.js");
|
|
2251
|
+
const scripts = pkg.scripts ?? {};
|
|
2252
|
+
const seenLabels = /* @__PURE__ */ new Set();
|
|
2253
|
+
let hasLint = false;
|
|
2254
|
+
let hasTypecheck = false;
|
|
2255
|
+
let lintCmd = "";
|
|
2256
|
+
let typecheckCmd = "";
|
|
2257
|
+
const installCmd = pm === "npm" ? "npm install" : pm === "yarn" ? "yarn" : `${pm} install`;
|
|
2258
|
+
profile.commands.push({ label: "install", command: installCmd });
|
|
2259
|
+
const runPrefix = (script) => {
|
|
2260
|
+
if (pm === "npm") return `npm run ${script}`;
|
|
2261
|
+
if (pm === "yarn") return `yarn ${script}`;
|
|
2262
|
+
return `${pm} run ${script}`;
|
|
2263
|
+
};
|
|
2264
|
+
for (const [scriptName] of Object.entries(scripts)) {
|
|
2265
|
+
const label = standardLabel(scriptName);
|
|
2266
|
+
const command = scriptName === "test" ? `${pm === "yarn" ? "yarn" : pm} test` : runPrefix(scriptName);
|
|
2267
|
+
const finalLabel = label ?? scriptName;
|
|
2268
|
+
if (seenLabels.has(finalLabel)) continue;
|
|
2269
|
+
seenLabels.add(finalLabel);
|
|
2270
|
+
profile.commands.push({ label: finalLabel, command });
|
|
2271
|
+
if (finalLabel === "lint") {
|
|
2272
|
+
hasLint = true;
|
|
2273
|
+
lintCmd = command;
|
|
2274
|
+
}
|
|
2275
|
+
if (finalLabel === "typecheck") {
|
|
2276
|
+
hasTypecheck = true;
|
|
2277
|
+
typecheckCmd = command;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
const pmTest = pm === "yarn" ? "yarn test" : `${pm} test`;
|
|
2281
|
+
let oneFileCmd = null;
|
|
2282
|
+
let runnerLabel = null;
|
|
2283
|
+
if (has("vitest")) {
|
|
2284
|
+
runnerLabel = "Vitest";
|
|
2285
|
+
oneFileCmd = `${pmTest} -- <file>`;
|
|
2286
|
+
} else if (has("jest")) {
|
|
2287
|
+
runnerLabel = "Jest";
|
|
2288
|
+
oneFileCmd = `${pmTest} -- <file>`;
|
|
2289
|
+
} else if (has("mocha")) {
|
|
2290
|
+
runnerLabel = "Mocha";
|
|
2291
|
+
oneFileCmd = `npx mocha <file>`;
|
|
2292
|
+
} else if (has("@playwright/test") || has("playwright")) {
|
|
2293
|
+
runnerLabel = "Playwright";
|
|
2294
|
+
oneFileCmd = `npx playwright test <file>`;
|
|
2295
|
+
}
|
|
2296
|
+
if (oneFileCmd !== null && "test" in scripts) {
|
|
2297
|
+
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
2298
|
+
}
|
|
2299
|
+
const tsconfig = parseJson(await readText(join3(dir, "tsconfig.json")));
|
|
2300
|
+
if (tsconfig) {
|
|
2301
|
+
const co = tsconfig.compilerOptions;
|
|
2302
|
+
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
2303
|
+
}
|
|
2304
|
+
if (pkg.type === "module") {
|
|
2305
|
+
pushUnique(profile.codeStyle, "ES modules (import/export), not CommonJS");
|
|
2306
|
+
}
|
|
2307
|
+
const eslintConfig = files.some((f) => /^\.eslintrc(\..+)?$/.test(f)) || files.some((f) => /^eslint\.config\.[cm]?[jt]s$/.test(f)) || pkg.eslintConfig !== void 0;
|
|
2308
|
+
if (eslintConfig) pushUnique(profile.codeStyle, "ESLint configured");
|
|
2309
|
+
const prettierConfig = files.some((f) => /^\.prettierrc(\..+)?$/.test(f)) || files.some((f) => /^prettier\.config\.[cm]?[jt]s$/.test(f)) || pkg.prettier !== void 0;
|
|
2310
|
+
if (prettierConfig) pushUnique(profile.codeStyle, "Prettier configured");
|
|
2311
|
+
if (runnerLabel !== null) pushUnique(profile.testing, `${runnerLabel} test runner`);
|
|
2312
|
+
if (oneFileCmd !== null && "test" in scripts) {
|
|
2313
|
+
pushUnique(profile.testing, `run one test file: ${oneFileCmd}`);
|
|
2314
|
+
}
|
|
2315
|
+
const testsLoc = await detectTestsLocation(dir, files, dirs);
|
|
2316
|
+
if (testsLoc !== null) pushUnique(profile.testing, testsLoc);
|
|
2317
|
+
if (hasLint && hasTypecheck) {
|
|
2318
|
+
profile.preCommit = `run ${lintCmd} and ${typecheckCmd} before committing`;
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
function parsePyproject(text) {
|
|
2322
|
+
const tables = /* @__PURE__ */ new Set();
|
|
2323
|
+
let name = null;
|
|
2324
|
+
let description = null;
|
|
2325
|
+
const deps = [];
|
|
2326
|
+
let section = "";
|
|
2327
|
+
let inDepsArray = false;
|
|
2328
|
+
const depFromSpec = (raw) => {
|
|
2329
|
+
const cleaned = raw.trim().replace(/^["']+/, "").trim();
|
|
2330
|
+
if (cleaned === "") return;
|
|
2331
|
+
const m = cleaned.match(/^[A-Za-z0-9_.\-]+/);
|
|
2332
|
+
if (m) pushUnique(deps, m[0].toLowerCase());
|
|
2333
|
+
};
|
|
2334
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
2335
|
+
const line = raw.trim();
|
|
2336
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
2337
|
+
const header = line.match(/^\[([^\]]+)\]$/);
|
|
2338
|
+
if (header) {
|
|
2339
|
+
section = header[1].trim();
|
|
2340
|
+
if (section.startsWith("tool.")) tables.add(section);
|
|
2341
|
+
inDepsArray = false;
|
|
2342
|
+
continue;
|
|
2343
|
+
}
|
|
2344
|
+
if (inDepsArray) {
|
|
2345
|
+
if (line.includes("]")) inDepsArray = false;
|
|
2346
|
+
const inner = line.replace(/]\s*$/, "");
|
|
2347
|
+
if (inner.trim() !== "") depFromSpec(inner);
|
|
2348
|
+
continue;
|
|
2349
|
+
}
|
|
2350
|
+
if (section === "project") {
|
|
2351
|
+
const nameM = line.match(/^name\s*=\s*["']([^"']+)["']/);
|
|
2352
|
+
if (nameM) name = nameM[1];
|
|
2353
|
+
const descM = line.match(/^description\s*=\s*["']([^"']*)["']/);
|
|
2354
|
+
if (descM) description = descM[1];
|
|
2355
|
+
if (/^dependencies\s*=\s*\[/.test(line)) {
|
|
2356
|
+
const after = line.slice(line.indexOf("[") + 1);
|
|
2357
|
+
if (line.includes("]")) {
|
|
2358
|
+
for (const part of after.replace(/]\s*$/, "").split(",")) depFromSpec(part);
|
|
2359
|
+
} else {
|
|
2360
|
+
inDepsArray = true;
|
|
2361
|
+
if (after.trim() !== "") depFromSpec(after);
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
if (section === "tool.poetry") {
|
|
2366
|
+
const nameM = line.match(/^name\s*=\s*["']([^"']+)["']/);
|
|
2367
|
+
if (nameM && name === null) name = nameM[1];
|
|
2368
|
+
const descM = line.match(/^description\s*=\s*["']([^"']*)["']/);
|
|
2369
|
+
if (descM && description === null) description = descM[1];
|
|
2370
|
+
}
|
|
2371
|
+
if (section === "tool.poetry.dependencies") {
|
|
2372
|
+
const keyM = line.match(/^([A-Za-z0-9_.\-]+)\s*=/);
|
|
2373
|
+
if (keyM && keyM[1].toLowerCase() !== "python") pushUnique(deps, keyM[1].toLowerCase());
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
return { name, description, deps, tables, hasPoetry: tables.has("tool.poetry") };
|
|
2377
|
+
}
|
|
2378
|
+
var PY_STACK = {
|
|
2379
|
+
django: "Django",
|
|
2380
|
+
flask: "Flask",
|
|
2381
|
+
fastapi: "FastAPI",
|
|
2382
|
+
pytest: "pytest",
|
|
2383
|
+
sqlalchemy: "SQLAlchemy",
|
|
2384
|
+
pydantic: "Pydantic"
|
|
2385
|
+
};
|
|
2386
|
+
function pyDepsFromRequirements(text) {
|
|
2387
|
+
const deps = [];
|
|
2388
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
2389
|
+
const line = raw.trim();
|
|
2390
|
+
if (line === "" || line.startsWith("#") || line.startsWith("-")) continue;
|
|
2391
|
+
const m = line.match(/^[A-Za-z0-9_.\-]+/);
|
|
2392
|
+
if (m) pushUnique(deps, m[0].toLowerCase());
|
|
2393
|
+
}
|
|
2394
|
+
return deps;
|
|
2395
|
+
}
|
|
2396
|
+
async function scanPython(dir, files, profile) {
|
|
2397
|
+
let name = null;
|
|
2398
|
+
let description = null;
|
|
2399
|
+
const deps = [];
|
|
2400
|
+
const tables = /* @__PURE__ */ new Set();
|
|
2401
|
+
let hasPoetry = false;
|
|
2402
|
+
const pyprojectText = await readText(join3(dir, "pyproject.toml"));
|
|
2403
|
+
if (pyprojectText !== null) {
|
|
2404
|
+
const parsed = parsePyproject(pyprojectText);
|
|
2405
|
+
name = parsed.name;
|
|
2406
|
+
description = parsed.description;
|
|
2407
|
+
for (const d of parsed.deps) pushUnique(deps, d);
|
|
2408
|
+
for (const t of parsed.tables) tables.add(t);
|
|
2409
|
+
hasPoetry = parsed.hasPoetry;
|
|
2410
|
+
}
|
|
2411
|
+
if (files.includes("requirements.txt")) {
|
|
2412
|
+
const reqText = await readText(join3(dir, "requirements.txt"));
|
|
2413
|
+
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
2414
|
+
}
|
|
2415
|
+
if (name !== null && name.trim() !== "") profile.name = name;
|
|
2416
|
+
if (description !== null && description.trim() !== "") profile.description = description;
|
|
2417
|
+
pushUnique(profile.stack, "Python");
|
|
2418
|
+
for (const [dep, label] of Object.entries(PY_STACK)) {
|
|
2419
|
+
if (deps.includes(dep)) pushUnique(profile.stack, label);
|
|
2420
|
+
}
|
|
2421
|
+
profile.packageManager = hasPoetry ? "poetry" : "pip";
|
|
2422
|
+
const hasPytest = deps.includes("pytest") || tables.has("tool.pytest.ini_options") || files.includes("pytest.ini");
|
|
2423
|
+
if (hasPytest) {
|
|
2424
|
+
profile.commands.push({ label: "test", command: "pytest" });
|
|
2425
|
+
profile.commands.push({ label: "test one file", command: "pytest <file>" });
|
|
2426
|
+
pushUnique(profile.testing, "pytest test runner");
|
|
2427
|
+
pushUnique(profile.testing, "run one test file: pytest <file>");
|
|
2428
|
+
}
|
|
2429
|
+
const hasRuff = tables.has("tool.ruff") || files.includes("ruff.toml") || files.includes(".ruff.toml");
|
|
2430
|
+
const hasBlack = tables.has("tool.black");
|
|
2431
|
+
const hasMypy = tables.has("tool.mypy") || files.includes("mypy.ini");
|
|
2432
|
+
if (hasRuff) {
|
|
2433
|
+
profile.commands.push({ label: "lint", command: "ruff check ." });
|
|
2434
|
+
pushUnique(profile.codeStyle, "ruff configured (linting)");
|
|
2435
|
+
}
|
|
2436
|
+
if (hasBlack) {
|
|
2437
|
+
profile.commands.push({ label: "format", command: "black ." });
|
|
2438
|
+
pushUnique(profile.codeStyle, "black configured (formatting)");
|
|
2439
|
+
}
|
|
2440
|
+
if (hasMypy) {
|
|
2441
|
+
profile.commands.push({ label: "typecheck", command: "mypy ." });
|
|
2442
|
+
pushUnique(profile.codeStyle, "mypy configured (type checking)");
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
async function scanRust(dir, profile) {
|
|
2446
|
+
const text = await readText(join3(dir, "Cargo.toml"));
|
|
2447
|
+
pushUnique(profile.stack, "Rust");
|
|
2448
|
+
profile.packageManager = "cargo";
|
|
2449
|
+
if (text !== null) {
|
|
2450
|
+
let section = "";
|
|
2451
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
2452
|
+
const line = raw.trim();
|
|
2453
|
+
const header = line.match(/^\[([^\]]+)\]$/);
|
|
2454
|
+
if (header) {
|
|
2455
|
+
section = header[1].trim();
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
if (section === "package") {
|
|
2459
|
+
const m = line.match(/^name\s*=\s*["']([^"']+)["']/);
|
|
2460
|
+
if (m) {
|
|
2461
|
+
profile.name = m[1];
|
|
2462
|
+
break;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
profile.commands.push({ label: "build", command: "cargo build" });
|
|
2468
|
+
profile.commands.push({ label: "test", command: "cargo test" });
|
|
2469
|
+
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
2470
|
+
}
|
|
2471
|
+
async function scanGo(dir, profile) {
|
|
2472
|
+
const text = await readText(join3(dir, "go.mod"));
|
|
2473
|
+
pushUnique(profile.stack, "Go");
|
|
2474
|
+
profile.packageManager = "go";
|
|
2475
|
+
if (text !== null) {
|
|
2476
|
+
const m = text.match(/^module\s+(\S+)/m);
|
|
2477
|
+
if (m) {
|
|
2478
|
+
const mod = m[1];
|
|
2479
|
+
profile.name = mod.includes("/") ? mod.slice(mod.lastIndexOf("/") + 1) : mod;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
profile.commands.push({ label: "build", command: "go build ./..." });
|
|
2483
|
+
profile.commands.push({ label: "test", command: "go test ./..." });
|
|
2484
|
+
profile.commands.push({ label: "lint", command: "go vet ./..." });
|
|
2485
|
+
}
|
|
2486
|
+
function parseMakefile(text) {
|
|
2487
|
+
const targets = [];
|
|
2488
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
2489
|
+
if (/^\t/.test(raw)) continue;
|
|
2490
|
+
const m = raw.match(/^([A-Za-z0-9_.\-]+)\s*:(?!=)/);
|
|
2491
|
+
if (m) {
|
|
2492
|
+
const t = m[1];
|
|
2493
|
+
if (t !== ".PHONY") pushUnique(targets, t);
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
return targets;
|
|
2497
|
+
}
|
|
2498
|
+
function parseReadme(text) {
|
|
2499
|
+
const lines = text.split(/\r?\n/);
|
|
2500
|
+
let name = null;
|
|
2501
|
+
let i = 0;
|
|
2502
|
+
for (; i < lines.length; i++) {
|
|
2503
|
+
const line = lines[i].trim();
|
|
2504
|
+
const m = line.match(/^#\s+(.+)$/);
|
|
2505
|
+
if (m) {
|
|
2506
|
+
name = m[1].trim();
|
|
2507
|
+
i++;
|
|
2508
|
+
break;
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
const para = [];
|
|
2512
|
+
for (; i < lines.length; i++) {
|
|
2513
|
+
const line = lines[i].trim();
|
|
2514
|
+
if (line === "") {
|
|
2515
|
+
if (para.length > 0) break;
|
|
2516
|
+
continue;
|
|
2517
|
+
}
|
|
2518
|
+
if (line.startsWith("#")) break;
|
|
2519
|
+
if (line.startsWith(">") || line.startsWith("![") || line.startsWith("[!")) {
|
|
2520
|
+
if (para.length > 0) break;
|
|
2521
|
+
continue;
|
|
2522
|
+
}
|
|
2523
|
+
para.push(line);
|
|
2524
|
+
}
|
|
2525
|
+
let description = null;
|
|
2526
|
+
if (para.length > 0) {
|
|
2527
|
+
const joined = para.join(" ").replace(/\s+/g, " ").trim();
|
|
2528
|
+
const m = joined.match(/^(.+?[.!?])(\s|$)/);
|
|
2529
|
+
description = m ? m[1].trim() : joined;
|
|
2530
|
+
}
|
|
2531
|
+
return { name, description };
|
|
2532
|
+
}
|
|
2533
|
+
async function scanProject(dir) {
|
|
2534
|
+
const profile = emptyProfile(basename(dir));
|
|
2535
|
+
const { files, dirs } = await listEntries(dir);
|
|
2536
|
+
if (files.includes("package.json")) {
|
|
2537
|
+
const pkg = parseJson(await readText(join3(dir, "package.json")));
|
|
2538
|
+
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
2539
|
+
}
|
|
2540
|
+
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
2541
|
+
await scanPython(dir, files, profile);
|
|
2542
|
+
}
|
|
2543
|
+
if (files.includes("Cargo.toml")) {
|
|
2544
|
+
await scanRust(dir, profile);
|
|
2545
|
+
}
|
|
2546
|
+
if (files.includes("go.mod")) {
|
|
2547
|
+
await scanGo(dir, profile);
|
|
2548
|
+
}
|
|
2549
|
+
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
2550
|
+
const text = await readText(join3(dir, "Makefile"));
|
|
2551
|
+
if (text !== null) {
|
|
2552
|
+
for (const t of parseMakefile(text)) {
|
|
2553
|
+
profile.commands.push({ label: t, command: `make ${t}` });
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
if (profile.description === null || profile.name === basename(dir)) {
|
|
2558
|
+
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
2559
|
+
if (readmeName) {
|
|
2560
|
+
const text = await readText(join3(dir, readmeName));
|
|
2561
|
+
if (text !== null) {
|
|
2562
|
+
const parsed = parseReadme(text);
|
|
2563
|
+
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
2564
|
+
if (profile.description === null && parsed.description !== null) {
|
|
2565
|
+
profile.description = parsed.description;
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
profile.structure = await detectStructure(dir, dirs);
|
|
2571
|
+
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
2572
|
+
if (envFile) {
|
|
2573
|
+
const text = await readText(join3(dir, envFile));
|
|
2574
|
+
if (text !== null) profile.envVars = parseEnvNames(text);
|
|
2575
|
+
}
|
|
2576
|
+
return profile;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
// src/optimize-command.ts
|
|
2580
|
+
var OPTIMIZED_NAME = "CLAUDE.optimized.md";
|
|
2581
|
+
var PLAYBOOK_NAME = "PLAYBOOK.md";
|
|
2582
|
+
var SETTINGS_NAME = "settings.suggested.json";
|
|
2583
|
+
function usd3(n) {
|
|
2584
|
+
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
2585
|
+
}
|
|
2586
|
+
function describeDetection(project) {
|
|
2587
|
+
const name = project.name?.trim() || "unnamed project";
|
|
2588
|
+
const n = project.commands.length;
|
|
2589
|
+
const cmds = `${n} command${n === 1 ? "" : "s"}`;
|
|
2590
|
+
const stack = project.stack.length > 0 ? project.stack.join(", ") : "no stack detected";
|
|
2591
|
+
return `Detected: ${name}, ${cmds}, ${stack}`;
|
|
2592
|
+
}
|
|
2593
|
+
async function pathExists(p) {
|
|
2594
|
+
try {
|
|
2595
|
+
await stat2(p);
|
|
2596
|
+
return true;
|
|
2597
|
+
} catch {
|
|
2598
|
+
return false;
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
function lineDiff(oldText, newText) {
|
|
2602
|
+
const oldLines = oldText.split(/\r?\n/);
|
|
2603
|
+
const newLines = newText.split(/\r?\n/);
|
|
2604
|
+
const oldSet = new Set(oldLines);
|
|
2605
|
+
const newSet = new Set(newLines);
|
|
2606
|
+
const lines = [];
|
|
2607
|
+
for (const line of oldLines) {
|
|
2608
|
+
if (!newSet.has(line)) lines.push(`- ${line}`);
|
|
2609
|
+
}
|
|
2610
|
+
for (const line of newLines) {
|
|
2611
|
+
if (!oldSet.has(line)) lines.push(`+ ${line}`);
|
|
2612
|
+
}
|
|
2613
|
+
if (lines.length === 0) lines.push(" (no line-level changes)");
|
|
2614
|
+
return lines.join("\n");
|
|
2615
|
+
}
|
|
2616
|
+
async function runOptimize(opts) {
|
|
2617
|
+
const { logs, claudeMd } = await loadAuditInputs({ path: opts.path, claudeMdPath: opts.claudeMdPath });
|
|
2618
|
+
const report = analyzeUploads(logs);
|
|
2619
|
+
const cmd = analyzeClaudeMd(claudeMd);
|
|
2620
|
+
const { pillars } = scorePillars(report, cmd, {});
|
|
2621
|
+
const { fixes } = synthesize(report, pillars, cmd);
|
|
2622
|
+
const projectDir = opts.projectDir || process.cwd();
|
|
2623
|
+
const project = await scanProject(projectDir);
|
|
2624
|
+
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
2625
|
+
const recoverable = cacheMissExposureUsd(report);
|
|
2626
|
+
const outDir = opts.out || join4(process.cwd(), "costclaw-out");
|
|
2627
|
+
await mkdir(outDir, { recursive: true });
|
|
2628
|
+
const playbookPath = join4(outDir, PLAYBOOK_NAME);
|
|
2629
|
+
await writeFile(playbookPath, result.playbook, "utf8");
|
|
2630
|
+
const settingsPath = join4(outDir, SETTINGS_NAME);
|
|
2631
|
+
await writeFile(settingsPath, result.settingsJson, "utf8");
|
|
2632
|
+
const lines = [];
|
|
2633
|
+
lines.push("CostClaw optimize");
|
|
2634
|
+
lines.push("");
|
|
2635
|
+
if (opts.write) {
|
|
2636
|
+
const target = opts.write;
|
|
2637
|
+
const backup = `${target}.bak`;
|
|
2638
|
+
if (await pathExists(backup) && !opts.force) {
|
|
2639
|
+
throw new Error(
|
|
2640
|
+
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
2641
|
+
);
|
|
2642
|
+
}
|
|
2643
|
+
let original = "";
|
|
2644
|
+
if (await pathExists(target)) {
|
|
2645
|
+
original = await readFile5(target, "utf8");
|
|
2646
|
+
}
|
|
2647
|
+
await writeFile(backup, original, "utf8");
|
|
2648
|
+
await writeFile(target, result.optimizedClaudeMd, "utf8");
|
|
2649
|
+
lines.push(`Backed up the original to ${backup}`);
|
|
2650
|
+
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
2651
|
+
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
2652
|
+
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
2653
|
+
lines.push("");
|
|
2654
|
+
lines.push("Diff (old vs new):");
|
|
2655
|
+
lines.push(lineDiff(original, result.optimizedClaudeMd));
|
|
2656
|
+
lines.push("");
|
|
2657
|
+
lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
|
|
2658
|
+
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
2659
|
+
} else {
|
|
2660
|
+
const optimizedPath = join4(outDir, OPTIMIZED_NAME);
|
|
2661
|
+
await writeFile(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
2662
|
+
lines.push("Dry run (no files of yours were changed).");
|
|
2663
|
+
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
2664
|
+
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
2665
|
+
lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
|
|
2666
|
+
lines.push("");
|
|
2667
|
+
lines.push(describeDetection(project));
|
|
2668
|
+
lines.push(`Recoverable spend (cache-miss exposure): ${usd3(recoverable)}`);
|
|
2669
|
+
lines.push("");
|
|
2670
|
+
lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
|
|
2671
|
+
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
2672
|
+
lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
|
|
2673
|
+
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied for you.");
|
|
2674
|
+
}
|
|
2675
|
+
if (result.notes.length > 0) {
|
|
2676
|
+
lines.push("");
|
|
2677
|
+
lines.push("Notes:");
|
|
2678
|
+
for (const note of result.notes) lines.push(` - ${note}`);
|
|
2679
|
+
}
|
|
2680
|
+
lines.push("");
|
|
2681
|
+
lines.push("Nothing left your machine.");
|
|
2682
|
+
return { output: lines.join("\n") };
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
// src/license.ts
|
|
2686
|
+
import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile2, rm } from "fs/promises";
|
|
2687
|
+
import { join as join5 } from "path";
|
|
2688
|
+
import { homedir as homedir3, hostname } from "os";
|
|
2689
|
+
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
2690
|
+
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
2691
|
+
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
2692
|
+
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
2693
|
+
-----END PUBLIC KEY-----`;
|
|
2694
|
+
var KEY_PREFIX = "CC1";
|
|
2695
|
+
var NOT_ACTIVATED_MESSAGE = [
|
|
2696
|
+
"costclaw optimize needs a license.",
|
|
2697
|
+
"",
|
|
2698
|
+
"Buy a one-time license at https://costclaw.io, then run:",
|
|
2699
|
+
" costclaw activate <your-license-key>",
|
|
2700
|
+
"",
|
|
2701
|
+
"costclaw audit is free and does not need a license."
|
|
2702
|
+
].join("\n");
|
|
2703
|
+
var INVALID_MESSAGE = [
|
|
2704
|
+
"The saved CostClaw license is not valid for this version.",
|
|
2705
|
+
"",
|
|
2706
|
+
"Re-activate with the key from your purchase email:",
|
|
2707
|
+
" costclaw activate <your-license-key>",
|
|
2708
|
+
"",
|
|
2709
|
+
"Key missing or not working? Email wes@dashclaw.io with your order number.",
|
|
2710
|
+
"costclaw audit stays free."
|
|
2711
|
+
].join("\n");
|
|
2712
|
+
function defaultConfigDir() {
|
|
2713
|
+
return join5(homedir3(), ".costclaw");
|
|
2714
|
+
}
|
|
2715
|
+
function licenseFile(dir) {
|
|
2716
|
+
return join5(dir, "license.json");
|
|
2717
|
+
}
|
|
2718
|
+
function base64UrlDecode(part) {
|
|
2719
|
+
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
2720
|
+
}
|
|
2721
|
+
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
2722
|
+
const parts = licenseKey.trim().split(".");
|
|
2723
|
+
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
2724
|
+
const [prefix, payloadPart, signaturePart] = parts;
|
|
2725
|
+
try {
|
|
2726
|
+
const publicKey = createPublicKey(publicKeyPem);
|
|
2727
|
+
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
2728
|
+
const signature = base64UrlDecode(signaturePart);
|
|
2729
|
+
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
2730
|
+
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
2731
|
+
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
2732
|
+
return payload;
|
|
2733
|
+
} catch {
|
|
2734
|
+
return null;
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
async function readStoredLicense(dir) {
|
|
2738
|
+
try {
|
|
2739
|
+
const data = JSON.parse(await readFile6(licenseFile(dir), "utf8"));
|
|
2740
|
+
if (!data || typeof data.licenseKey !== "string") return null;
|
|
2741
|
+
return data;
|
|
2742
|
+
} catch {
|
|
2743
|
+
return null;
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
async function writeStoredLicense(dir, lic) {
|
|
2747
|
+
await mkdir2(dir, { recursive: true });
|
|
2748
|
+
await writeFile2(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
2749
|
+
}
|
|
2750
|
+
async function clearStoredLicense(dir) {
|
|
2751
|
+
await rm(licenseFile(dir), { force: true });
|
|
2752
|
+
}
|
|
2753
|
+
async function activateLicense(licenseKey, opts = {}) {
|
|
2754
|
+
const key = licenseKey.trim();
|
|
2755
|
+
if (!key) throw new Error("Provide your license key: costclaw activate <key>");
|
|
2756
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2757
|
+
const payload = verifyLicenseKey(key, opts.publicKeyPem);
|
|
2758
|
+
if (!payload) {
|
|
2759
|
+
throw new Error(
|
|
2760
|
+
"Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
|
|
2761
|
+
);
|
|
2762
|
+
}
|
|
2763
|
+
const stored = {
|
|
2764
|
+
licenseKey: key,
|
|
2765
|
+
instanceId: "local",
|
|
2766
|
+
instanceName: opts.instanceName?.trim() || hostname(),
|
|
2767
|
+
email: payload.e,
|
|
2768
|
+
activatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2769
|
+
};
|
|
2770
|
+
await writeStoredLicense(configDir, stored);
|
|
2771
|
+
return stored;
|
|
2772
|
+
}
|
|
2773
|
+
async function checkLicense(opts = {}) {
|
|
2774
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2775
|
+
const stored = await readStoredLicense(configDir);
|
|
2776
|
+
if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
|
|
2777
|
+
const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
|
|
2778
|
+
if (payload) {
|
|
2779
|
+
return { ok: true, email: payload.e ?? stored.email };
|
|
2780
|
+
}
|
|
2781
|
+
await clearStoredLicense(configDir);
|
|
2782
|
+
return { ok: false, message: INVALID_MESSAGE };
|
|
2783
|
+
}
|
|
2784
|
+
async function deactivateLicense(opts = {}) {
|
|
2785
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
2786
|
+
const stored = await readStoredLicense(configDir);
|
|
2787
|
+
if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
|
|
2788
|
+
await clearStoredLicense(configDir);
|
|
2789
|
+
}
|
|
2790
|
+
|
|
1238
2791
|
// src/index.ts
|
|
1239
2792
|
process.on("unhandledRejection", (reason) => {
|
|
1240
2793
|
console.error("Unhandled rejection:", reason);
|
|
@@ -1255,15 +2808,71 @@ async function main() {
|
|
|
1255
2808
|
process.stdout.write(output + "\n");
|
|
1256
2809
|
return;
|
|
1257
2810
|
}
|
|
2811
|
+
if (command === "activate") {
|
|
2812
|
+
const key = args[0] && !args[0].startsWith("--") ? args[0] : void 0;
|
|
2813
|
+
if (!key) {
|
|
2814
|
+
process.stderr.write("Usage: costclaw activate <license-key> [--name <machine-name>]\n");
|
|
2815
|
+
process.exit(1);
|
|
2816
|
+
}
|
|
2817
|
+
const lic = await activateLicense(key, { instanceName: getFlag(args, "--name") });
|
|
2818
|
+
const who = lic.email ? ` (licensed to ${lic.email})` : "";
|
|
2819
|
+
process.stdout.write(`costclaw optimize is unlocked on this machine${who}.
|
|
2820
|
+
Run: costclaw optimize
|
|
2821
|
+
`);
|
|
2822
|
+
return;
|
|
2823
|
+
}
|
|
2824
|
+
if (command === "deactivate") {
|
|
2825
|
+
await deactivateLicense();
|
|
2826
|
+
process.stdout.write(
|
|
2827
|
+
"Your CostClaw license has been released from this machine. You can activate it on another machine now.\n"
|
|
2828
|
+
);
|
|
2829
|
+
return;
|
|
2830
|
+
}
|
|
2831
|
+
if (command === "optimize") {
|
|
2832
|
+
const gate = await checkLicense();
|
|
2833
|
+
if (!gate.ok) {
|
|
2834
|
+
process.stderr.write(gate.message + "\n");
|
|
2835
|
+
process.exit(1);
|
|
2836
|
+
}
|
|
2837
|
+
if (gate.offline) {
|
|
2838
|
+
process.stderr.write("Could not reach the license server; running on your saved activation.\n");
|
|
2839
|
+
}
|
|
2840
|
+
const { output } = await runOptimize({
|
|
2841
|
+
path: getFlag(args, "--path"),
|
|
2842
|
+
claudeMdPath: getFlag(args, "--claude-md"),
|
|
2843
|
+
projectDir: getFlag(args, "--project") || process.cwd(),
|
|
2844
|
+
out: getFlag(args, "--out"),
|
|
2845
|
+
write: getFlag(args, "--write"),
|
|
2846
|
+
force: args.includes("--force")
|
|
2847
|
+
});
|
|
2848
|
+
process.stdout.write(output + "\n");
|
|
2849
|
+
return;
|
|
2850
|
+
}
|
|
1258
2851
|
process.stderr.write(
|
|
1259
2852
|
[
|
|
1260
2853
|
"CostClaw - privacy-first Claude Code cost and setup audit",
|
|
1261
2854
|
"",
|
|
1262
2855
|
"Usage:",
|
|
1263
2856
|
" costclaw audit [--path <dir>] [--claude-md <file>] [--json]",
|
|
2857
|
+
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--force]",
|
|
2858
|
+
" costclaw activate <license-key> [--name <machine-name>]",
|
|
2859
|
+
" costclaw deactivate",
|
|
2860
|
+
"",
|
|
2861
|
+
"audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
|
|
2862
|
+
"machine and prints a cost report plus a six-pillar setup score. It is free.",
|
|
2863
|
+
"",
|
|
2864
|
+
"optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
|
|
2865
|
+
"scaffold and a prioritized fix playbook. It also scans --project <dir>",
|
|
2866
|
+
"(default: the current directory) to auto-fill the scaffold's name, commands,",
|
|
2867
|
+
"structure, and other facts from your real project files. By default it",
|
|
2868
|
+
"dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
|
|
2869
|
+
"optimized CLAUDE.md in place after backing up the original and printing a diff.",
|
|
2870
|
+
"optimize needs a one-time license: buy at https://costclaw.io, then run",
|
|
2871
|
+
"costclaw activate <key>. activate and deactivate move that license between",
|
|
2872
|
+
"machines. audit never needs a license.",
|
|
1264
2873
|
"",
|
|
1265
|
-
"
|
|
1266
|
-
"
|
|
2874
|
+
"Everything runs locally. Nothing is uploaded. The only network call is the",
|
|
2875
|
+
"license check to Lemon Squeezy, which sends just the key, never your logs.",
|
|
1267
2876
|
""
|
|
1268
2877
|
].join("\n") + "\n"
|
|
1269
2878
|
);
|