costclaw 0.7.0 → 0.8.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.
Files changed (3) hide show
  1. package/README.md +33 -2
  2. package/dist/index.js +104 -18
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -179,8 +179,9 @@ npx costclaw optimize
179
179
  ```
180
180
 
181
181
  Turns the same audit into done-for-you artifacts: an optimized `CLAUDE.md`
182
- scaffold, a prioritized fix playbook, and a conservative, project-derived
183
- `settings.suggested.json` permission allowlist. It scans `--project <dir>`
182
+ scaffold, a prioritized fix playbook, a conservative, project-derived
183
+ `settings.suggested.json` permission allowlist, and a `HARNESS-UPGRADE.md` work
184
+ order for your own Claude Code. It scans `--project <dir>`
184
185
  (default: the current directory) to auto-fill the scaffold from your real files.
185
186
  By default it dry-runs into `./costclaw-out` and touches none of your files.
186
187
 
@@ -195,6 +196,36 @@ And it tells you what it actually did to the file that rides on every turn:
195
196
  Your CLAUDE.md: an estimated 5,266 tokens to 2,479 (52.9% smaller), paid on every turn.
196
197
  ```
197
198
 
199
+ costclaw never calls a model, so it does not rewrite your prose: your own sections
200
+ are carried through exactly as written. When that carried prose is most of what is
201
+ left, the receipt says so rather than presenting a small percentage as a win:
202
+
203
+ ```
204
+ About 1,714 of those tokens are your own prose, carried through as written.
205
+ costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md
206
+ ranks your heaviest sections and flags the dated lines to move into docs/.
207
+ ```
208
+
209
+ `HARNESS-UPGRADE.md` is the fourth artifact: a work order you hand to your own
210
+ Claude Code (`claude "Follow costclaw-out/HARNESS-UPGRADE.md"`). It carries the
211
+ merge and permission tasks plus evidence-conditional ones, and when your carried
212
+ prose is heavy it ranks it so the trimming is a worklist instead of a guess:
213
+
214
+ ```
215
+ Heaviest carried sections, largest first:
216
+
217
+ - Core Philosophy: est. 1,382 tokens.
218
+ - How to Work: est. 1,267 tokens, 2 dated lines.
219
+ - Communication and Output: est. 550 tokens, 3 dated lines.
220
+
221
+ The remaining 6 carried sections account for the other 1,880 tokens.
222
+ ```
223
+
224
+ Those rows plus the remainder line add up to the stated total, the same way the
225
+ playbook's per-project table reconciles. costclaw sets no target line count
226
+ anywhere: it measures what your sections cost and which lines carry dates, and
227
+ leaves the keep-or-move judgment to you.
228
+
198
229
  The playbook breaks the recoverable headline down by project, so you can see
199
230
  which repo owes which dollars and at what cache hit rate:
200
231
 
package/dist/index.js CHANGED
@@ -1260,11 +1260,14 @@ var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
1260
1260
  function severityRank(s) {
1261
1261
  return s === "critical" ? 3 : s === "warn" ? 2 : 1;
1262
1262
  }
1263
+ function num2(n) {
1264
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1265
+ }
1263
1266
  function sizeFix(cmd) {
1264
1267
  if (cmd.chars > 6e3) {
1265
1268
  return {
1266
1269
  title: "Trim your CLAUDE.md",
1267
- action: `Your CLAUDE.md is an estimated ${cmd.estTokens.toLocaleString()} tokens (${cmd.chars.toLocaleString()} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
1270
+ action: `Your CLAUDE.md is an estimated ${num2(cmd.estTokens)} tokens (${num2(cmd.chars)} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
1268
1271
  };
1269
1272
  }
1270
1273
  return {
@@ -1620,6 +1623,9 @@ function usd(n) {
1620
1623
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1621
1624
  return `${neg ? "-" : ""}$${grouped}${cents}`;
1622
1625
  }
1626
+ function num3(n) {
1627
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1628
+ }
1623
1629
  function clean(text2) {
1624
1630
  return sanitizeText(text2);
1625
1631
  }
@@ -1664,16 +1670,25 @@ function parseSections(md) {
1664
1670
  const lines = md.split(/\r?\n/);
1665
1671
  const sections = [];
1666
1672
  let current = null;
1673
+ const finish = (c) => {
1674
+ const body = c.body.join("\n").trim();
1675
+ return {
1676
+ heading: c.heading,
1677
+ body,
1678
+ tokens: Math.round(body.length / 4),
1679
+ volatileLines: c.body.filter((l) => VOLATILE_MARKER.test(l)).length
1680
+ };
1681
+ };
1667
1682
  for (const line of lines) {
1668
1683
  const m = line.match(/^##\s+(.+?)\s*$/);
1669
1684
  if (m) {
1670
- if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1685
+ if (current) sections.push(finish(current));
1671
1686
  current = { heading: m[1], body: [] };
1672
1687
  } else if (current) {
1673
1688
  current.body.push(line);
1674
1689
  }
1675
1690
  }
1676
- if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1691
+ if (current) sections.push(finish(current));
1677
1692
  return sections.filter((s) => s.body.length > 0);
1678
1693
  }
1679
1694
  var REGENERATED_HEADING = [
@@ -1693,7 +1708,9 @@ function carriedSections(currentClaudeMd) {
1693
1708
  other: [],
1694
1709
  droppedVolatile: [],
1695
1710
  replaced: [],
1696
- commandsBody: null
1711
+ commandsBody: null,
1712
+ carriedTokens: 0,
1713
+ carriedList: []
1697
1714
  };
1698
1715
  if (!currentClaudeMd) return out;
1699
1716
  for (const section of parseSections(currentClaudeMd)) {
@@ -1706,10 +1723,16 @@ function carriedSections(currentClaudeMd) {
1706
1723
  }
1707
1724
  } else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
1708
1725
  out.workflow = section.body;
1726
+ out.carriedTokens += section.tokens;
1727
+ out.carriedList.push(section);
1709
1728
  } else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
1710
1729
  out.architecture = section.body;
1730
+ out.carriedTokens += section.tokens;
1731
+ out.carriedList.push(section);
1711
1732
  } else {
1712
1733
  out.other.push(section);
1734
+ out.carriedTokens += section.tokens;
1735
+ out.carriedList.push(section);
1713
1736
  }
1714
1737
  }
1715
1738
  return out;
@@ -1800,8 +1823,8 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
1800
1823
  " How to use this file:",
1801
1824
  " - Replace every placeholder comment with your project's real details, then",
1802
1825
  " delete any line that does not earn its place.",
1803
- " - Keep it lean. Current Anthropic guidance is under about 200 lines. For each",
1804
- ' line ask "would removing this make the agent make a mistake?" If not, cut it.',
1826
+ ' - Keep it lean, but do not cut to a line count. For each line ask "would',
1827
+ ' removing this make the agent make a mistake?" If not, cut it.',
1805
1828
  " - Only include what the agent cannot infer from the code: commands it cannot",
1806
1829
  " guess, conventions that differ from the language defaults, and non-obvious",
1807
1830
  " gotchas. Skip anything self-evident.",
@@ -2245,7 +2268,7 @@ function claudeMdReceiptLine(claudeMdTokens) {
2245
2268
  const grew = delta > 0;
2246
2269
  const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
2247
2270
  const tail = grew ? "It is re-read on every turn, so the larger file costs a little more every time too." : "It is re-read on every turn, so that saving repeats every session.";
2248
- return `Your optimized CLAUDE.md goes from an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()}${pct2}. ${tail}`;
2271
+ return `Your optimized CLAUDE.md goes from an estimated ${num3(before)} tokens to ${num3(after)}${pct2}. ${tail}`;
2249
2272
  }
2250
2273
  function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
2251
2274
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
@@ -2315,7 +2338,9 @@ function buildSettings(project) {
2315
2338
  const settings = { permissions: { allow, deny: [...BASE_DENY] } };
2316
2339
  return clean(JSON.stringify(settings, null, 2) + "\n");
2317
2340
  }
2318
- function buildHarnessPrompt(input, carried) {
2341
+ var CARRY_HEAVY_TOKENS = 1500;
2342
+ var CARRY_WORKLIST_CAP = 8;
2343
+ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2319
2344
  const project = input.project;
2320
2345
  const name = project?.name?.trim() || "this project";
2321
2346
  const findings = input.report.findings;
@@ -2342,8 +2367,9 @@ function buildHarnessPrompt(input, carried) {
2342
2367
  "- Never invent project facts. When a merge choice is unclear, ask.",
2343
2368
  "- Show a diff before replacing any human-written file, and back the",
2344
2369
  " file up first (CLAUDE.md -> CLAUDE.md.bak).",
2345
- "- Keep the final CLAUDE.md lean: under about 200 lines, and every line",
2346
- ' must pass "would removing this make the agent make a mistake?"',
2370
+ '- Keep the final CLAUDE.md lean: every line must pass "would removing',
2371
+ ' this make the agent make a mistake?" Cut what fails that test, not down',
2372
+ " to a line count. There is no target number of lines.",
2347
2373
  "- Commit per this repo's conventions when a task completes cleanly."
2348
2374
  ].join("\n")
2349
2375
  );
@@ -2376,6 +2402,43 @@ function buildHarnessPrompt(input, carried) {
2376
2402
  ].join("\n")
2377
2403
  );
2378
2404
  let n = 3;
2405
+ const worklist = [...carried.carriedList].sort((a, b) => b.tokens - a.tokens).slice(0, CARRY_WORKLIST_CAP);
2406
+ if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
2407
+ const rows = worklist.map((s) => {
2408
+ const n2 = s.volatileLines;
2409
+ const dated = n2 > 0 ? `, ${num3(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
2410
+ return `- ${s.heading}: est. ${num3(s.tokens)} tokens${dated}.`;
2411
+ });
2412
+ const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
2413
+ const rest = carried.carriedList.length - worklist.length;
2414
+ const tail = rest > 0 ? [`The remaining ${num3(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num3(carried.carriedTokens - shown)} tokens.`] : [];
2415
+ const before = claudeMdTokens.before;
2416
+ const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
2417
+ const consequence = saved <= 0 ? "that is why the optimized file is no smaller." : saved < 0.2 ? "that is why the optimized file is barely smaller." : "it is the weight that is left.";
2418
+ parts.push(
2419
+ [
2420
+ `## Task ${n++}: Reclaim the carried sections`,
2421
+ "",
2422
+ `Your CLAUDE.md carries an estimated ${num3(carried.carriedTokens)} tokens of your`,
2423
+ "own prose, paid on every turn of every session.",
2424
+ `costclaw does not rewrite your prose, so it passed all of it through untouched:`,
2425
+ `${consequence} Doing the actual trimming is this task,`,
2426
+ "and it needs judgment costclaw will not fake.",
2427
+ "",
2428
+ "Heaviest carried sections, largest first:",
2429
+ "",
2430
+ ...rows,
2431
+ ...tail,
2432
+ "",
2433
+ "For each one decide, line by line: is this a durable operating rule the agent",
2434
+ "needs loaded every turn, or is it narrative history? Dated lines are the usual",
2435
+ "giveaway for history. Rules stay in CLAUDE.md. History moves to docs/ (a",
2436
+ "DECISIONS.md for choices, an ERRORS.md for incidents) where the agent can open",
2437
+ "it on demand. Move it, do not delete it. Ask before cutting anything you cannot",
2438
+ "confidently classify."
2439
+ ].join("\n")
2440
+ );
2441
+ }
2379
2442
  if (carried.droppedVolatile.length > 0) {
2380
2443
  parts.push(
2381
2444
  [
@@ -2445,9 +2508,15 @@ function buildHarnessPrompt(input, carried) {
2445
2508
  const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
2446
2509
  if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
2447
2510
  if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
2511
+ verify.push("- Confirm no generator comment blocks are left in CLAUDE.md.");
2512
+ if (carried.carriedTokens >= CARRY_HEAVY_TOKENS) {
2513
+ verify.push(
2514
+ "- Confirm every line moved out of CLAUDE.md landed in a file under",
2515
+ " docs/, and that re-reading CLAUDE.md start to finish still answers",
2516
+ " what the agent needs to know. Report the token count before and after."
2517
+ );
2518
+ }
2448
2519
  verify.push(
2449
- "- Confirm CLAUDE.md is under about 200 lines with no generator comments",
2450
- " left in it.",
2451
2520
  "- After about a week of normal usage, run `npx costclaw audit`: the",
2452
2521
  ' "Since optimize" line measures the cache-hit movement these changes',
2453
2522
  " are meant to produce."
@@ -2466,9 +2535,10 @@ function optimize(input) {
2466
2535
  before: input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null,
2467
2536
  after: Math.round(optimizedClaudeMd.trim().length / 4)
2468
2537
  };
2538
+ const carriedTokens = carried.carriedTokens;
2469
2539
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
2470
2540
  const settingsJson = buildSettings(input.project);
2471
- const harnessPrompt = buildHarnessPrompt(input, carried);
2541
+ const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
2472
2542
  const cleanNotes = notes.map((n) => clean(n));
2473
2543
  const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
2474
2544
  if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
@@ -2480,6 +2550,7 @@ function optimize(input) {
2480
2550
  notes: cleanNotes.map(sanitizeText),
2481
2551
  placeholdersRemaining: stats.placeholders,
2482
2552
  claudeMdTokens,
2553
+ carriedTokens,
2483
2554
  sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
2484
2555
  };
2485
2556
  }
@@ -2491,6 +2562,7 @@ function optimize(input) {
2491
2562
  notes: cleanNotes,
2492
2563
  placeholdersRemaining: stats.placeholders,
2493
2564
  claudeMdTokens,
2565
+ carriedTokens,
2494
2566
  sectionDispositions: cleanDispositions
2495
2567
  };
2496
2568
  }
@@ -3699,6 +3771,9 @@ function approxTokens(n) {
3699
3771
  function plural2(n, noun) {
3700
3772
  return n === 1 ? noun : `${noun}s`;
3701
3773
  }
3774
+ function num4(n) {
3775
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3776
+ }
3702
3777
  var STYLE2 = `
3703
3778
  :root{
3704
3779
  --bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
@@ -4026,11 +4101,13 @@ function renderArtifactCards(input) {
4026
4101
  function renderApplyCta(input) {
4027
4102
  return `<div class="cta"><b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
4028
4103
  }
4029
- function renderCarriedDisclosure(sections) {
4104
+ function renderCarriedDisclosure(sections, carriedTokens) {
4030
4105
  const carried = sections.filter((s) => s.disposition === "carried");
4031
4106
  if (carried.length === 0) return "";
4032
4107
  const names = carried.map((s) => esc(s.name)).join(" &middot; ");
4033
- return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md</summary><div class="cols">${names}</div></details>`;
4108
+ const weight = carriedTokens > 0 ? `, about ${num4(carriedTokens)} tokens` : "";
4109
+ const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
4110
+ return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
4034
4111
  }
4035
4112
  function renderHeader(input) {
4036
4113
  const parts = [];
@@ -4071,7 +4148,7 @@ ${renderArtifactCards(input)}
4071
4148
  <h2>Apply it</h2>
4072
4149
  ${renderApplyCta(input)}
4073
4150
 
4074
- ${renderCarriedDisclosure(input.sectionDispositions)}
4151
+ ${renderCarriedDisclosure(input.sectionDispositions, input.carriedTokens)}
4075
4152
 
4076
4153
  <footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
4077
4154
  No network calls, no telemetry, no model calls.</footer>
@@ -4772,6 +4849,7 @@ async function runOptimize(opts) {
4772
4849
  currentClaudeMd: claudeMd ?? null,
4773
4850
  optimizedClaudeMd: result.optimizedClaudeMd,
4774
4851
  claudeMdTokens: result.claudeMdTokens,
4852
+ carriedTokens: result.carriedTokens,
4775
4853
  sectionDispositions: result.sectionDispositions,
4776
4854
  placeholdersRemaining: result.placeholdersRemaining,
4777
4855
  fixes,
@@ -4840,9 +4918,17 @@ async function runOptimize(opts) {
4840
4918
  if (before != null && before !== after) {
4841
4919
  const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
4842
4920
  const dir = after > before ? "larger" : "smaller";
4921
+ const g = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4843
4922
  lines.push(
4844
- `Your CLAUDE.md: an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()} (${pct2}% ${dir}), paid on every turn.`
4923
+ `Your CLAUDE.md: an estimated ${g(before)} tokens to ${g(after)} (${pct2}% ${dir}), paid on every turn.`
4845
4924
  );
4925
+ if (result.carriedTokens >= after / 2) {
4926
+ lines.push(
4927
+ `About ${g(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
4928
+ "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
4929
+ "ranks your heaviest sections and flags the dated lines to move into docs/."
4930
+ );
4931
+ }
4846
4932
  }
4847
4933
  lines.push("");
4848
4934
  if (result.placeholdersRemaining > 0) {
@@ -5207,7 +5293,7 @@ function parseBadgeFlags(args) {
5207
5293
  };
5208
5294
  }
5209
5295
  function cliVersion() {
5210
- return true ? "0.7.0" : "0.0.0-dev";
5296
+ return true ? "0.8.0" : "0.0.0-dev";
5211
5297
  }
5212
5298
  function isHelpRequest(command, args) {
5213
5299
  if (command === void 0) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
5
5
  "type": "module",
6
6
  "bin": {