costclaw 0.13.3 → 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 (2) hide show
  1. package/dist/index.js +445 -32
  2. package/package.json +47 -47
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";
@@ -5716,7 +5929,7 @@ async function runAudit(opts) {
5716
5929
  // src/optimize-command.ts
5717
5930
  import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
5718
5931
  import { basename as basename3, join as join10, resolve as resolve6 } from "path";
5719
- import { homedir as homedir5 } from "os";
5932
+ import { homedir as homedir6 } from "os";
5720
5933
 
5721
5934
  // src/claude-md-imports.ts
5722
5935
  import { readFile as readFile5 } from "fs/promises";
@@ -5747,12 +5960,18 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
5747
5960
  // src/apply-command.ts
5748
5961
  import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
5749
5962
  import { join as join7, dirname as dirname3 } from "path";
5963
+ import { homedir as homedir5 } from "os";
5750
5964
  var IMPORT_LINE2 = "@.claude/costclaw.md";
5751
5965
  var INCLUDE_REL = ".claude/costclaw.md";
5752
5966
  var APPLY_DIR_REL = ".claude/costclaw";
5753
5967
  var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
5754
5968
  var INCLUDE_ARTIFACT = "costclaw.md";
5969
+ var INCLUDE_SECTIONS_ARTIFACT = "costclaw.sections.json";
5755
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";
5756
5975
  async function pathExists(p) {
5757
5976
  try {
5758
5977
  await stat(p);
@@ -5761,21 +5980,49 @@ async function pathExists(p) {
5761
5980
  return false;
5762
5981
  }
5763
5982
  }
5764
- function ensureImportLine(claudeMd) {
5765
- 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}
5766
6014
  `, added: true };
5767
- const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE2);
5768
- if (has) return { text: claudeMd, added: false };
6015
+ if (claudeMd.split(/\r?\n/).some((l) => l.trim() === line)) return { text: claudeMd, added: false };
5769
6016
  const base = claudeMd.replace(/\s*$/, "");
5770
- return { text: base.length === 0 ? `${IMPORT_LINE2}
6017
+ return { text: base.length === 0 ? `${line}
5771
6018
  ` : `${base}
5772
6019
 
5773
- ${IMPORT_LINE2}
6020
+ ${line}
5774
6021
  `, added: true };
5775
6022
  }
5776
- function stripImportLine(claudeMd) {
6023
+ function stripLine(claudeMd, line) {
5777
6024
  const lines = claudeMd.split(/\r?\n/);
5778
- const i = lines.findIndex((l) => l.trim() === IMPORT_LINE2);
6025
+ const i = lines.findIndex((l) => l.trim() === line);
5779
6026
  if (i < 0) return { text: claudeMd, removed: false };
5780
6027
  lines.splice(i, 1);
5781
6028
  if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
@@ -5783,6 +6030,12 @@ function stripImportLine(claudeMd) {
5783
6030
  if (!text2.endsWith("\n")) text2 += "\n";
5784
6031
  return { text: text2 === "\n" ? "" : text2, removed: true };
5785
6032
  }
6033
+ function ensureImportLine(claudeMd) {
6034
+ return ensureLine(claudeMd, IMPORT_LINE2);
6035
+ }
6036
+ function stripImportLine(claudeMd) {
6037
+ return stripLine(claudeMd, IMPORT_LINE2);
6038
+ }
5786
6039
  async function runInclude(opts) {
5787
6040
  const { projectDir, artifactsDir } = opts;
5788
6041
  const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
@@ -5795,7 +6048,7 @@ async function runInclude(opts) {
5795
6048
  const includeDest = join7(projectDir, INCLUDE_REL);
5796
6049
  await writeFile4(includeDest, includeMd, "utf8");
5797
6050
  const wrote = [includeDest];
5798
- const lines = [`Wrote ${INCLUDE_REL}`];
6051
+ const lines = [`Wrote ${INCLUDE_REL}`, ...describeIncludeSections(await readIncludeSections(artifactsDir))];
5799
6052
  const claudeMdPath = join7(projectDir, "CLAUDE.md");
5800
6053
  const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
5801
6054
  const { text: text2, added } = ensureImportLine(existing);
@@ -5894,10 +6147,95 @@ async function runReplace(opts) {
5894
6147
  return { lines, wrote: [claudeMdPath, backup], removed: [] };
5895
6148
  }
5896
6149
  async function runApply(opts) {
6150
+ if (opts.global) return runGlobal(opts);
5897
6151
  if (opts.mode === "replace") return runReplace(opts);
5898
6152
  if (opts.mode === "remove") return runRemove(opts);
5899
6153
  return runInclude(opts);
5900
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
+ }
5901
6239
  function lineDiff(oldText, newText) {
5902
6240
  const oldLines = oldText.split(/\r?\n/);
5903
6241
  const newLines = newText.split(/\r?\n/);
@@ -7558,6 +7896,10 @@ var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
7558
7896
  var DASHBOARD_NAME2 = "DASHBOARD.html";
7559
7897
  var UPGRADE_ALL_NAME = "UPGRADE-ALL.md";
7560
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";
7561
7903
  var DEFAULT_LIMIT = 10;
7562
7904
  function usd6(n) {
7563
7905
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
@@ -7623,6 +7965,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7623
7965
  await writeFile6(join10(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
7624
7966
  await writeFile6(join10(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
7625
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
+ );
7626
7973
  const review = reviewProjectClaudeMd({
7627
7974
  text: currentClaudeMd ?? null,
7628
7975
  report: ctx.report,
@@ -7696,6 +8043,10 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7696
8043
  `${n} section${n === 1 ? "" : "s"} left as placeholder${n === 1 ? "" : "s"} (no evidence to fill ${n === 1 ? "it" : "them"}); search the scaffold for <!-- ... -->.`
7697
8044
  );
7698
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*/, "")}`);
7699
8050
  for (const note of result.notes) lines.push(` - ${note}`);
7700
8051
  if (review.changes.length > 0) {
7701
8052
  const n = review.changes.length;
@@ -7724,7 +8075,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7724
8075
  };
7725
8076
  }
7726
8077
  async function runOptimize(opts) {
7727
- const home = opts.home ?? homedir5();
8078
+ const home = opts.home ?? homedir6();
7728
8079
  let inputsClaudeMdPath = opts.claudeMdPath;
7729
8080
  if (!inputsClaudeMdPath && opts.projectDir) {
7730
8081
  const own2 = join10(opts.projectDir, "CLAUDE.md");
@@ -7861,6 +8212,37 @@ async function runOptimize(opts) {
7861
8212
  const upgradeAllPath = join10(upgradeRoot, UPGRADE_ALL_NAME);
7862
8213
  await mkdir6(upgradeRoot, { recursive: true });
7863
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
+ }
7864
8246
  let indexHtmlPath = null;
7865
8247
  if (!single && ctx.dashboard) {
7866
8248
  const rows = merged.map((e) => ({
@@ -7985,7 +8367,7 @@ async function runBadge(opts) {
7985
8367
  // src/diff-command.ts
7986
8368
  import { readdir as readdir4, readFile as readFile11 } from "fs/promises";
7987
8369
  import { join as join11 } from "path";
7988
- import { homedir as homedir6 } from "os";
8370
+ import { homedir as homedir7 } from "os";
7989
8371
 
7990
8372
  // src/format-diff.ts
7991
8373
  function usd7(n) {
@@ -8099,7 +8481,7 @@ async function runDiff(opts) {
8099
8481
  let pathA = opts.fileA;
8100
8482
  let pathB = opts.fileB;
8101
8483
  if (!pathA || !pathB) {
8102
- const dir = join11(opts.home ?? homedir6(), ".costclaw", "history");
8484
+ const dir = join11(opts.home ?? homedir7(), ".costclaw", "history");
8103
8485
  let files = [];
8104
8486
  try {
8105
8487
  files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
@@ -8177,11 +8559,12 @@ function parseApplyFlags(args) {
8177
8559
  from,
8178
8560
  applySettings,
8179
8561
  applySettingsPath,
8180
- force: args.includes("--force")
8562
+ force: args.includes("--force"),
8563
+ global: args.includes("--global")
8181
8564
  };
8182
8565
  }
8183
8566
  function cliVersion() {
8184
- return true ? "0.13.3" : "0.0.0-dev";
8567
+ return true ? "0.15.0" : "0.0.0-dev";
8185
8568
  }
8186
8569
  function isHelpRequest(command, args) {
8187
8570
  if (command === void 0) return false;
@@ -8198,6 +8581,7 @@ function helpText() {
8198
8581
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
8199
8582
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
8200
8583
  " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
8584
+ " costclaw apply --global [--replace] [--remove] [--from <dir>] [--force]",
8201
8585
  " costclaw activate <license-key> [--name <machine-name>]",
8202
8586
  " costclaw deactivate",
8203
8587
  " costclaw --version",
@@ -8259,6 +8643,13 @@ function helpText() {
8259
8643
  "optimize run, or generates them cold if none exist yet. --force allows",
8260
8644
  "overwriting an existing .bak backup for --replace and --apply-settings.",
8261
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
+ "",
8262
8653
  "optimize and apply need a one-time license: buy at https://costclaw.io, then",
8263
8654
  "run costclaw activate <key>. activate and deactivate move that license",
8264
8655
  "between machines. audit never needs a license.",
@@ -8354,7 +8745,29 @@ Run: costclaw optimize
8354
8745
  process.exit(1);
8355
8746
  }
8356
8747
  const flags = parseApplyFlags(args);
8357
- 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
+ }
8358
8771
  let artifactsDir = flags.from;
8359
8772
  if (!artifactsDir) {
8360
8773
  const manifest = await readManifest(root);
package/package.json CHANGED
@@ -1,47 +1,47 @@
1
- {
2
- "name": "costclaw",
3
- "version": "0.13.3",
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
+ }