costclaw 0.13.2 → 0.15.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 +76 -72
  2. package/dist/index.js +475 -55
  3. package/package.json +47 -47
package/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  A local cost and setup audit for [Claude Code](https://claude.com/claude-code).
4
4
  Point it at your session logs and it shows where token spend leaks, scores your
5
- setup across six pillars, and ranks counterfactual opportunities by estimated
6
- token value.
5
+ setup across six pillars, and ranks counterfactual opportunities by estimated
6
+ token value.
7
7
 
8
- Your prompts are analyzed locally and never uploaded. The audit parses the logs
9
- already on your disk and prints a report.
8
+ Your prompts are analyzed locally and never uploaded. The audit parses the logs
9
+ already on your disk and prints a report.
10
10
 
11
11
  ## Use it
12
12
 
@@ -16,43 +16,43 @@ Requires Node 20+.
16
16
  npx costclaw audit
17
17
  ```
18
18
 
19
- That reads `~/.claude/projects` (override with `--path <dir>`) and prints a
20
- local report. This concise example is synthetic, generated from synthetic inputs:
19
+ That reads `~/.claude/projects` (override with `--path <dir>`) and prints a
20
+ local report. This concise example is synthetic, generated from synthetic inputs:
21
21
 
22
22
  ```
23
23
  CostClaw audit
24
- Source: synthetic example (1 session across 1 project)
25
- CLAUDE.md: synthetic input
26
-
27
- Cache-miss exposure (estimate): $90.01
28
-
29
- Estimated current API-equivalent valuation: $100.01 Cache hit: 0.0% Session hours (timestamp union): 1.0
30
- Model spend: opus 0.01% / haiku 99.99%
31
-
32
- Rule-based setup score: 74 / 100 (Solid)
33
- CLAUDE.md quality 72
34
- Context hygiene 50
35
- Prompting patterns 75
36
- Session management 100
37
- Tool and MCP config 88
38
- Cost discipline 67
39
-
40
- Top opportunities by estimated exposure:
41
- - [$90.01] Reduce cache-miss exposure
42
- Synthetic cache-read counterfactual; cold and unique inputs may not be cacheable.
24
+ Source: synthetic example (1 session across 1 project)
25
+ CLAUDE.md: synthetic input
26
+
27
+ Cache-miss exposure (estimate): $90.01
28
+
29
+ Estimated current API-equivalent valuation: $100.01 Cache hit: 0.0% Session hours (timestamp union): 1.0
30
+ Model spend: opus 0.01% / haiku 99.99%
31
+
32
+ Rule-based setup score: 74 / 100 (Solid)
33
+ CLAUDE.md quality 72
34
+ Context hygiene 50
35
+ Prompting patterns 75
36
+ Session management 100
37
+ Tool and MCP config 88
38
+ Cost discipline 67
39
+
40
+ Top opportunities by estimated exposure:
41
+ - [$90.01] Reduce cache-miss exposure
42
+ Synthetic cache-read counterfactual; cold and unique inputs may not be cacheable.
43
43
  ```
44
44
 
45
- The audit applies rules to observed cache and setup patterns. Its suggested causes
46
- and actions are hypotheses to inspect, not diagnoses or proof that a change will save
47
- money. Burn Clock needs at least 7 active days of logs; below that it is left out.
45
+ The audit applies rules to observed cache and setup patterns. Its suggested causes
46
+ and actions are hypotheses to inspect, not diagnoses or proof that a change will save
47
+ money. Burn Clock needs at least 7 active days of logs; below that it is left out.
48
48
 
49
49
  ## On a subscription? Declare your plan
50
50
 
51
51
  Every dollar the audit prints is an API-equivalent price: what those tokens
52
52
  would cost at pay-as-you-go rates. On a Claude subscription (Pro or Max) your
53
- usage within an included allowance may have no marginal token charge. Extra Usage
54
- can be billed, so API-equivalent figures are neither money back nor a statement of
55
- your actual subscription charges.
53
+ usage within an included allowance may have no marginal token charge. Extra Usage
54
+ can be billed, so API-equivalent figures are neither money back nor a statement of
55
+ your actual subscription charges.
56
56
 
57
57
  The first interactive run asks which one you are on and remembers the answer, so
58
58
  usually there is nothing to do. To set it directly, or to change it later:
@@ -64,21 +64,21 @@ npx costclaw audit --plan max20x # or pro, max5x; --plan api switches back
64
64
  Piped runs, `--json` and CI are never asked and assume API rates, so a scripted
65
65
  audit never blocks waiting for an answer.
66
66
 
67
- The headline becomes cache-miss exposure - a counterfactual comparison of logged
68
- token use with a cache-read scenario - with dollars as API-equivalent context. The
69
- following uses the same synthetic example:
67
+ The headline becomes cache-miss exposure - a counterfactual comparison of logged
68
+ token use with a cache-read scenario - with dollars as API-equivalent context. The
69
+ following uses the same synthetic example:
70
70
 
71
71
  ```
72
- Cache-miss exposure (counterfactual): 90.0% of analyzed usage ($90.01 at API rates)
73
-
74
- Estimated current API-equivalent valuation: $100.01 Cache hit: 0.0% Session hours (timestamp union): 1.0
75
- Plan: max20x. This synthetic example does not measure quota, billing, or promise
76
- more work. Activity windows are omitted when there is insufficient history.
72
+ Cache-miss exposure (counterfactual): 90.0% of analyzed usage ($90.01 at API rates)
73
+
74
+ Estimated current API-equivalent valuation: $100.01 Cache hit: 0.0% Session hours (timestamp union): 1.0
75
+ Plan: max20x. This synthetic example does not measure quota, billing, or promise
76
+ more work. Activity windows are omitted when there is insufficient history.
77
77
  ```
78
78
 
79
- Usage windows are fixed activity bins based on local timestamps. They summarize
80
- observed activity only: CostClaw does not know Anthropic's actual quota, rate-limit
81
- windows, subscription inclusion, or billing adjustments.
79
+ Usage windows are fixed activity bins based on local timestamps. They summarize
80
+ observed activity only: CostClaw does not know Anthropic's actual quota, rate-limit
81
+ windows, subscription inclusion, or billing adjustments.
82
82
 
83
83
  The value is saved to `~/.costclaw/config.json`, so later runs (and `optimize`)
84
84
  remember it. The findings and their ranking are identical either way; only the
@@ -91,6 +91,10 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--h
91
91
  ```
92
92
 
93
93
  - `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
94
+ To audit **one project** instead of all of them, pass that project's own
95
+ directory under `~/.claude/projects` — the one named after its path, like
96
+ `~/.claude/projects/C--Users-you-Projects-myapp`. The report then covers that
97
+ project alone and says `1 project`.
94
98
  - `--claude-md <file>` score a specific CLAUDE.md file's quality (by default the
95
99
  audit scores `~/.claude/CLAUDE.md` when it exists).
96
100
  - `--plan <api|pro|max5x|max20x>` declare how you pay for Claude (see above);
@@ -107,24 +111,24 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--h
107
111
  "What to do next" ramp: the commands to run next, how the optimize license
108
112
  works, and a command reference.
109
113
  - `--card [file]` also write a shareable score card SVG (default
110
- `costclaw-card.svg`): your score, band, cache-miss exposure estimate, cache hit rate, and
114
+ `costclaw-card.svg`): your score, band, cache-miss exposure estimate, cache hit rate, and
111
115
  strongest pillar. A static file, no fonts or network calls.
112
116
 
113
117
  Run `costclaw --version` (or `-v` / `costclaw version`) to print the installed
114
- CLI version.
115
-
116
- ## Accuracy boundary
117
-
118
- The report estimates current API-equivalent list-price value from logged usage and a
119
- dated rate table. It is not billing proof. Unknown model IDs, unavailable pricing
120
- modifiers, and incomplete logs add uncertainty. Repeated cumulative request updates
121
- are counted once using the highest coherent observed total; logged cache TTL splits are priced
122
- when available. A top-level/split conflict retains the valid top-level count at the
123
- conservative one-hour rate with a warning; legacy writes without a split use five-minute
124
- pricing with a warning. Cache-miss exposure is a counterfactual, and the setup score uses
125
- rules rather than a provider quality grade. The release retests these boundaries with
126
- `npm test --workspace @costclaw/engine -- accuracy-regression` and
127
- `npm test --workspace costclaw -- accuracy-report`.
118
+ CLI version.
119
+
120
+ ## Accuracy boundary
121
+
122
+ The report estimates current API-equivalent list-price value from logged usage and a
123
+ dated rate table. It is not billing proof. Unknown model IDs, unavailable pricing
124
+ modifiers, and incomplete logs add uncertainty. Repeated cumulative request updates
125
+ are counted once using the highest coherent observed total; logged cache TTL splits are priced
126
+ when available. A top-level/split conflict retains the valid top-level count at the
127
+ conservative one-hour rate with a warning; legacy writes without a split use five-minute
128
+ pricing with a warning. Cache-miss exposure is a counterfactual, and the setup score uses
129
+ rules rather than a provider quality grade. The release retests these boundaries with
130
+ `npm test --workspace @costclaw/engine -- accuracy-regression` and
131
+ `npm test --workspace costclaw -- accuracy-report`.
128
132
 
129
133
  ## Diff
130
134
 
@@ -135,8 +139,8 @@ Every audit run saves a snapshot of the derived record to `~/.costclaw/history`
135
139
  npx costclaw diff
136
140
  ```
137
141
 
138
- That compares your latest two audits and shows movement in the estimates. It does not
139
- verify money recovered. The numeric example below is illustrative:
142
+ That compares your latest two audits and shows movement in the estimates. It does not
143
+ verify money recovered. The numeric example below is illustrative:
140
144
 
141
145
  ```
142
146
  CostClaw diff
@@ -145,14 +149,14 @@ Baseline: 2026-06-09 Current: 2026-07-09 (30 days)
145
149
  Since the baseline:
146
150
  New spend $842.10 across 210 new sessions
147
151
  Marginal cache hit 97.1% (lifetime 96.2%)
148
- Cache-miss exposure (estimate) +$96.40 (now $1131.61)
152
+ Cache-miss exposure (estimate) +$96.40 (now $1131.61)
149
153
 
150
- Rule-based setup score: 83 -> 86 (+3, Tight)
154
+ Rule-based setup score: 83 -> 86 (+3, Tight)
151
155
  CLAUDE.md quality 69 -> 78 (+9)
152
156
  ...
153
157
 
154
158
  Fixes resolved since the baseline:
155
- - [$52.40] Review model fit for 61 small sessions
159
+ - [$52.40] Review model fit for 61 small sessions
156
160
  ```
157
161
 
158
162
  The marginal cache hit rate covers only the period between the two audits, which
@@ -179,10 +183,10 @@ its band. Drop it in a README with a plain image tag:
179
183
  costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]
180
184
  ```
181
185
 
182
- ## Optimize
183
-
184
- The numeric examples in this section are illustrative placeholders, not output from
185
- an account or a promise of savings.
186
+ ## Optimize
187
+
188
+ The numeric examples in this section are illustrative placeholders, not output from
189
+ an account or a promise of savings.
186
190
 
187
191
  ```bash
188
192
  npx costclaw optimize
@@ -258,13 +262,13 @@ playbook's per-project table reconciles. costclaw sets no target line count
258
262
  anywhere: it measures what your sections cost and which lines carry dates, and
259
263
  leaves the keep-or-move judgment to you.
260
264
 
261
- The playbook breaks the cache-miss exposure estimate down by project, so you can see
262
- which repository has modeled exposure and at what cache hit rate:
265
+ The playbook breaks the cache-miss exposure estimate down by project, so you can see
266
+ which repository has modeled exposure and at what cache hit rate:
263
267
 
264
268
  ```
265
269
  ### Where that money is
266
270
 
267
- | Project | Cache-miss exposure (estimate) | Cache hit | Main sessions |
271
+ | Project | Cache-miss exposure (estimate) | Cache hit | Main sessions |
268
272
  | --- | --- | --- | --- |
269
273
  | some-app | $490.43 | 98% | 229 |
270
274
  | another-app | $312.43 | 99% | 131 |
@@ -322,6 +326,6 @@ costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from
322
326
 
323
327
  ## Privacy
324
328
 
325
- The audit saves a derived `AuditRecord`: totals and generated prose, with no raw
326
- prompt text, file paths, or secrets. A hosted dashboard is on the roadmap and would
327
- receive only that derived record, never your logs.
329
+ The audit saves a derived `AuditRecord`: totals and generated prose, with no raw
330
+ prompt text, file paths, or secrets. A hosted dashboard is on the roadmap and would
331
+ receive only that derived record, never your logs.
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { fileURLToPath } from "url";
5
- import { realpathSync } from "fs";
6
- import { homedir as homedir7 } from "os";
5
+ import { realpathSync, existsSync } from "fs";
6
+ import { join as join12, dirname as dirname4 } from "path";
7
+ import { homedir as homedir8 } from "os";
7
8
 
8
9
  // ../../packages/engine/src/types.ts
9
10
  function emptyTotals() {
@@ -2698,6 +2699,7 @@ var REGENERATED_HEADING = [
2698
2699
  /^env(ironment)?\b/i
2699
2700
  ];
2700
2701
  var VOLATILE_HEADING = /^(status|changelog|progress|history|roadmap|todos?|next steps)\b/i;
2702
+ var WORKING_AGREEMENT_HEADING = /^(working agreement|working agreements|ground rules|how (we|you) work)\b/i;
2701
2703
  var WORKFLOW_HEADING = /workflow|etiquette|contributing|branch|commit/i;
2702
2704
  var ARCH_HEADING = /architecture|gotcha|footgun|how it works|data flow|overview/i;
2703
2705
  function carriedSections(currentClaudeMd) {
@@ -2800,7 +2802,7 @@ function stackOneLiner(stack) {
2800
2802
  }
2801
2803
  return `A ${joined} project.`;
2802
2804
  }
2803
- function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy) {
2805
+ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy, missingEvidence) {
2804
2806
  const re = REGENERATED_HEADING[categoryIndex];
2805
2807
  const wasReplaced = carried.replaced.some((h) => re.test(h));
2806
2808
  if (wasReplaced) {
@@ -2811,7 +2813,24 @@ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy)
2811
2813
  };
2812
2814
  }
2813
2815
  if (hasContent) return { name: label, disposition: "filled", why: filledWhy };
2814
- return { name: label, disposition: "placeholder", why: `${label} was left as a placeholder; no matching evidence was found.` };
2816
+ return {
2817
+ name: label,
2818
+ disposition: "placeholder",
2819
+ why: missingEvidence ? `${label} was left as a placeholder: ${missingEvidence}` : `${label} was left as a placeholder; no matching evidence was found.`
2820
+ };
2821
+ }
2822
+ function buildWorkingAgreement() {
2823
+ return [
2824
+ "## Working agreement",
2825
+ "",
2826
+ "- Read a file before editing it. Never edit on top of a search result or a remembered version.",
2827
+ "- Verify before saying done: run the command and read the output. A tool reporting success is not evidence.",
2828
+ "- Fix what you break in the same turn. Never delete, skip, or comment out a failing test to go green.",
2829
+ "- Every changed line traces to the request. No unrequested refactors, abstractions, or features.",
2830
+ "- Batch independent tool calls into one turn; go one at a time only when a call needs the previous result.",
2831
+ "- Never guess an API, a flag, or a version. Check the installed package or its docs first.",
2832
+ "- When two sources disagree, or the request has two readings, say so and ask instead of picking silently."
2833
+ ].join("\n");
2815
2834
  }
2816
2835
  function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
2817
2836
  const { currentClaudeMd, project } = input;
@@ -2885,7 +2904,9 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2885
2904
  dispositions.push(regenDisposition("Commands", 0, carried, true, "Filled from the project's manifest commands."));
2886
2905
  } else {
2887
2906
  stats.placeholders += 1;
2888
- dispositions.push(regenDisposition("Commands", 0, carried, false, ""));
2907
+ dispositions.push(
2908
+ regenDisposition("Commands", 0, carried, false, "", "the project manifest declared no runnable scripts.")
2909
+ );
2889
2910
  parts.push(
2890
2911
  [
2891
2912
  "## Commands",
@@ -2918,7 +2939,16 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2918
2939
  dispositions.push(regenDisposition("Project structure", 1, carried, true, "Filled from the project's detected directory layout."));
2919
2940
  } else {
2920
2941
  stats.placeholders += 1;
2921
- dispositions.push(regenDisposition("Project structure", 1, carried, false, ""));
2942
+ dispositions.push(
2943
+ regenDisposition(
2944
+ "Project structure",
2945
+ 1,
2946
+ carried,
2947
+ false,
2948
+ "",
2949
+ "no annotated directories were found, and a bare path tells the agent nothing the file tree does not."
2950
+ )
2951
+ );
2922
2952
  parts.push(
2923
2953
  [
2924
2954
  "## Project structure",
@@ -2943,7 +2973,16 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2943
2973
  dispositions.push(regenDisposition("Code style", 2, carried, true, "Filled from the project's detected style conventions."));
2944
2974
  } else {
2945
2975
  stats.placeholders += 1;
2946
- dispositions.push(regenDisposition("Code style", 2, carried, false, ""));
2976
+ dispositions.push(
2977
+ regenDisposition(
2978
+ "Code style",
2979
+ 2,
2980
+ carried,
2981
+ false,
2982
+ "",
2983
+ "no convention was detected that differs from the language defaults."
2984
+ )
2985
+ );
2947
2986
  parts.push(
2948
2987
  [
2949
2988
  "## Code style",
@@ -2968,7 +3007,9 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2968
3007
  dispositions.push(regenDisposition("Testing", 3, carried, true, "Filled from the project's detected test setup."));
2969
3008
  } else {
2970
3009
  stats.placeholders += 1;
2971
- dispositions.push(regenDisposition("Testing", 3, carried, false, ""));
3010
+ dispositions.push(
3011
+ regenDisposition("Testing", 3, carried, false, "", "no test runner or test directory was detected.")
3012
+ );
2972
3013
  parts.push(
2973
3014
  [
2974
3015
  "## Testing",
@@ -3040,7 +3081,16 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
3040
3081
  dispositions.push(regenDisposition("Environment", 4, carried, true, "Filled from the project's detected environment variable names."));
3041
3082
  } else {
3042
3083
  stats.placeholders += 1;
3043
- dispositions.push(regenDisposition("Environment", 4, carried, false, ""));
3084
+ dispositions.push(
3085
+ regenDisposition(
3086
+ "Environment",
3087
+ 4,
3088
+ carried,
3089
+ false,
3090
+ "",
3091
+ "no environment variable names were detected, so there was nothing to list without inventing it."
3092
+ )
3093
+ );
3044
3094
  parts.push(
3045
3095
  [
3046
3096
  "## Environment",
@@ -3054,6 +3104,24 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
3054
3104
  ].join("\n")
3055
3105
  );
3056
3106
  }
3107
+ const userHasOwnAgreement = carried.other.some((s) => WORKING_AGREEMENT_HEADING.test(s.heading));
3108
+ if (userHasOwnAgreement) {
3109
+ dispositions.push({
3110
+ name: "Working agreement",
3111
+ disposition: "carried",
3112
+ why: "You already have a working-agreement section, so yours was kept and CostClaw's default was left out."
3113
+ });
3114
+ } else {
3115
+ parts.push(buildWorkingAgreement());
3116
+ notes.push(
3117
+ "Added a Working agreement section: seven rules that cut rework. They are CostClaw's, not facts about your project, so delete any line yours contradicts."
3118
+ );
3119
+ dispositions.push({
3120
+ name: "Working agreement",
3121
+ disposition: "filled",
3122
+ why: "CostClaw's default working agreement: rules that cut rework, not facts about your project. Delete any line your project contradicts."
3123
+ });
3124
+ }
3057
3125
  parts.push(
3058
3126
  [
3059
3127
  "<!--",
@@ -3116,14 +3184,40 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
3116
3184
  }
3117
3185
  return clean(parts.join("\n\n").trimEnd() + "\n");
3118
3186
  }
3119
- var INCLUDE_HEADING = [...REGENERATED_HEADING, /^token discipline\b/i];
3120
- function isPlaceholderOnly(body) {
3121
- return /^<!--[^]*?-->$/.test(body.trim());
3187
+ var INCLUDE_HEADING = [
3188
+ ...REGENERATED_HEADING,
3189
+ /^token discipline\b/i,
3190
+ WORKING_AGREEMENT_HEADING
3191
+ ];
3192
+ function stripCommentBlocks(body) {
3193
+ const out = [];
3194
+ let inBlock = false;
3195
+ for (const line of body.split("\n")) {
3196
+ if (inBlock) {
3197
+ if (line.includes("-->")) inBlock = false;
3198
+ continue;
3199
+ }
3200
+ const t = line.trim();
3201
+ if (t.startsWith("<!--")) {
3202
+ if (!t.includes("-->")) inBlock = true;
3203
+ continue;
3204
+ }
3205
+ out.push(line);
3206
+ }
3207
+ return out.join("\n").trim();
3208
+ }
3209
+ function importableBody(body) {
3210
+ const stripped = stripCommentBlocks(body);
3211
+ if (stripped.length === 0 || stripped.includes("<!--")) return null;
3212
+ return stripped;
3122
3213
  }
3123
3214
  function buildIncludeMd(optimizedClaudeMd) {
3124
- const sections = parseSections(optimizedClaudeMd).filter(
3125
- (s) => INCLUDE_HEADING.some((re) => re.test(s.heading)) && !isPlaceholderOnly(s.body)
3215
+ const eligible = parseSections(optimizedClaudeMd).filter(
3216
+ (s) => INCLUDE_HEADING.some((re) => re.test(s.heading))
3126
3217
  );
3218
+ const graded = eligible.map((s) => ({ heading: s.heading, body: importableBody(s.body) }));
3219
+ const sections = graded.filter((s) => s.body !== null);
3220
+ const skipped = graded.filter((s) => s.body === null).map((s) => s.heading);
3127
3221
  const header = [
3128
3222
  "<!--",
3129
3223
  " Generated by CostClaw (https://costclaw.io). Regenerated on every",
@@ -3135,7 +3229,11 @@ function buildIncludeMd(optimizedClaudeMd) {
3135
3229
  const parts = [header, ...sections.map((s) => `## ${s.heading}
3136
3230
 
3137
3231
  ${s.body}`)];
3138
- return { includeMd: clean(parts.join("\n\n").trimEnd() + "\n"), includeSections: sections.map((s) => s.heading) };
3232
+ return {
3233
+ includeMd: clean(parts.join("\n\n").trimEnd() + "\n"),
3234
+ includeSections: sections.map((s) => s.heading),
3235
+ skipped
3236
+ };
3139
3237
  }
3140
3238
  function joinAnd(items) {
3141
3239
  if (items.length === 0) return "";
@@ -3582,7 +3680,11 @@ function optimize(input) {
3582
3680
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
3583
3681
  const settingsJson = buildSettings(input.project);
3584
3682
  const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
3585
- const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
3683
+ const { includeMd, includeSections, skipped: skippedSections } = buildIncludeMd(optimizedClaudeMd);
3684
+ const includeSkipped = skippedSections.map((name) => ({
3685
+ name,
3686
+ why: dispositions.find((d) => d.name === name)?.why ?? `${name} had no content to import.`
3687
+ }));
3586
3688
  const totalByTier = tierCounts(carried.carriedList);
3587
3689
  const droppedByTier = { rule: 0, fact: 0, prose: 0 };
3588
3690
  for (const d of selection.dropped) droppedByTier[d.kind]++;
@@ -3608,6 +3710,7 @@ function optimize(input) {
3608
3710
  harnessPrompt: sanitizeText(harnessPrompt),
3609
3711
  includeMd: sanitizeText(includeMd),
3610
3712
  includeSections,
3713
+ includeSkipped: includeSkipped.map((s) => ({ name: sanitizeText(s.name), why: sanitizeText(clean(s.why)) })),
3611
3714
  notes: cleanNotes.map(sanitizeText),
3612
3715
  placeholdersRemaining: stats.placeholders,
3613
3716
  claudeMdTokens,
@@ -3623,6 +3726,7 @@ function optimize(input) {
3623
3726
  harnessPrompt,
3624
3727
  includeMd,
3625
3728
  includeSections,
3729
+ includeSkipped: includeSkipped.map((s) => ({ name: clean(s.name), why: clean(s.why) })),
3626
3730
  notes: cleanNotes,
3627
3731
  placeholdersRemaining: stats.placeholders,
3628
3732
  claudeMdTokens,
@@ -4359,6 +4463,115 @@ function buildUpgradeAll(input) {
4359
4463
  parts.push(verify.join("\n"));
4360
4464
  return sanitizeText(parts.join("\n\n").trimEnd() + "\n");
4361
4465
  }
4466
+ var GLOBAL_IMPORT_LINE = "@~/.claude/costclaw-global.md";
4467
+ var GLOBAL_INCLUDE_REL = ".claude/costclaw-global.md";
4468
+ function optimizeGlobalClaudeMd(review) {
4469
+ if (review.scope !== "global") {
4470
+ throw new Error(`optimizeGlobalClaudeMd needs a global review, got "${review.scope}"`);
4471
+ }
4472
+ const kept = [];
4473
+ let droppedLines = 0;
4474
+ const droppedByChange = /* @__PURE__ */ new Map();
4475
+ for (const line of review.lines) {
4476
+ if (line.mark === "keep") {
4477
+ kept.push(line.text);
4478
+ continue;
4479
+ }
4480
+ if (line.mark !== "remove" && line.mark !== "move") continue;
4481
+ droppedLines += 1;
4482
+ const id = line.changeId ?? "dropped";
4483
+ const at2 = droppedByChange.get(id);
4484
+ if (at2) at2.push(line.text);
4485
+ else droppedByChange.set(id, [line.text]);
4486
+ }
4487
+ const changeById = new Map(review.changes.map((c) => [c.id, c]));
4488
+ const droppedParts = [];
4489
+ for (const [id, lines] of droppedByChange) {
4490
+ const text2 = lines.join("\n").trim();
4491
+ if (text2.length === 0) continue;
4492
+ const change = changeById.get(id);
4493
+ const where = change?.destination ? `Belongs in: ${change.destination}` : "No destination was suggested.";
4494
+ droppedParts.push(
4495
+ [
4496
+ `## ${change?.heading ?? "Dropped"} (${change?.kind ?? "removed"})`,
4497
+ "",
4498
+ `Why: ${change?.reason ?? "the review marked it for removal"}.`,
4499
+ where,
4500
+ "",
4501
+ text2
4502
+ ].join("\n")
4503
+ );
4504
+ }
4505
+ const droppedMd = droppedParts.length === 0 ? "" : sanitizeText(
4506
+ [
4507
+ "# Taken out of your global CLAUDE.md",
4508
+ "",
4509
+ "`costclaw apply --global --replace` removed these blocks from",
4510
+ "~/.claude/CLAUDE.md. Nothing here is deleted: this file is the copy. Move",
4511
+ "each block to the destination named under it, or paste it back if the",
4512
+ "review was wrong.",
4513
+ ...droppedParts.map((p) => `
4514
+ ${p}`)
4515
+ ].join("\n").trimEnd() + "\n"
4516
+ );
4517
+ const blocks = /* @__PURE__ */ new Map();
4518
+ for (const line of review.lines) {
4519
+ if (line.mark !== "add") continue;
4520
+ const id = line.changeId ?? "add";
4521
+ const at2 = blocks.get(id);
4522
+ if (at2) at2.push(line.text);
4523
+ else blocks.set(id, [line.text]);
4524
+ }
4525
+ const includeSections = [];
4526
+ const bodies = [];
4527
+ for (const lines of blocks.values()) {
4528
+ const text2 = lines.join("\n").trim();
4529
+ if (text2.length === 0) continue;
4530
+ const heading = text2.match(/^##\s+(.+)$/m)?.[1]?.trim();
4531
+ if (!heading) continue;
4532
+ includeSections.push(heading);
4533
+ bodies.push(text2);
4534
+ }
4535
+ const includeMd = bodies.length === 0 ? "" : sanitizeText(
4536
+ [
4537
+ [
4538
+ "<!--",
4539
+ " Generated by CostClaw (https://costclaw.io). Regenerated on every",
4540
+ " `costclaw apply --global`; edit your CLAUDE.md, not this file.",
4541
+ ` Imported from ~/.claude/CLAUDE.md by the line: ${GLOBAL_IMPORT_LINE}`,
4542
+ " These sections come from your own audit, not from a template.",
4543
+ " Undo: costclaw apply --global --remove",
4544
+ "-->"
4545
+ ].join("\n"),
4546
+ ...bodies
4547
+ ].join("\n\n").trimEnd() + "\n"
4548
+ );
4549
+ const body = collapseBlankRuns(kept).join("\n").replace(/\s*$/, "");
4550
+ const optimizedMd = sanitizeText(
4551
+ (bodies.length === 0 ? `${body}
4552
+ ` : `${body}
4553
+
4554
+ ${GLOBAL_IMPORT_LINE}
4555
+ `).replace(/^\n+/, "")
4556
+ );
4557
+ return {
4558
+ optimizedMd,
4559
+ includeMd,
4560
+ includeSections,
4561
+ droppedLines,
4562
+ droppedMd,
4563
+ empty: bodies.length === 0 && droppedLines === 0
4564
+ };
4565
+ }
4566
+ function collapseBlankRuns(lines) {
4567
+ const out = [];
4568
+ for (const line of lines) {
4569
+ const blank = line.trim().length === 0;
4570
+ if (blank && out.length > 0 && out[out.length - 1].trim().length === 0) continue;
4571
+ out.push(line);
4572
+ }
4573
+ return out;
4574
+ }
4362
4575
 
4363
4576
  // src/audit-command.ts
4364
4577
  import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
@@ -4504,15 +4717,36 @@ function projectNameFromLogs(files) {
4504
4717
  }
4505
4718
  return null;
4506
4719
  }
4720
+ async function scanProjectDir(projPath, dirName, out) {
4721
+ const files = await collectJsonl(projPath);
4722
+ const probe = projectNameFromLogs(files);
4723
+ const repoRoot = probe ? repoRootFor(probe.cwd) : null;
4724
+ const resolvedSlug = repoRoot ? basename(repoRoot) : probe?.slug;
4725
+ const projectSlug = resolvedSlug || dirName;
4726
+ if (probe && !out.projectDirs.has(projectSlug)) out.projectDirs.set(projectSlug, repoRoot ?? probe.cwd);
4727
+ for (const full of files) {
4728
+ const rel = relative(projPath, full).split(sep).join("/");
4729
+ const name = `${dirName}/${rel}`;
4730
+ const { kind, parentSessionId } = classify(rel);
4731
+ try {
4732
+ closeSync(openSync(full, "r"));
4733
+ out.logs.push(lazyLog(full, { name, kind, parentSessionId, projectSlug }));
4734
+ } catch {
4735
+ out.skipped.push(name);
4736
+ }
4737
+ }
4738
+ }
4507
4739
  async function readSessions(rootPath) {
4508
- const logs = [];
4509
- const skipped = [];
4510
- const projectDirs = /* @__PURE__ */ new Map();
4740
+ const out = { logs: [], skipped: [], projectDirs: /* @__PURE__ */ new Map() };
4511
4741
  let entries;
4512
4742
  try {
4513
4743
  entries = await readdir(rootPath, { withFileTypes: true });
4514
4744
  } catch {
4515
- return { logs, skipped, projectDirs };
4745
+ return out;
4746
+ }
4747
+ if (entries.some((e) => e.isFile() && e.name.endsWith(".jsonl"))) {
4748
+ await scanProjectDir(rootPath, basename(rootPath), out);
4749
+ return out;
4516
4750
  }
4517
4751
  for (const dir of entries) {
4518
4752
  if (!dir.isDirectory()) continue;
@@ -4520,28 +4754,12 @@ async function readSessions(rootPath) {
4520
4754
  try {
4521
4755
  await readdir(projPath);
4522
4756
  } catch {
4523
- skipped.push(dir.name);
4757
+ out.skipped.push(dir.name);
4524
4758
  continue;
4525
4759
  }
4526
- const files = await collectJsonl(projPath);
4527
- const probe = projectNameFromLogs(files);
4528
- const repoRoot = probe ? repoRootFor(probe.cwd) : null;
4529
- const resolvedSlug = repoRoot ? basename(repoRoot) : probe?.slug;
4530
- const projectSlug = resolvedSlug || dir.name;
4531
- if (probe && !projectDirs.has(projectSlug)) projectDirs.set(projectSlug, repoRoot ?? probe.cwd);
4532
- for (const full of files) {
4533
- const rel = relative(projPath, full).split(sep).join("/");
4534
- const name = `${dir.name}/${rel}`;
4535
- const { kind, parentSessionId } = classify(rel);
4536
- try {
4537
- closeSync(openSync(full, "r"));
4538
- logs.push(lazyLog(full, { name, kind, parentSessionId, projectSlug }));
4539
- } catch {
4540
- skipped.push(name);
4541
- }
4542
- }
4760
+ await scanProjectDir(projPath, dir.name, out);
4543
4761
  }
4544
- return { logs, skipped, projectDirs };
4762
+ return out;
4545
4763
  }
4546
4764
 
4547
4765
  // src/ansi.ts
@@ -5711,7 +5929,7 @@ async function runAudit(opts) {
5711
5929
  // src/optimize-command.ts
5712
5930
  import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
5713
5931
  import { basename as basename3, join as join10, resolve as resolve6 } from "path";
5714
- import { homedir as homedir5 } from "os";
5932
+ import { homedir as homedir6 } from "os";
5715
5933
 
5716
5934
  // src/claude-md-imports.ts
5717
5935
  import { readFile as readFile5 } from "fs/promises";
@@ -5742,12 +5960,18 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
5742
5960
  // src/apply-command.ts
5743
5961
  import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
5744
5962
  import { join as join7, dirname as dirname3 } from "path";
5963
+ import { homedir as homedir5 } from "os";
5745
5964
  var IMPORT_LINE2 = "@.claude/costclaw.md";
5746
5965
  var INCLUDE_REL = ".claude/costclaw.md";
5747
5966
  var APPLY_DIR_REL = ".claude/costclaw";
5748
5967
  var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
5749
5968
  var INCLUDE_ARTIFACT = "costclaw.md";
5969
+ var INCLUDE_SECTIONS_ARTIFACT = "costclaw.sections.json";
5750
5970
  var OPTIMIZED_ARTIFACT = "CLAUDE.optimized.md";
5971
+ var GLOBAL_INCLUDE_ARTIFACT = "costclaw-global.md";
5972
+ var GLOBAL_OPTIMIZED_ARTIFACT = "CLAUDE.global.optimized.md";
5973
+ var GLOBAL_DROPPED_ARTIFACT = "costclaw-global.removed.md";
5974
+ var GLOBAL_DROPPED_REL = ".claude/costclaw-global.removed.md";
5751
5975
  async function pathExists(p) {
5752
5976
  try {
5753
5977
  await stat(p);
@@ -5756,21 +5980,49 @@ async function pathExists(p) {
5756
5980
  return false;
5757
5981
  }
5758
5982
  }
5759
- function ensureImportLine(claudeMd) {
5760
- if (claudeMd === null) return { text: `${IMPORT_LINE2}
5983
+ async function readIncludeSections(artifactsDir) {
5984
+ const path = join7(artifactsDir, INCLUDE_SECTIONS_ARTIFACT);
5985
+ if (!await pathExists(path)) return null;
5986
+ let parsed;
5987
+ try {
5988
+ parsed = JSON.parse(await readFile6(path, "utf8"));
5989
+ } catch {
5990
+ return null;
5991
+ }
5992
+ if (typeof parsed !== "object" || parsed === null) return null;
5993
+ const raw = parsed;
5994
+ return {
5995
+ included: Array.isArray(raw.included) ? raw.included.filter((v) => typeof v === "string") : [],
5996
+ skipped: Array.isArray(raw.skipped) ? raw.skipped.filter(
5997
+ (v) => typeof v === "object" && v !== null && typeof v.name === "string" && typeof v.why === "string"
5998
+ ) : []
5999
+ };
6000
+ }
6001
+ function describeIncludeSections(report) {
6002
+ if (report === null) return [];
6003
+ const lines = report.included.length > 0 ? [`It carries ${report.included.length} section${report.included.length === 1 ? "" : "s"}: ${report.included.join(", ")}.`] : ["It carries no sections: the scan found nothing importable in this project."];
6004
+ for (const s of report.skipped) {
6005
+ lines.push(` Left out ${s.name}: ${s.why.replace(/^.*?placeholder:\s*/, "")}`);
6006
+ }
6007
+ if (report.skipped.length > 0) {
6008
+ lines.push(" Those are limits of what a scan can detect, not errors. Add them to your own CLAUDE.md.");
6009
+ }
6010
+ return lines;
6011
+ }
6012
+ function ensureLine(claudeMd, line) {
6013
+ if (claudeMd === null) return { text: `${line}
5761
6014
  `, added: true };
5762
- const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE2);
5763
- if (has) return { text: claudeMd, added: false };
6015
+ if (claudeMd.split(/\r?\n/).some((l) => l.trim() === line)) return { text: claudeMd, added: false };
5764
6016
  const base = claudeMd.replace(/\s*$/, "");
5765
- return { text: base.length === 0 ? `${IMPORT_LINE2}
6017
+ return { text: base.length === 0 ? `${line}
5766
6018
  ` : `${base}
5767
6019
 
5768
- ${IMPORT_LINE2}
6020
+ ${line}
5769
6021
  `, added: true };
5770
6022
  }
5771
- function stripImportLine(claudeMd) {
6023
+ function stripLine(claudeMd, line) {
5772
6024
  const lines = claudeMd.split(/\r?\n/);
5773
- const i = lines.findIndex((l) => l.trim() === IMPORT_LINE2);
6025
+ const i = lines.findIndex((l) => l.trim() === line);
5774
6026
  if (i < 0) return { text: claudeMd, removed: false };
5775
6027
  lines.splice(i, 1);
5776
6028
  if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
@@ -5778,6 +6030,12 @@ function stripImportLine(claudeMd) {
5778
6030
  if (!text2.endsWith("\n")) text2 += "\n";
5779
6031
  return { text: text2 === "\n" ? "" : text2, removed: true };
5780
6032
  }
6033
+ function ensureImportLine(claudeMd) {
6034
+ return ensureLine(claudeMd, IMPORT_LINE2);
6035
+ }
6036
+ function stripImportLine(claudeMd) {
6037
+ return stripLine(claudeMd, IMPORT_LINE2);
6038
+ }
5781
6039
  async function runInclude(opts) {
5782
6040
  const { projectDir, artifactsDir } = opts;
5783
6041
  const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
@@ -5790,7 +6048,7 @@ async function runInclude(opts) {
5790
6048
  const includeDest = join7(projectDir, INCLUDE_REL);
5791
6049
  await writeFile4(includeDest, includeMd, "utf8");
5792
6050
  const wrote = [includeDest];
5793
- const lines = [`Wrote ${INCLUDE_REL}`];
6051
+ const lines = [`Wrote ${INCLUDE_REL}`, ...describeIncludeSections(await readIncludeSections(artifactsDir))];
5794
6052
  const claudeMdPath = join7(projectDir, "CLAUDE.md");
5795
6053
  const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
5796
6054
  const { text: text2, added } = ensureImportLine(existing);
@@ -5889,10 +6147,95 @@ async function runReplace(opts) {
5889
6147
  return { lines, wrote: [claudeMdPath, backup], removed: [] };
5890
6148
  }
5891
6149
  async function runApply(opts) {
6150
+ if (opts.global) return runGlobal(opts);
5892
6151
  if (opts.mode === "replace") return runReplace(opts);
5893
6152
  if (opts.mode === "remove") return runRemove(opts);
5894
6153
  return runInclude(opts);
5895
6154
  }
6155
+ async function runGlobal(opts) {
6156
+ const home = opts.home ?? homedir5();
6157
+ const claudeMdPath = join7(home, ".claude", "CLAUDE.md");
6158
+ const includeDest = join7(home, GLOBAL_INCLUDE_REL);
6159
+ if (opts.mode === "remove") {
6160
+ const removed = [];
6161
+ const lines2 = [];
6162
+ if (await pathExists(includeDest)) {
6163
+ await rm3(includeDest, { force: true });
6164
+ removed.push(includeDest);
6165
+ lines2.push(`Removed ${GLOBAL_INCLUDE_REL}`);
6166
+ }
6167
+ if (await pathExists(claudeMdPath)) {
6168
+ const { text: text2, removed: didRemove } = stripLine(await readFile6(claudeMdPath, "utf8"), GLOBAL_IMPORT_LINE);
6169
+ if (didRemove) {
6170
+ await writeFile4(claudeMdPath, text2, "utf8");
6171
+ lines2.push(`Removed "${GLOBAL_IMPORT_LINE}" from ${claudeMdPath}`);
6172
+ }
6173
+ }
6174
+ if (lines2.length === 0) lines2.push("Nothing to remove: the global include was not applied.");
6175
+ return { lines: lines2, wrote: [], removed };
6176
+ }
6177
+ const includeSrc = join7(opts.artifactsDir, GLOBAL_INCLUDE_ARTIFACT);
6178
+ const optimizedSrc = join7(opts.artifactsDir, GLOBAL_OPTIMIZED_ARTIFACT);
6179
+ const hasInclude = await pathExists(includeSrc);
6180
+ if (!hasInclude && !await pathExists(optimizedSrc)) {
6181
+ throw new Error(
6182
+ `No global artifacts in ${opts.artifactsDir}; run costclaw optimize first (it writes ${GLOBAL_OPTIMIZED_ARTIFACT}).`
6183
+ );
6184
+ }
6185
+ const original = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
6186
+ const backup = `${claudeMdPath}.bak`;
6187
+ if (original !== null) {
6188
+ if (await pathExists(backup) && !opts.force) {
6189
+ throw new Error(
6190
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
6191
+ );
6192
+ }
6193
+ await writeFile4(backup, original, "utf8");
6194
+ }
6195
+ const wrote = [];
6196
+ const lines = [];
6197
+ await mkdir4(dirname3(claudeMdPath), { recursive: true });
6198
+ if (hasInclude) {
6199
+ await writeFile4(includeDest, await readFile6(includeSrc, "utf8"), "utf8");
6200
+ wrote.push(includeDest);
6201
+ lines.push(`Wrote ${GLOBAL_INCLUDE_REL}`);
6202
+ } else {
6203
+ lines.push("Your audit produced no global sections to add, so no include file was written.");
6204
+ }
6205
+ if (opts.mode === "replace") {
6206
+ const optimized = await readFile6(optimizedSrc, "utf8");
6207
+ const droppedSrc = join7(opts.artifactsDir, GLOBAL_DROPPED_ARTIFACT);
6208
+ if (await pathExists(droppedSrc)) {
6209
+ const droppedDest = join7(home, GLOBAL_DROPPED_REL);
6210
+ await writeFile4(droppedDest, await readFile6(droppedSrc, "utf8"), "utf8");
6211
+ wrote.push(droppedDest);
6212
+ lines.push(`Saved every dropped block, verbatim and with its destination, to ${GLOBAL_DROPPED_REL}`);
6213
+ }
6214
+ await writeFile4(claudeMdPath, optimized, "utf8");
6215
+ wrote.push(claudeMdPath);
6216
+ lines.push(
6217
+ `Rewrote ${claudeMdPath} with every reviewed removal applied`,
6218
+ "",
6219
+ "Diff (old vs new):",
6220
+ lineDiff(original ?? "", optimized)
6221
+ );
6222
+ } else if (hasInclude) {
6223
+ const { text: text2, added } = ensureLine(original, GLOBAL_IMPORT_LINE);
6224
+ if (added) {
6225
+ await writeFile4(claudeMdPath, text2, "utf8");
6226
+ wrote.push(claudeMdPath);
6227
+ lines.push(`Added "${GLOBAL_IMPORT_LINE}" to ${claudeMdPath}`);
6228
+ } else {
6229
+ lines.push("Your global CLAUDE.md already imports it");
6230
+ }
6231
+ lines.push(
6232
+ "Every line you wrote is untouched. To also drop the sections the review marked remove, rerun with --replace."
6233
+ );
6234
+ }
6235
+ if (original !== null) lines.push(`Backed up the original to ${backup}`);
6236
+ lines.push("Undo: costclaw apply --global --remove");
6237
+ return { lines, wrote, removed: [] };
6238
+ }
5896
6239
  function lineDiff(oldText, newText) {
5897
6240
  const oldLines = oldText.split(/\r?\n/);
5898
6241
  const newLines = newText.split(/\r?\n/);
@@ -7553,6 +7896,10 @@ var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
7553
7896
  var DASHBOARD_NAME2 = "DASHBOARD.html";
7554
7897
  var UPGRADE_ALL_NAME = "UPGRADE-ALL.md";
7555
7898
  var INCLUDE_NAME2 = "costclaw.md";
7899
+ var INCLUDE_SECTIONS_NAME = "costclaw.sections.json";
7900
+ var GLOBAL_OPTIMIZED_NAME = "CLAUDE.global.optimized.md";
7901
+ var GLOBAL_DROPPED_NAME = "costclaw-global.removed.md";
7902
+ var GLOBAL_INCLUDE_NAME = "costclaw-global.md";
7556
7903
  var DEFAULT_LIMIT = 10;
7557
7904
  function usd6(n) {
7558
7905
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
@@ -7618,6 +7965,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7618
7965
  await writeFile6(join10(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
7619
7966
  await writeFile6(join10(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
7620
7967
  await writeFile6(join10(artifactsDir, INCLUDE_NAME2), result.includeMd, "utf8");
7968
+ await writeFile6(
7969
+ join10(artifactsDir, INCLUDE_SECTIONS_NAME),
7970
+ JSON.stringify({ included: result.includeSections, skipped: result.includeSkipped }, null, 2) + "\n",
7971
+ "utf8"
7972
+ );
7621
7973
  const review = reviewProjectClaudeMd({
7622
7974
  text: currentClaudeMd ?? null,
7623
7975
  report: ctx.report,
@@ -7691,6 +8043,10 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7691
8043
  `${n} section${n === 1 ? "" : "s"} left as placeholder${n === 1 ? "" : "s"} (no evidence to fill ${n === 1 ? "it" : "them"}); search the scaffold for <!-- ... -->.`
7692
8044
  );
7693
8045
  }
8046
+ lines.push(
8047
+ result.includeSections.length > 0 ? `costclaw.md will carry ${num6(result.includeSections.length)} section${result.includeSections.length === 1 ? "" : "s"}: ${result.includeSections.join(", ")}.` : "costclaw.md will carry no sections: the scan found nothing importable."
8048
+ );
8049
+ for (const s of result.includeSkipped) lines.push(` - Left out ${s.name}: ${s.why.replace(/^.*?placeholder:\s*/, "")}`);
7694
8050
  for (const note of result.notes) lines.push(` - ${note}`);
7695
8051
  if (review.changes.length > 0) {
7696
8052
  const n = review.changes.length;
@@ -7719,7 +8075,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7719
8075
  };
7720
8076
  }
7721
8077
  async function runOptimize(opts) {
7722
- const home = opts.home ?? homedir5();
8078
+ const home = opts.home ?? homedir6();
7723
8079
  let inputsClaudeMdPath = opts.claudeMdPath;
7724
8080
  if (!inputsClaudeMdPath && opts.projectDir) {
7725
8081
  const own2 = join10(opts.projectDir, "CLAUDE.md");
@@ -7856,6 +8212,37 @@ async function runOptimize(opts) {
7856
8212
  const upgradeAllPath = join10(upgradeRoot, UPGRADE_ALL_NAME);
7857
8213
  await mkdir6(upgradeRoot, { recursive: true });
7858
8214
  await writeFile6(upgradeAllPath, upgradeAll, "utf8");
8215
+ const homeClaudeMd = join10(home, ".claude", "CLAUDE.md");
8216
+ const reviewedTheGlobalFile = globalPath !== null && resolve6(globalPath) === resolve6(homeClaudeMd);
8217
+ const globalOptimized = reviewedTheGlobalFile ? optimizeGlobalClaudeMd(globalReview) : null;
8218
+ if (globalOptimized) {
8219
+ await writeFile6(join10(upgradeRoot, GLOBAL_OPTIMIZED_NAME), globalOptimized.optimizedMd, "utf8");
8220
+ if (globalOptimized.includeMd.length > 0) {
8221
+ await writeFile6(join10(upgradeRoot, GLOBAL_INCLUDE_NAME), globalOptimized.includeMd, "utf8");
8222
+ }
8223
+ if (globalOptimized.droppedMd.length > 0) {
8224
+ await writeFile6(join10(upgradeRoot, GLOBAL_DROPPED_NAME), globalOptimized.droppedMd, "utf8");
8225
+ }
8226
+ }
8227
+ if (!globalOptimized) {
8228
+ lines.push(
8229
+ `Reviewed ${globalLabel} as this run's scored file. Run costclaw optimize with no --project or --claude-md to generate for ~/.claude/CLAUDE.md.`
8230
+ );
8231
+ } else if (globalOptimized.empty) {
8232
+ lines.push(`Your global CLAUDE.md (${globalLabel}) needs no changes this run.`);
8233
+ } else {
8234
+ const parts = [];
8235
+ if (globalOptimized.includeSections.length > 0) {
8236
+ parts.push(`adds ${globalOptimized.includeSections.join(", ")} from your audit`);
8237
+ }
8238
+ if (globalOptimized.droppedLines > 0) {
8239
+ parts.push(`drops ${globalOptimized.droppedLines} reviewed line${globalOptimized.droppedLines === 1 ? "" : "s"}`);
8240
+ }
8241
+ lines.push(
8242
+ `Your global CLAUDE.md (${globalLabel}): ${parts.join(", ")}.`,
8243
+ `Apply it with: costclaw apply --global. It writes ~/${GLOBAL_INCLUDE_REL.replace(/\\/g, "/")} and one import line, and backs up the original.`
8244
+ );
8245
+ }
7859
8246
  let indexHtmlPath = null;
7860
8247
  if (!single && ctx.dashboard) {
7861
8248
  const rows = merged.map((e) => ({
@@ -7980,7 +8367,7 @@ async function runBadge(opts) {
7980
8367
  // src/diff-command.ts
7981
8368
  import { readdir as readdir4, readFile as readFile11 } from "fs/promises";
7982
8369
  import { join as join11 } from "path";
7983
- import { homedir as homedir6 } from "os";
8370
+ import { homedir as homedir7 } from "os";
7984
8371
 
7985
8372
  // src/format-diff.ts
7986
8373
  function usd7(n) {
@@ -8094,7 +8481,7 @@ async function runDiff(opts) {
8094
8481
  let pathA = opts.fileA;
8095
8482
  let pathB = opts.fileB;
8096
8483
  if (!pathA || !pathB) {
8097
- const dir = join11(opts.home ?? homedir6(), ".costclaw", "history");
8484
+ const dir = join11(opts.home ?? homedir7(), ".costclaw", "history");
8098
8485
  let files = [];
8099
8486
  try {
8100
8487
  files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
@@ -8172,11 +8559,12 @@ function parseApplyFlags(args) {
8172
8559
  from,
8173
8560
  applySettings,
8174
8561
  applySettingsPath,
8175
- force: args.includes("--force")
8562
+ force: args.includes("--force"),
8563
+ global: args.includes("--global")
8176
8564
  };
8177
8565
  }
8178
8566
  function cliVersion() {
8179
- return true ? "0.13.2" : "0.0.0-dev";
8567
+ return true ? "0.15.0" : "0.0.0-dev";
8180
8568
  }
8181
8569
  function isHelpRequest(command, args) {
8182
8570
  if (command === void 0) return false;
@@ -8193,6 +8581,7 @@ function helpText() {
8193
8581
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
8194
8582
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
8195
8583
  " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
8584
+ " costclaw apply --global [--replace] [--remove] [--from <dir>] [--force]",
8196
8585
  " costclaw activate <license-key> [--name <machine-name>]",
8197
8586
  " costclaw deactivate",
8198
8587
  " costclaw --version",
@@ -8200,6 +8589,8 @@ function helpText() {
8200
8589
  "",
8201
8590
  "audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
8202
8591
  "machine and prints a cost report plus a six-pillar setup score. It is free.",
8592
+ "To audit one project rather than all of them, point --path at that project's",
8593
+ "own directory under ~/.claude/projects (the one named after its path).",
8203
8594
  "By default it also writes a self-contained HTML report (costclaw-report.html)",
8204
8595
  "and opens it in your browser; --no-html skips that, --html <file> picks the",
8205
8596
  "path, and --json runs stay file-free unless --html is passed explicitly.",
@@ -8252,6 +8643,13 @@ function helpText() {
8252
8643
  "optimize run, or generates them cold if none exist yet. --force allows",
8253
8644
  "overwriting an existing .bak backup for --replace and --apply-settings.",
8254
8645
  "",
8646
+ "apply --global does the same for ~/.claude/CLAUDE.md, the one file loaded on",
8647
+ "every turn of every project. It writes the sections your audit earned to",
8648
+ "~/.claude/costclaw-global.md, adds one @~/.claude/costclaw-global.md import",
8649
+ "line, and backs the original up first. --replace additionally writes the",
8650
+ "rewritten file, dropping what the review marked remove or move; there is no",
8651
+ "git repo in ~/.claude, so the .bak is the undo. --remove takes both back out.",
8652
+ "",
8255
8653
  "optimize and apply need a one-time license: buy at https://costclaw.io, then",
8256
8654
  "run costclaw activate <key>. activate and deactivate move that license",
8257
8655
  "between machines. audit never needs a license.",
@@ -8347,7 +8745,29 @@ Run: costclaw optimize
8347
8745
  process.exit(1);
8348
8746
  }
8349
8747
  const flags = parseApplyFlags(args);
8350
- const root = defaultOptimizeRoot(homedir7());
8748
+ const root = defaultOptimizeRoot(homedir8());
8749
+ if (flags.global) {
8750
+ const manifest = await readManifest(root);
8751
+ const candidates = [
8752
+ ...flags.from ? [flags.from] : [],
8753
+ root,
8754
+ ...(manifest?.projects ?? []).map((e) => e.artifactsDir)
8755
+ ];
8756
+ let globalDir = candidates.find((dir) => existsSync(join12(dir, "CLAUDE.global.optimized.md")));
8757
+ if (!globalDir) {
8758
+ const run = await runOptimize({ serve: false, dashboard: false, version: cliVersion() });
8759
+ globalDir = run.upgradeAllPath ? dirname4(run.upgradeAllPath) : run.root;
8760
+ }
8761
+ const outcome2 = await runApply({
8762
+ projectDir: flags.projectDir,
8763
+ mode: flags.mode,
8764
+ artifactsDir: globalDir,
8765
+ global: true,
8766
+ force: flags.force
8767
+ });
8768
+ process.stdout.write(outcome2.lines.join("\n") + "\n");
8769
+ return;
8770
+ }
8351
8771
  let artifactsDir = flags.from;
8352
8772
  if (!artifactsDir) {
8353
8773
  const manifest = await readManifest(root);
package/package.json CHANGED
@@ -1,47 +1,47 @@
1
- {
2
- "name": "costclaw",
3
- "version": "0.13.2",
4
- "description": "Local Claude Code usage estimates, cache analysis, and rule-based setup checks. Your prompts stay on your machine.",
5
- "type": "module",
6
- "bin": {
7
- "costclaw": "dist/index.js"
8
- },
9
- "files": [
10
- "dist"
11
- ],
12
- "engines": {
13
- "node": ">=20"
14
- },
15
- "license": "UNLICENSED",
16
- "homepage": "https://www.costclaw.io",
17
- "keywords": [
18
- "claude-code",
19
- "claude",
20
- "anthropic",
21
- "cost",
22
- "finops",
23
- "audit",
24
- "tokens",
25
- "cli"
26
- ],
27
- "scripts": {
28
- "audit": "tsx src/index.ts audit",
29
- "diff": "tsx src/index.ts diff",
30
- "optimize": "tsx src/index.ts optimize",
31
- "dev": "tsx src/index.ts",
32
- "build": "npm run check:privacy && tsup",
33
- "test": "npm run check:no-network && vitest run",
34
- "typecheck": "tsc --noEmit",
35
- "check:no-network": "node ../../scripts/check-no-network.mjs --self-test && node ../../scripts/check-no-network.mjs",
36
- "check:privacy": "npm --prefix ../../packages/engine run test -- tests/audit.test.ts",
37
- "prepublishOnly": "npm --prefix ../.. test && npm --prefix ../.. run typecheck && npm run build"
38
- },
39
- "devDependencies": {
40
- "@costclaw/engine": "*",
41
- "@types/node": "^22.10.0",
42
- "tsup": "^8.3.5",
43
- "tsx": "^4.19.0",
44
- "typescript": "^5.7.0",
45
- "vitest": "^2.1.8"
46
- }
47
- }
1
+ {
2
+ "name": "costclaw",
3
+ "version": "0.15.0",
4
+ "description": "Local Claude Code usage estimates, cache analysis, and rule-based setup checks. Your prompts stay on your machine.",
5
+ "type": "module",
6
+ "bin": {
7
+ "costclaw": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "license": "UNLICENSED",
16
+ "homepage": "https://www.costclaw.io",
17
+ "keywords": [
18
+ "claude-code",
19
+ "claude",
20
+ "anthropic",
21
+ "cost",
22
+ "finops",
23
+ "audit",
24
+ "tokens",
25
+ "cli"
26
+ ],
27
+ "scripts": {
28
+ "audit": "tsx src/index.ts audit",
29
+ "diff": "tsx src/index.ts diff",
30
+ "optimize": "tsx src/index.ts optimize",
31
+ "dev": "tsx src/index.ts",
32
+ "build": "npm run check:privacy && tsup",
33
+ "test": "npm run check:no-network && vitest run",
34
+ "typecheck": "tsc --noEmit",
35
+ "check:no-network": "node ../../scripts/check-no-network.mjs --self-test && node ../../scripts/check-no-network.mjs",
36
+ "check:privacy": "npm --prefix ../../packages/engine run test -- tests/audit.test.ts",
37
+ "prepublishOnly": "npm --prefix ../.. test && npm --prefix ../.. run typecheck && npm run build"
38
+ },
39
+ "devDependencies": {
40
+ "@costclaw/engine": "*",
41
+ "@types/node": "^22.10.0",
42
+ "tsup": "^8.3.5",
43
+ "tsx": "^4.19.0",
44
+ "typescript": "^5.7.0",
45
+ "vitest": "^2.1.8"
46
+ }
47
+ }