costclaw 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -19
- package/dist/index.js +1079 -299
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
|
+
import { homedir as homedir7 } from "os";
|
|
5
6
|
|
|
6
7
|
// ../../packages/engine/src/types.ts
|
|
7
8
|
function emptyTotals() {
|
|
@@ -2363,6 +2364,27 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
|
|
|
2363
2364
|
}
|
|
2364
2365
|
return clean(parts.join("\n\n").trimEnd() + "\n");
|
|
2365
2366
|
}
|
|
2367
|
+
var INCLUDE_HEADING = [...REGENERATED_HEADING, /^token discipline\b/i];
|
|
2368
|
+
function isPlaceholderOnly(body) {
|
|
2369
|
+
return /^<!--[^]*?-->$/.test(body.trim());
|
|
2370
|
+
}
|
|
2371
|
+
function buildIncludeMd(optimizedClaudeMd) {
|
|
2372
|
+
const sections = parseSections(optimizedClaudeMd).filter(
|
|
2373
|
+
(s) => INCLUDE_HEADING.some((re) => re.test(s.heading)) && !isPlaceholderOnly(s.body)
|
|
2374
|
+
);
|
|
2375
|
+
const header = [
|
|
2376
|
+
"<!--",
|
|
2377
|
+
" Generated by CostClaw (https://costclaw.io). Regenerated on every",
|
|
2378
|
+
" `costclaw apply`; edit your CLAUDE.md, not this file.",
|
|
2379
|
+
" Imported from CLAUDE.md by the line: @.claude/costclaw.md",
|
|
2380
|
+
" Undo: costclaw apply . --remove",
|
|
2381
|
+
"-->"
|
|
2382
|
+
].join("\n");
|
|
2383
|
+
const parts = [header, ...sections.map((s) => `## ${s.heading}
|
|
2384
|
+
|
|
2385
|
+
${s.body}`)];
|
|
2386
|
+
return { includeMd: clean(parts.join("\n\n").trimEnd() + "\n"), includeSections: sections.map((s) => s.heading) };
|
|
2387
|
+
}
|
|
2366
2388
|
function joinAnd(items) {
|
|
2367
2389
|
if (items.length === 0) return "";
|
|
2368
2390
|
if (items.length === 1) return items[0];
|
|
@@ -2577,8 +2599,9 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
2577
2599
|
[
|
|
2578
2600
|
"You are Claude Code, working in this repository. costclaw generated this",
|
|
2579
2601
|
"work order from a local audit of real usage logs plus a scan of this",
|
|
2580
|
-
"project; every task is grounded in that evidence.
|
|
2581
|
-
"
|
|
2602
|
+
"project; every task is grounded in that evidence. The files named below",
|
|
2603
|
+
"sit in the same folder as this work order. Execute the tasks in order",
|
|
2604
|
+
"and report what changed at the end."
|
|
2582
2605
|
].join("\n")
|
|
2583
2606
|
);
|
|
2584
2607
|
parts.push(
|
|
@@ -2596,30 +2619,34 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
2596
2619
|
);
|
|
2597
2620
|
parts.push(
|
|
2598
2621
|
[
|
|
2599
|
-
"## Task 1:
|
|
2622
|
+
"## Task 1: Slim your CLAUDE.md",
|
|
2623
|
+
"",
|
|
2624
|
+
"If `.claude/costclaw.md` does not exist yet, run `npx costclaw apply .`",
|
|
2625
|
+
"first. It writes the generated sections (see `costclaw.md` here) to",
|
|
2626
|
+
"`.claude/costclaw.md` and adds `@.claude/costclaw.md` to CLAUDE.md.",
|
|
2600
2627
|
"",
|
|
2601
|
-
"
|
|
2628
|
+
"Then, in `./CLAUDE.md`:",
|
|
2629
|
+
"- For each section the include now covers (Commands, Project structure,",
|
|
2630
|
+
" Code style, Testing, Environment): compare yours with the include. If a",
|
|
2631
|
+
" fact of yours is missing from the include, keep that line in CLAUDE.md",
|
|
2632
|
+
" under its heading (the include is regenerated, never edit it). Otherwise",
|
|
2633
|
+
" delete your copy so each section appears once.",
|
|
2634
|
+
"- Move the volatile sections listed below into docs/ and link them.",
|
|
2635
|
+
"- Strip any generator HTML comment blocks.",
|
|
2636
|
+
"- Show the diff before writing.",
|
|
2602
2637
|
"",
|
|
2603
|
-
"
|
|
2604
|
-
"- Structure and curation: the optimized file wins (section set, command",
|
|
2605
|
-
" curation, dropped filler).",
|
|
2606
|
-
"- Commands: start from the optimized curated list with its annotations;",
|
|
2607
|
-
" re-add a dropped script only when the workflow genuinely needs it",
|
|
2608
|
-
" pinned in an always-loaded file.",
|
|
2609
|
-
"- Strip the generator's HTML comment blocks from the final file.",
|
|
2610
|
-
"- Back up, show the diff, then write."
|
|
2638
|
+
"Only `apply --replace` swaps the whole file; do not do that here."
|
|
2611
2639
|
].join("\n")
|
|
2612
2640
|
);
|
|
2613
2641
|
parts.push(
|
|
2614
2642
|
[
|
|
2615
2643
|
"## Task 2: Permission allowlist",
|
|
2616
2644
|
"",
|
|
2617
|
-
"Review `
|
|
2618
|
-
"
|
|
2619
|
-
"
|
|
2620
|
-
"
|
|
2621
|
-
"
|
|
2622
|
-
"with a backup and a diff if you prefer."
|
|
2645
|
+
"Review `settings.suggested.json` (read-only tools plus this project's",
|
|
2646
|
+
"safe commands; denies secret reads and destructive ops). Merge the",
|
|
2647
|
+
"rules you agree with additively into `.claude/settings.json`, keeping",
|
|
2648
|
+
"every existing entry. `npx costclaw apply . --apply-settings`",
|
|
2649
|
+
"performs the mechanical merge with a backup and a diff if you prefer."
|
|
2623
2650
|
].join("\n")
|
|
2624
2651
|
);
|
|
2625
2652
|
let n = 3;
|
|
@@ -2729,7 +2756,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
2729
2756
|
const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
|
|
2730
2757
|
if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
|
|
2731
2758
|
if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
|
|
2732
|
-
verify.push(
|
|
2759
|
+
verify.push(
|
|
2760
|
+
"- Confirm CLAUDE.md contains the line `@.claude/costclaw.md` and that the",
|
|
2761
|
+
" regenerated sections (Commands, Project structure, Code style, Testing,",
|
|
2762
|
+
" Environment) appear once across CLAUDE.md and the include.",
|
|
2763
|
+
"- Confirm no generator comment blocks are left in CLAUDE.md."
|
|
2764
|
+
);
|
|
2733
2765
|
if (carried.carriedTokens >= CARRY_HEAVY_TOKENS) {
|
|
2734
2766
|
verify.push(
|
|
2735
2767
|
"- Confirm every line moved out of CLAUDE.md landed in a file under",
|
|
@@ -2760,14 +2792,17 @@ function optimize(input) {
|
|
|
2760
2792
|
const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
|
|
2761
2793
|
const settingsJson = buildSettings(input.project);
|
|
2762
2794
|
const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
|
|
2795
|
+
const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
|
|
2763
2796
|
const cleanNotes = notes.map((n) => clean(n));
|
|
2764
2797
|
const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
|
|
2765
|
-
if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
|
|
2798
|
+
if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || hasEmDash(includeMd) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
|
|
2766
2799
|
return {
|
|
2767
2800
|
optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
|
|
2768
2801
|
playbook: sanitizeText(playbook),
|
|
2769
2802
|
settingsJson: sanitizeText(settingsJson),
|
|
2770
2803
|
harnessPrompt: sanitizeText(harnessPrompt),
|
|
2804
|
+
includeMd: sanitizeText(includeMd),
|
|
2805
|
+
includeSections,
|
|
2771
2806
|
notes: cleanNotes.map(sanitizeText),
|
|
2772
2807
|
placeholdersRemaining: stats.placeholders,
|
|
2773
2808
|
claudeMdTokens,
|
|
@@ -2780,6 +2815,8 @@ function optimize(input) {
|
|
|
2780
2815
|
playbook,
|
|
2781
2816
|
settingsJson,
|
|
2782
2817
|
harnessPrompt,
|
|
2818
|
+
includeMd,
|
|
2819
|
+
includeSections,
|
|
2783
2820
|
notes: cleanNotes,
|
|
2784
2821
|
placeholdersRemaining: stats.placeholders,
|
|
2785
2822
|
claudeMdTokens,
|
|
@@ -3111,7 +3148,7 @@ function projectNameFromLogs(files) {
|
|
|
3111
3148
|
if (typeof rec.cwd === "string" && rec.cwd) {
|
|
3112
3149
|
const parts = rec.cwd.split(/[\\/]+/).filter(Boolean);
|
|
3113
3150
|
const base = parts.at(-1);
|
|
3114
|
-
if (base) return base;
|
|
3151
|
+
if (base) return { slug: base, cwd: rec.cwd };
|
|
3115
3152
|
}
|
|
3116
3153
|
}
|
|
3117
3154
|
} finally {
|
|
@@ -3123,13 +3160,14 @@ function projectNameFromLogs(files) {
|
|
|
3123
3160
|
async function readSessions(rootPath) {
|
|
3124
3161
|
const logs = [];
|
|
3125
3162
|
const skipped = [];
|
|
3126
|
-
|
|
3163
|
+
const projectDirs = /* @__PURE__ */ new Map();
|
|
3164
|
+
let entries;
|
|
3127
3165
|
try {
|
|
3128
|
-
|
|
3166
|
+
entries = await readdir(rootPath, { withFileTypes: true });
|
|
3129
3167
|
} catch {
|
|
3130
|
-
return { logs, skipped };
|
|
3168
|
+
return { logs, skipped, projectDirs };
|
|
3131
3169
|
}
|
|
3132
|
-
for (const dir of
|
|
3170
|
+
for (const dir of entries) {
|
|
3133
3171
|
if (!dir.isDirectory()) continue;
|
|
3134
3172
|
const projPath = join(rootPath, dir.name);
|
|
3135
3173
|
try {
|
|
@@ -3139,7 +3177,9 @@ async function readSessions(rootPath) {
|
|
|
3139
3177
|
continue;
|
|
3140
3178
|
}
|
|
3141
3179
|
const files = await collectJsonl(projPath);
|
|
3142
|
-
const
|
|
3180
|
+
const probe = projectNameFromLogs(files);
|
|
3181
|
+
const projectSlug = probe?.slug ?? dir.name;
|
|
3182
|
+
if (probe && !projectDirs.has(probe.slug)) projectDirs.set(probe.slug, probe.cwd);
|
|
3143
3183
|
for (const full of files) {
|
|
3144
3184
|
const rel = relative(projPath, full).split(sep).join("/");
|
|
3145
3185
|
const name = `${dir.name}/${rel}`;
|
|
@@ -3152,7 +3192,7 @@ async function readSessions(rootPath) {
|
|
|
3152
3192
|
}
|
|
3153
3193
|
}
|
|
3154
3194
|
}
|
|
3155
|
-
return { logs, skipped };
|
|
3195
|
+
return { logs, skipped, projectDirs };
|
|
3156
3196
|
}
|
|
3157
3197
|
|
|
3158
3198
|
// src/ansi.ts
|
|
@@ -4106,7 +4146,7 @@ var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
|
4106
4146
|
var SNAPSHOT_KEEP = 50;
|
|
4107
4147
|
async function loadAuditInputs(opts) {
|
|
4108
4148
|
const root = opts.path || defaultProjectsPath();
|
|
4109
|
-
const { logs, skipped } = await readSessions(root);
|
|
4149
|
+
const { logs, skipped, projectDirs } = await readSessions(root);
|
|
4110
4150
|
if (logs.length === 0) {
|
|
4111
4151
|
throw new Error(`No .jsonl sessions found under ${root}. Set CLAUDE_PROJECTS_PATH or pass --path <dir>.`);
|
|
4112
4152
|
}
|
|
@@ -4123,7 +4163,7 @@ async function loadAuditInputs(opts) {
|
|
|
4123
4163
|
} catch {
|
|
4124
4164
|
}
|
|
4125
4165
|
}
|
|
4126
|
-
return { logs, claudeMd, claudeMdSource, root, skipped };
|
|
4166
|
+
return { logs, claudeMd, claudeMdSource, root, skipped, projectDirs };
|
|
4127
4167
|
}
|
|
4128
4168
|
async function runAudit(opts) {
|
|
4129
4169
|
const { logs, claudeMd, claudeMdSource, root, skipped } = await loadAuditInputs({
|
|
@@ -4187,10 +4227,252 @@ async function runAudit(opts) {
|
|
|
4187
4227
|
}
|
|
4188
4228
|
|
|
4189
4229
|
// src/optimize-command.ts
|
|
4190
|
-
import { mkdir as
|
|
4191
|
-
import { join as
|
|
4230
|
+
import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile9, stat as stat3 } from "fs/promises";
|
|
4231
|
+
import { basename as basename2, join as join9, resolve as resolve4 } from "path";
|
|
4192
4232
|
import { homedir as homedir5 } from "os";
|
|
4193
4233
|
|
|
4234
|
+
// src/apply-command.ts
|
|
4235
|
+
import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile5, rm as rm3, stat, copyFile } from "fs/promises";
|
|
4236
|
+
import { join as join6, dirname } from "path";
|
|
4237
|
+
var IMPORT_LINE = "@.claude/costclaw.md";
|
|
4238
|
+
var INCLUDE_REL = ".claude/costclaw.md";
|
|
4239
|
+
var APPLY_DIR_REL = ".claude/costclaw";
|
|
4240
|
+
var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
|
|
4241
|
+
var INCLUDE_ARTIFACT = "costclaw.md";
|
|
4242
|
+
var OPTIMIZED_ARTIFACT = "CLAUDE.optimized.md";
|
|
4243
|
+
async function pathExists(p) {
|
|
4244
|
+
try {
|
|
4245
|
+
await stat(p);
|
|
4246
|
+
return true;
|
|
4247
|
+
} catch {
|
|
4248
|
+
return false;
|
|
4249
|
+
}
|
|
4250
|
+
}
|
|
4251
|
+
function ensureImportLine(claudeMd) {
|
|
4252
|
+
if (claudeMd === null) return { text: `${IMPORT_LINE}
|
|
4253
|
+
`, added: true };
|
|
4254
|
+
const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE);
|
|
4255
|
+
if (has) return { text: claudeMd, added: false };
|
|
4256
|
+
const base = claudeMd.replace(/\s*$/, "");
|
|
4257
|
+
return { text: base.length === 0 ? `${IMPORT_LINE}
|
|
4258
|
+
` : `${base}
|
|
4259
|
+
|
|
4260
|
+
${IMPORT_LINE}
|
|
4261
|
+
`, added: true };
|
|
4262
|
+
}
|
|
4263
|
+
function stripImportLine(claudeMd) {
|
|
4264
|
+
const lines = claudeMd.split(/\r?\n/);
|
|
4265
|
+
const i = lines.findIndex((l) => l.trim() === IMPORT_LINE);
|
|
4266
|
+
if (i < 0) return { text: claudeMd, removed: false };
|
|
4267
|
+
lines.splice(i, 1);
|
|
4268
|
+
if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
|
|
4269
|
+
let text2 = lines.join("\n");
|
|
4270
|
+
if (!text2.endsWith("\n")) text2 += "\n";
|
|
4271
|
+
return { text: text2 === "\n" ? "" : text2, removed: true };
|
|
4272
|
+
}
|
|
4273
|
+
async function runInclude(opts) {
|
|
4274
|
+
const { projectDir, artifactsDir } = opts;
|
|
4275
|
+
const includeSrc = join6(artifactsDir, INCLUDE_ARTIFACT);
|
|
4276
|
+
if (!await pathExists(includeSrc)) {
|
|
4277
|
+
throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
|
|
4278
|
+
}
|
|
4279
|
+
const includeMd = await readFile5(includeSrc, "utf8");
|
|
4280
|
+
const claudeDir = join6(projectDir, ".claude");
|
|
4281
|
+
await mkdir4(claudeDir, { recursive: true });
|
|
4282
|
+
const includeDest = join6(projectDir, INCLUDE_REL);
|
|
4283
|
+
await writeFile4(includeDest, includeMd, "utf8");
|
|
4284
|
+
const wrote = [includeDest];
|
|
4285
|
+
const lines = [`Wrote ${INCLUDE_REL}`];
|
|
4286
|
+
const claudeMdPath = join6(projectDir, "CLAUDE.md");
|
|
4287
|
+
const existing = await pathExists(claudeMdPath) ? await readFile5(claudeMdPath, "utf8") : null;
|
|
4288
|
+
const { text: text2, added } = ensureImportLine(existing);
|
|
4289
|
+
if (added) {
|
|
4290
|
+
await writeFile4(claudeMdPath, text2, "utf8");
|
|
4291
|
+
wrote.push(claudeMdPath);
|
|
4292
|
+
lines.push(`Added "${IMPORT_LINE}" to CLAUDE.md`);
|
|
4293
|
+
} else {
|
|
4294
|
+
lines.push("CLAUDE.md already imports it");
|
|
4295
|
+
}
|
|
4296
|
+
const companionDir = join6(projectDir, APPLY_DIR_REL);
|
|
4297
|
+
await mkdir4(companionDir, { recursive: true });
|
|
4298
|
+
for (const name of COMPANIONS) {
|
|
4299
|
+
const src = join6(artifactsDir, name);
|
|
4300
|
+
if (await pathExists(src)) {
|
|
4301
|
+
const dest = join6(companionDir, name);
|
|
4302
|
+
await copyFile(src, dest);
|
|
4303
|
+
wrote.push(dest);
|
|
4304
|
+
}
|
|
4305
|
+
}
|
|
4306
|
+
lines.push(`Copied the playbook, work order and suggested settings to ${APPLY_DIR_REL}/`);
|
|
4307
|
+
lines.push(`Undo: costclaw apply ${projectDir} --remove`);
|
|
4308
|
+
lines.push('Next: claude "Follow .claude/costclaw/HARNESS-UPGRADE.md"');
|
|
4309
|
+
if (opts.applySettings) {
|
|
4310
|
+
const settingsSrc = join6(artifactsDir, "settings.suggested.json");
|
|
4311
|
+
const suggestedJson = await readFile5(settingsSrc, "utf8");
|
|
4312
|
+
const target = opts.applySettingsPath ?? join6(projectDir, ".claude", "settings.json");
|
|
4313
|
+
const settingsLines = await applyDerivedSettings(target, suggestedJson, opts.force ?? false);
|
|
4314
|
+
lines.push(...settingsLines);
|
|
4315
|
+
wrote.push(target);
|
|
4316
|
+
}
|
|
4317
|
+
return { lines, wrote, removed: [] };
|
|
4318
|
+
}
|
|
4319
|
+
async function runRemove(opts) {
|
|
4320
|
+
const { projectDir } = opts;
|
|
4321
|
+
const includeDest = join6(projectDir, INCLUDE_REL);
|
|
4322
|
+
const companionDir = join6(projectDir, APPLY_DIR_REL);
|
|
4323
|
+
const removed = [];
|
|
4324
|
+
if (await pathExists(includeDest)) {
|
|
4325
|
+
await rm3(includeDest, { force: true });
|
|
4326
|
+
removed.push(includeDest);
|
|
4327
|
+
}
|
|
4328
|
+
if (await pathExists(companionDir)) {
|
|
4329
|
+
await rm3(companionDir, { recursive: true, force: true });
|
|
4330
|
+
removed.push(companionDir);
|
|
4331
|
+
}
|
|
4332
|
+
const lines = [`Removed ${INCLUDE_REL} and ${APPLY_DIR_REL}/`];
|
|
4333
|
+
const claudeMdPath = join6(projectDir, "CLAUDE.md");
|
|
4334
|
+
if (await pathExists(claudeMdPath)) {
|
|
4335
|
+
const existing = await readFile5(claudeMdPath, "utf8");
|
|
4336
|
+
const { text: text2, removed: didRemove } = stripImportLine(existing);
|
|
4337
|
+
if (didRemove) {
|
|
4338
|
+
if (text2 === "") {
|
|
4339
|
+
await rm3(claudeMdPath, { force: true });
|
|
4340
|
+
removed.push(claudeMdPath);
|
|
4341
|
+
lines.push("Removed CLAUDE.md (it held only the import line)");
|
|
4342
|
+
} else {
|
|
4343
|
+
await writeFile4(claudeMdPath, text2, "utf8");
|
|
4344
|
+
lines.push(`Removed "${IMPORT_LINE}" from CLAUDE.md`);
|
|
4345
|
+
}
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
return { lines, wrote: [], removed };
|
|
4349
|
+
}
|
|
4350
|
+
async function runReplace(opts) {
|
|
4351
|
+
const { projectDir, artifactsDir, force } = opts;
|
|
4352
|
+
if (!await pathExists(join6(projectDir, ".git"))) {
|
|
4353
|
+
throw new Error(
|
|
4354
|
+
"apply --replace needs a git repository so the change can be undone with git checkout -- CLAUDE.md. Use the default include mode instead."
|
|
4355
|
+
);
|
|
4356
|
+
}
|
|
4357
|
+
const optimizedSrc = join6(artifactsDir, OPTIMIZED_ARTIFACT);
|
|
4358
|
+
if (!await pathExists(optimizedSrc)) {
|
|
4359
|
+
throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
|
|
4360
|
+
}
|
|
4361
|
+
const optimized = await readFile5(optimizedSrc, "utf8");
|
|
4362
|
+
const claudeMdPath = join6(projectDir, "CLAUDE.md");
|
|
4363
|
+
const backup = `${claudeMdPath}.bak`;
|
|
4364
|
+
if (await pathExists(backup) && !force) {
|
|
4365
|
+
throw new Error(
|
|
4366
|
+
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
4367
|
+
);
|
|
4368
|
+
}
|
|
4369
|
+
const original = await pathExists(claudeMdPath) ? await readFile5(claudeMdPath, "utf8") : "";
|
|
4370
|
+
await writeFile4(backup, original, "utf8");
|
|
4371
|
+
await writeFile4(claudeMdPath, optimized, "utf8");
|
|
4372
|
+
const lines = [
|
|
4373
|
+
`Backed up the original to ${backup}`,
|
|
4374
|
+
`Wrote the optimized CLAUDE.md to ${claudeMdPath}`,
|
|
4375
|
+
"",
|
|
4376
|
+
"Diff (old vs new):",
|
|
4377
|
+
lineDiff(original, optimized),
|
|
4378
|
+
"",
|
|
4379
|
+
"Undo: git checkout -- CLAUDE.md (or restore CLAUDE.md.bak)"
|
|
4380
|
+
];
|
|
4381
|
+
return { lines, wrote: [claudeMdPath, backup], removed: [] };
|
|
4382
|
+
}
|
|
4383
|
+
async function runApply(opts) {
|
|
4384
|
+
if (opts.mode === "replace") return runReplace(opts);
|
|
4385
|
+
if (opts.mode === "remove") return runRemove(opts);
|
|
4386
|
+
return runInclude(opts);
|
|
4387
|
+
}
|
|
4388
|
+
function lineDiff(oldText, newText) {
|
|
4389
|
+
const oldLines = oldText.split(/\r?\n/);
|
|
4390
|
+
const newLines = newText.split(/\r?\n/);
|
|
4391
|
+
const oldSet = new Set(oldLines);
|
|
4392
|
+
const newSet = new Set(newLines);
|
|
4393
|
+
const lines = [];
|
|
4394
|
+
for (const line of oldLines) {
|
|
4395
|
+
if (!newSet.has(line)) lines.push(`- ${line}`);
|
|
4396
|
+
}
|
|
4397
|
+
for (const line of newLines) {
|
|
4398
|
+
if (!oldSet.has(line)) lines.push(`+ ${line}`);
|
|
4399
|
+
}
|
|
4400
|
+
if (lines.length === 0) lines.push(" (no line-level changes)");
|
|
4401
|
+
return lines.join("\n");
|
|
4402
|
+
}
|
|
4403
|
+
function asStringArray(value) {
|
|
4404
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
4405
|
+
}
|
|
4406
|
+
function unionStrings(existing, additions) {
|
|
4407
|
+
const out = [];
|
|
4408
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4409
|
+
for (const v of existing) {
|
|
4410
|
+
if (!seen.has(v)) {
|
|
4411
|
+
seen.add(v);
|
|
4412
|
+
out.push(v);
|
|
4413
|
+
}
|
|
4414
|
+
}
|
|
4415
|
+
for (const v of additions) {
|
|
4416
|
+
if (!seen.has(v)) {
|
|
4417
|
+
seen.add(v);
|
|
4418
|
+
out.push(v);
|
|
4419
|
+
}
|
|
4420
|
+
}
|
|
4421
|
+
return out;
|
|
4422
|
+
}
|
|
4423
|
+
function isPlainObject(value) {
|
|
4424
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4425
|
+
}
|
|
4426
|
+
async function applyDerivedSettings(target, suggestedJson, force) {
|
|
4427
|
+
const backup = `${target}.bak`;
|
|
4428
|
+
if (await pathExists(backup) && !force) {
|
|
4429
|
+
throw new Error(
|
|
4430
|
+
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
4431
|
+
);
|
|
4432
|
+
}
|
|
4433
|
+
let existingText = "";
|
|
4434
|
+
let existing = {};
|
|
4435
|
+
if (await pathExists(target)) {
|
|
4436
|
+
existingText = await readFile5(target, "utf8");
|
|
4437
|
+
if (existingText.trim() !== "") {
|
|
4438
|
+
let parsed;
|
|
4439
|
+
try {
|
|
4440
|
+
parsed = JSON.parse(existingText);
|
|
4441
|
+
} catch {
|
|
4442
|
+
throw new Error(
|
|
4443
|
+
`Could not parse ${target} as JSON, so it was left untouched. If it contains comments or trailing commas (JSONC), remove them, or point --apply-settings at a plain JSON file.`
|
|
4444
|
+
);
|
|
4445
|
+
}
|
|
4446
|
+
if (!isPlainObject(parsed)) {
|
|
4447
|
+
throw new Error(
|
|
4448
|
+
`Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
|
|
4449
|
+
);
|
|
4450
|
+
}
|
|
4451
|
+
existing = parsed;
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
const suggested = JSON.parse(suggestedJson);
|
|
4455
|
+
const suggestedAllow = asStringArray(suggested.permissions?.allow);
|
|
4456
|
+
const suggestedDeny = asStringArray(suggested.permissions?.deny);
|
|
4457
|
+
const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
|
|
4458
|
+
const mergedPerms = { ...existingPerms };
|
|
4459
|
+
mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
|
|
4460
|
+
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
4461
|
+
const merged = { ...existing, permissions: mergedPerms };
|
|
4462
|
+
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
4463
|
+
await mkdir4(dirname(target), { recursive: true });
|
|
4464
|
+
await writeFile4(backup, existingText, "utf8");
|
|
4465
|
+
await writeFile4(target, mergedText, "utf8");
|
|
4466
|
+
return [
|
|
4467
|
+
`Merged the derived permission allowlist into ${target}`,
|
|
4468
|
+
`Backed up the previous file to ${backup}`,
|
|
4469
|
+
"Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
|
|
4470
|
+
"",
|
|
4471
|
+
"Diff (previous vs merged):",
|
|
4472
|
+
lineDiff(existingText, mergedText)
|
|
4473
|
+
];
|
|
4474
|
+
}
|
|
4475
|
+
|
|
4194
4476
|
// src/optimize-dashboard.ts
|
|
4195
4477
|
function usd5(n) {
|
|
4196
4478
|
const rounded = Math.round(n * 100) / 100;
|
|
@@ -4533,16 +4815,21 @@ var OPTIMIZED_NAME = "CLAUDE.optimized.md";
|
|
|
4533
4815
|
var PLAYBOOK_NAME = "PLAYBOOK.md";
|
|
4534
4816
|
var SETTINGS_NAME = "settings.suggested.json";
|
|
4535
4817
|
var HARNESS_NAME = "HARNESS-UPGRADE.md";
|
|
4818
|
+
var INCLUDE_NAME = "costclaw.md";
|
|
4536
4819
|
function renderArtifactCards(input) {
|
|
4537
4820
|
const { before, after } = input.claudeMdTokens;
|
|
4538
4821
|
const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
|
|
4539
4822
|
const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
|
|
4540
4823
|
const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
|
|
4541
4824
|
const card = (name, desc) => `<div class="file"><span class="nm">${esc(name)}</span><span class="ds">${esc(desc)}</span><a href="${esc(name)}">Open file</a></div>`;
|
|
4542
|
-
return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") +
|
|
4825
|
+
return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") + card(
|
|
4826
|
+
INCLUDE_NAME,
|
|
4827
|
+
"The generated sections as a standalone include. apply writes it to .claude/costclaw.md and adds one @ line to your CLAUDE.md."
|
|
4828
|
+
) + `</div>`;
|
|
4543
4829
|
}
|
|
4544
4830
|
function renderApplyCta(input) {
|
|
4545
|
-
|
|
4831
|
+
const applyBlock = input.applyCommand ? `<p style="margin:0">Apply the generated sections as an include (your CLAUDE.md keeps every line you wrote; undo with --remove):</p><code class="cmd">${esc(input.applyCommand)}</code><p style="margin:16px 0 0"></p>` : "";
|
|
4832
|
+
return `<div class="cta">` + applyBlock + `<b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
|
|
4546
4833
|
}
|
|
4547
4834
|
function renderCarriedDisclosure(sections, carriedTokens) {
|
|
4548
4835
|
const carried = sections.filter((s) => s.disposition === "carried");
|
|
@@ -4557,7 +4844,7 @@ function renderHeader(input) {
|
|
|
4557
4844
|
const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
4558
4845
|
if (stack.length > 0) parts.push(esc(stack.join(", ")));
|
|
4559
4846
|
parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
|
|
4560
|
-
parts.push(`
|
|
4847
|
+
parts.push(`5 artifacts written to ${esc(input.artifactsDir)}/`);
|
|
4561
4848
|
return `<header><p class="kicker">CostClaw optimize · dry run · nothing left your machine</p><h1>${esc(input.projectName)}</h1><p class="sub">${parts.join(" · ")}</p></header>`;
|
|
4562
4849
|
}
|
|
4563
4850
|
function renderOptimizeDashboard(input) {
|
|
@@ -4585,7 +4872,7 @@ ${renderFixes(input.fixes, input.report)}
|
|
|
4585
4872
|
<h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
|
|
4586
4873
|
${renderSetupWarnings(input.fixes, input.report)}
|
|
4587
4874
|
|
|
4588
|
-
<h2>Your
|
|
4875
|
+
<h2>Your five artifacts</h2>
|
|
4589
4876
|
${renderArtifactCards(input)}
|
|
4590
4877
|
|
|
4591
4878
|
<h2>Apply it</h2>
|
|
@@ -4596,6 +4883,77 @@ ${renderCarriedDisclosure(input.sectionDispositions, input.carriedTokens)}
|
|
|
4596
4883
|
<footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
|
|
4597
4884
|
No network calls, no telemetry, no model calls.</footer>
|
|
4598
4885
|
|
|
4886
|
+
</div>
|
|
4887
|
+
</body>
|
|
4888
|
+
</html>
|
|
4889
|
+
`;
|
|
4890
|
+
}
|
|
4891
|
+
var INDEX_STYLE = `
|
|
4892
|
+
.rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
|
|
4893
|
+
.acts{display:flex;gap:8px;flex-wrap:wrap}
|
|
4894
|
+
.acts form{margin:0}
|
|
4895
|
+
.acts button{font:inherit;font-size:.82rem;padding:6px 12px;border-radius:7px;border:1px solid var(--line);
|
|
4896
|
+
background:var(--panel);color:var(--ink);cursor:pointer}
|
|
4897
|
+
.acts button:hover{border-color:var(--accent)}
|
|
4898
|
+
.acts button.go{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
|
|
4899
|
+
td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-all}
|
|
4900
|
+
.banner{background:color-mix(in srgb,var(--good) 14%,transparent);border:1px solid var(--line);
|
|
4901
|
+
border-radius:10px;padding:12px 14px;margin:0 0 22px;font-size:.9rem}
|
|
4902
|
+
.state{font-size:.82rem}
|
|
4903
|
+
.state.on{color:var(--good);font-weight:650}
|
|
4904
|
+
.state.off{color:var(--ink2)}
|
|
4905
|
+
`;
|
|
4906
|
+
function indexTokens(tokens) {
|
|
4907
|
+
if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
|
|
4908
|
+
return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
|
|
4909
|
+
}
|
|
4910
|
+
function indexStatus(appliedAt) {
|
|
4911
|
+
if (!appliedAt) return `<span class="state off">not applied</span>`;
|
|
4912
|
+
return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
|
|
4913
|
+
}
|
|
4914
|
+
function actionForm(token, slug, action, label, primary) {
|
|
4915
|
+
return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}>${esc(label)}</button></form>`;
|
|
4916
|
+
}
|
|
4917
|
+
function indexActions(row, serve) {
|
|
4918
|
+
const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
|
|
4919
|
+
if (!serve) {
|
|
4920
|
+
return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
|
|
4921
|
+
}
|
|
4922
|
+
return `<div class="acts">` + actionForm(serve.token, row.slug, "include", "Apply", true) + actionForm(serve.token, row.slug, "remove", "Remove", false) + actionForm(serve.token, row.slug, "settings", "Apply settings", false) + `</div><p class="note" style="margin-top:6px">${details}</p>`;
|
|
4923
|
+
}
|
|
4924
|
+
function renderOptimizeIndex(input) {
|
|
4925
|
+
const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
|
|
4926
|
+
const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
|
|
4927
|
+
const rows = input.rows.map(
|
|
4928
|
+
(r) => `<tr><td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt)}</td><td>${indexActions(r, input.serve)}</td></tr>`
|
|
4929
|
+
).join("");
|
|
4930
|
+
const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">Spend</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
|
4931
|
+
const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
|
|
4932
|
+
const done = input.serve ? `<div class="acts" style="margin:0 0 22px"><form method="post" action="/done"><input type="hidden" name="token" value="${esc(input.serve.token)}"><button type="submit">Done</button></form></div>` : "";
|
|
4933
|
+
const how = input.serve ? `<p class="note">Apply writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md. Every line you wrote stays where it is. Remove undoes both.</p>` : `<p class="note">Run the line on a project's row to apply it. It writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md; every line you wrote stays where it is. Undo with <code>--remove</code>.</p>`;
|
|
4934
|
+
return `<!doctype html>
|
|
4935
|
+
<html lang="en">
|
|
4936
|
+
<head>
|
|
4937
|
+
<meta charset="utf-8">
|
|
4938
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4939
|
+
<title>CostClaw optimize: ${input.rows.length} ${plural2(input.rows.length, "project")}</title>
|
|
4940
|
+
<style>${STYLE2}${INDEX_STYLE}</style>
|
|
4941
|
+
</head>
|
|
4942
|
+
<body>
|
|
4943
|
+
<div class="wrap">
|
|
4944
|
+
<header><p class="kicker">CostClaw optimize · generated locally · nothing left your machine</p>
|
|
4945
|
+
<h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
|
|
4946
|
+
<p class="sub">${esc(usd5(total))} of analyzed spend · ${esc(usd5(recoverable))} recoverable ·
|
|
4947
|
+
artifacts in ${esc(input.root)}/</p></header>
|
|
4948
|
+
|
|
4949
|
+
${banner}${done}
|
|
4950
|
+
<h2>Your projects<span class="n">ranked by spend</span></h2>
|
|
4951
|
+
${body}
|
|
4952
|
+
${how}
|
|
4953
|
+
|
|
4954
|
+
<footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
|
|
4955
|
+
Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
|
|
4956
|
+
|
|
4599
4957
|
</div>
|
|
4600
4958
|
</body>
|
|
4601
4959
|
</html>
|
|
@@ -4603,8 +4961,8 @@ No network calls, no telemetry, no model calls.</footer>
|
|
|
4603
4961
|
}
|
|
4604
4962
|
|
|
4605
4963
|
// src/project-scan.ts
|
|
4606
|
-
import { readdir as readdir3, readFile as
|
|
4607
|
-
import { join as
|
|
4964
|
+
import { readdir as readdir3, readFile as readFile6, stat as stat2 } from "fs/promises";
|
|
4965
|
+
import { join as join7, basename } from "path";
|
|
4608
4966
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
4609
4967
|
"node_modules",
|
|
4610
4968
|
".git",
|
|
@@ -4633,7 +4991,7 @@ var DIR_NOTES = {
|
|
|
4633
4991
|
};
|
|
4634
4992
|
async function readText(p) {
|
|
4635
4993
|
try {
|
|
4636
|
-
return await
|
|
4994
|
+
return await readFile6(p, "utf8");
|
|
4637
4995
|
} catch {
|
|
4638
4996
|
return null;
|
|
4639
4997
|
}
|
|
@@ -4743,7 +5101,7 @@ async function containsTestFiles(dir) {
|
|
|
4743
5101
|
const top = await listEntries(dir);
|
|
4744
5102
|
if (top.files.some((f) => TEST_FILE.test(f))) return true;
|
|
4745
5103
|
for (const sub of top.dirs) {
|
|
4746
|
-
const inner = await listEntries(
|
|
5104
|
+
const inner = await listEntries(join7(dir, sub));
|
|
4747
5105
|
if (inner.files.some((f) => TEST_FILE.test(f))) return true;
|
|
4748
5106
|
}
|
|
4749
5107
|
return false;
|
|
@@ -4753,14 +5111,14 @@ async function detectTestsLocation(dir, files, dirs) {
|
|
|
4753
5111
|
if (candidates.length > 0) {
|
|
4754
5112
|
const withTests = [];
|
|
4755
5113
|
for (const c of candidates) {
|
|
4756
|
-
if (await containsTestFiles(
|
|
5114
|
+
if (await containsTestFiles(join7(dir, c))) withTests.push(c);
|
|
4757
5115
|
}
|
|
4758
5116
|
const chosen = withTests.length > 0 ? withTests : candidates;
|
|
4759
5117
|
return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
|
|
4760
5118
|
}
|
|
4761
5119
|
if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
4762
5120
|
if (dirs.includes("src")) {
|
|
4763
|
-
const sub = await listEntries(
|
|
5121
|
+
const sub = await listEntries(join7(dir, "src"));
|
|
4764
5122
|
if (sub.files.some((f) => TEST_FILE.test(f))) {
|
|
4765
5123
|
return "tests alongside source (*.test.* / *.spec.*)";
|
|
4766
5124
|
}
|
|
@@ -4843,7 +5201,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
4843
5201
|
if (oneFileCmd !== null && "test" in scripts) {
|
|
4844
5202
|
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
4845
5203
|
}
|
|
4846
|
-
const tsconfig = parseJson(await readText(
|
|
5204
|
+
const tsconfig = parseJson(await readText(join7(dir, "tsconfig.json")));
|
|
4847
5205
|
if (tsconfig) {
|
|
4848
5206
|
const co = tsconfig.compilerOptions;
|
|
4849
5207
|
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
@@ -4946,7 +5304,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4946
5304
|
const deps = [];
|
|
4947
5305
|
const tables = /* @__PURE__ */ new Set();
|
|
4948
5306
|
let hasPoetry = false;
|
|
4949
|
-
const pyprojectText = await readText(
|
|
5307
|
+
const pyprojectText = await readText(join7(dir, "pyproject.toml"));
|
|
4950
5308
|
if (pyprojectText !== null) {
|
|
4951
5309
|
const parsed = parsePyproject(pyprojectText);
|
|
4952
5310
|
name = parsed.name;
|
|
@@ -4956,7 +5314,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4956
5314
|
hasPoetry = parsed.hasPoetry;
|
|
4957
5315
|
}
|
|
4958
5316
|
if (files.includes("requirements.txt")) {
|
|
4959
|
-
const reqText = await readText(
|
|
5317
|
+
const reqText = await readText(join7(dir, "requirements.txt"));
|
|
4960
5318
|
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
4961
5319
|
}
|
|
4962
5320
|
if (name !== null && name.trim() !== "") profile.name = name;
|
|
@@ -4990,7 +5348,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4990
5348
|
}
|
|
4991
5349
|
}
|
|
4992
5350
|
async function scanRust(dir, profile) {
|
|
4993
|
-
const text2 = await readText(
|
|
5351
|
+
const text2 = await readText(join7(dir, "Cargo.toml"));
|
|
4994
5352
|
pushUnique(profile.stack, "Rust");
|
|
4995
5353
|
profile.packageManager = "cargo";
|
|
4996
5354
|
if (text2 !== null) {
|
|
@@ -5016,7 +5374,7 @@ async function scanRust(dir, profile) {
|
|
|
5016
5374
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
5017
5375
|
}
|
|
5018
5376
|
async function scanGo(dir, profile) {
|
|
5019
|
-
const text2 = await readText(
|
|
5377
|
+
const text2 = await readText(join7(dir, "go.mod"));
|
|
5020
5378
|
pushUnique(profile.stack, "Go");
|
|
5021
5379
|
profile.packageManager = "go";
|
|
5022
5380
|
if (text2 !== null) {
|
|
@@ -5081,7 +5439,7 @@ async function scanProject(dir) {
|
|
|
5081
5439
|
const profile = emptyProfile(basename(dir));
|
|
5082
5440
|
const { files, dirs } = await listEntries(dir);
|
|
5083
5441
|
if (files.includes("package.json")) {
|
|
5084
|
-
const pkg = parseJson(await readText(
|
|
5442
|
+
const pkg = parseJson(await readText(join7(dir, "package.json")));
|
|
5085
5443
|
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
5086
5444
|
}
|
|
5087
5445
|
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
@@ -5094,7 +5452,7 @@ async function scanProject(dir) {
|
|
|
5094
5452
|
await scanGo(dir, profile);
|
|
5095
5453
|
}
|
|
5096
5454
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
5097
|
-
const text2 = await readText(
|
|
5455
|
+
const text2 = await readText(join7(dir, "Makefile"));
|
|
5098
5456
|
if (text2 !== null) {
|
|
5099
5457
|
for (const t of parseMakefile(text2)) {
|
|
5100
5458
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
@@ -5104,7 +5462,7 @@ async function scanProject(dir) {
|
|
|
5104
5462
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
5105
5463
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
5106
5464
|
if (readmeName) {
|
|
5107
|
-
const text2 = await readText(
|
|
5465
|
+
const text2 = await readText(join7(dir, readmeName));
|
|
5108
5466
|
if (text2 !== null) {
|
|
5109
5467
|
const parsed = parseReadme(text2);
|
|
5110
5468
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
@@ -5117,21 +5475,312 @@ async function scanProject(dir) {
|
|
|
5117
5475
|
profile.structure = await detectStructure(dir, dirs);
|
|
5118
5476
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
5119
5477
|
if (envFile) {
|
|
5120
|
-
const text2 = await readText(
|
|
5478
|
+
const text2 = await readText(join7(dir, envFile));
|
|
5121
5479
|
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
5122
5480
|
}
|
|
5123
5481
|
return profile;
|
|
5124
5482
|
}
|
|
5125
5483
|
|
|
5484
|
+
// src/serve.ts
|
|
5485
|
+
import { createServer } from "http";
|
|
5486
|
+
import { randomBytes } from "crypto";
|
|
5487
|
+
import { readFile as readFile7 } from "fs/promises";
|
|
5488
|
+
import { extname, resolve as resolve2, sep as sep2 } from "path";
|
|
5489
|
+
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
5490
|
+
var MAX_BODY_BYTES = 64 * 1024;
|
|
5491
|
+
var DASHBOARD_NAME = "DASHBOARD.html";
|
|
5492
|
+
function parseForm(body) {
|
|
5493
|
+
const out = {};
|
|
5494
|
+
for (const pair of body.split("&")) {
|
|
5495
|
+
if (pair === "") continue;
|
|
5496
|
+
const eq = pair.indexOf("=");
|
|
5497
|
+
const rawKey = eq < 0 ? pair : pair.slice(0, eq);
|
|
5498
|
+
const rawValue = eq < 0 ? "" : pair.slice(eq + 1);
|
|
5499
|
+
const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
|
|
5500
|
+
const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
|
|
5501
|
+
out[key] = value;
|
|
5502
|
+
}
|
|
5503
|
+
return out;
|
|
5504
|
+
}
|
|
5505
|
+
function safeArtifactPath(root, urlPath) {
|
|
5506
|
+
let decoded;
|
|
5507
|
+
try {
|
|
5508
|
+
decoded = decodeURIComponent(urlPath);
|
|
5509
|
+
} catch {
|
|
5510
|
+
return null;
|
|
5511
|
+
}
|
|
5512
|
+
if (decoded.includes("\0")) return null;
|
|
5513
|
+
const resolvedRoot = resolve2(root);
|
|
5514
|
+
const full = resolve2(resolvedRoot, "." + decoded);
|
|
5515
|
+
if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
|
|
5516
|
+
return full;
|
|
5517
|
+
}
|
|
5518
|
+
function rowsFromManifest(manifest) {
|
|
5519
|
+
return manifest.projects.map((e) => ({
|
|
5520
|
+
slug: e.slug,
|
|
5521
|
+
projectDir: e.projectDir,
|
|
5522
|
+
artifactsHref: `${e.dir}/${DASHBOARD_NAME}`,
|
|
5523
|
+
spendUsd: e.spendUsd,
|
|
5524
|
+
recoverableUsd: e.recoverableUsd,
|
|
5525
|
+
tokens: e.tokens,
|
|
5526
|
+
...e.appliedAt ? { appliedAt: e.appliedAt } : {},
|
|
5527
|
+
applyCommand: `costclaw apply ${e.projectDir}`
|
|
5528
|
+
}));
|
|
5529
|
+
}
|
|
5530
|
+
function isApplyAction(value) {
|
|
5531
|
+
return value === "include" || value === "remove" || value === "settings";
|
|
5532
|
+
}
|
|
5533
|
+
var CONTENT_TYPES = {
|
|
5534
|
+
".html": "text/html; charset=utf-8",
|
|
5535
|
+
".md": "text/plain; charset=utf-8",
|
|
5536
|
+
".json": "application/json; charset=utf-8"
|
|
5537
|
+
};
|
|
5538
|
+
function contentTypeFor(path) {
|
|
5539
|
+
return CONTENT_TYPES[extname(path).toLowerCase()] ?? "application/octet-stream";
|
|
5540
|
+
}
|
|
5541
|
+
function readBody(req, limitBytes) {
|
|
5542
|
+
return new Promise((resolvePromise, reject) => {
|
|
5543
|
+
const chunks = [];
|
|
5544
|
+
let size = 0;
|
|
5545
|
+
req.on("data", (chunk) => {
|
|
5546
|
+
size += chunk.length;
|
|
5547
|
+
if (size > limitBytes) {
|
|
5548
|
+
reject(new Error("payload too large"));
|
|
5549
|
+
return;
|
|
5550
|
+
}
|
|
5551
|
+
chunks.push(chunk);
|
|
5552
|
+
});
|
|
5553
|
+
req.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8")));
|
|
5554
|
+
req.on("error", reject);
|
|
5555
|
+
});
|
|
5556
|
+
}
|
|
5557
|
+
function sendText(res, status, text2) {
|
|
5558
|
+
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
|
|
5559
|
+
res.end(text2);
|
|
5560
|
+
}
|
|
5561
|
+
async function startApplyServer(opts) {
|
|
5562
|
+
const token = randomBytes(16).toString("hex");
|
|
5563
|
+
const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
|
|
5564
|
+
const manifest = opts.manifest;
|
|
5565
|
+
let closedAlready = false;
|
|
5566
|
+
let resolveClosed;
|
|
5567
|
+
const closedPromise = new Promise((res) => {
|
|
5568
|
+
resolveClosed = res;
|
|
5569
|
+
});
|
|
5570
|
+
let idleTimer;
|
|
5571
|
+
function resetIdle() {
|
|
5572
|
+
clearTimeout(idleTimer);
|
|
5573
|
+
idleTimer = setTimeout(() => {
|
|
5574
|
+
void close();
|
|
5575
|
+
}, idleMs);
|
|
5576
|
+
idleTimer.unref();
|
|
5577
|
+
}
|
|
5578
|
+
async function close() {
|
|
5579
|
+
if (closedAlready) return;
|
|
5580
|
+
closedAlready = true;
|
|
5581
|
+
clearTimeout(idleTimer);
|
|
5582
|
+
await new Promise((res) => server.close(() => res()));
|
|
5583
|
+
resolveClosed();
|
|
5584
|
+
}
|
|
5585
|
+
async function handleIndex(req, res, search) {
|
|
5586
|
+
const msg = search.get("msg");
|
|
5587
|
+
const html = renderOptimizeIndex({
|
|
5588
|
+
version: opts.version,
|
|
5589
|
+
generatedAt: manifest.generatedAt,
|
|
5590
|
+
root: opts.root,
|
|
5591
|
+
rows: rowsFromManifest(manifest),
|
|
5592
|
+
serve: { token, ...msg ? { message: msg } : {} }
|
|
5593
|
+
});
|
|
5594
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
5595
|
+
res.end(html);
|
|
5596
|
+
}
|
|
5597
|
+
async function handleApply(req, res) {
|
|
5598
|
+
let body;
|
|
5599
|
+
try {
|
|
5600
|
+
body = await readBody(req, MAX_BODY_BYTES);
|
|
5601
|
+
} catch {
|
|
5602
|
+
sendText(res, 400, "Payload too large");
|
|
5603
|
+
return;
|
|
5604
|
+
}
|
|
5605
|
+
const form = parseForm(body);
|
|
5606
|
+
if (form["token"] !== token) {
|
|
5607
|
+
sendText(res, 403, "Forbidden");
|
|
5608
|
+
return;
|
|
5609
|
+
}
|
|
5610
|
+
const action = form["action"];
|
|
5611
|
+
if (!isApplyAction(action)) {
|
|
5612
|
+
sendText(res, 400, "Unknown action");
|
|
5613
|
+
return;
|
|
5614
|
+
}
|
|
5615
|
+
const entry = manifest.projects.find((p) => p.slug === form["slug"]);
|
|
5616
|
+
if (!entry) {
|
|
5617
|
+
sendText(res, 400, "Unknown project");
|
|
5618
|
+
return;
|
|
5619
|
+
}
|
|
5620
|
+
let msg;
|
|
5621
|
+
try {
|
|
5622
|
+
const lines = await opts.apply(entry, action);
|
|
5623
|
+
if (action === "remove") delete entry.appliedAt;
|
|
5624
|
+
else entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5625
|
+
if (opts.onManifestChange) await opts.onManifestChange(manifest);
|
|
5626
|
+
msg = lines[0] ?? "Done.";
|
|
5627
|
+
} catch (err) {
|
|
5628
|
+
msg = `Error: ${err instanceof Error ? err.message : String(err)}`;
|
|
5629
|
+
}
|
|
5630
|
+
res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg)}` });
|
|
5631
|
+
res.end();
|
|
5632
|
+
}
|
|
5633
|
+
async function handleDone(req, res) {
|
|
5634
|
+
let body;
|
|
5635
|
+
try {
|
|
5636
|
+
body = await readBody(req, MAX_BODY_BYTES);
|
|
5637
|
+
} catch {
|
|
5638
|
+
body = "";
|
|
5639
|
+
}
|
|
5640
|
+
const form = parseForm(body);
|
|
5641
|
+
if (form["token"] !== token) {
|
|
5642
|
+
sendText(res, 403, "Forbidden");
|
|
5643
|
+
return;
|
|
5644
|
+
}
|
|
5645
|
+
sendText(res, 200, "You can close this tab.");
|
|
5646
|
+
void close();
|
|
5647
|
+
}
|
|
5648
|
+
async function handleStatic(pathname, res) {
|
|
5649
|
+
const filePath = safeArtifactPath(opts.root, pathname);
|
|
5650
|
+
if (!filePath) {
|
|
5651
|
+
sendText(res, 404, "Not found");
|
|
5652
|
+
return;
|
|
5653
|
+
}
|
|
5654
|
+
try {
|
|
5655
|
+
const data = await readFile7(filePath);
|
|
5656
|
+
res.writeHead(200, { "content-type": contentTypeFor(filePath) });
|
|
5657
|
+
res.end(data);
|
|
5658
|
+
} catch {
|
|
5659
|
+
sendText(res, 404, "Not found");
|
|
5660
|
+
}
|
|
5661
|
+
}
|
|
5662
|
+
async function handle(req, res) {
|
|
5663
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
5664
|
+
const method = req.method ?? "GET";
|
|
5665
|
+
if (url.pathname === "/" && method === "GET") {
|
|
5666
|
+
await handleIndex(req, res, url.searchParams);
|
|
5667
|
+
return;
|
|
5668
|
+
}
|
|
5669
|
+
if (url.pathname === "/apply" && method === "POST") {
|
|
5670
|
+
await handleApply(req, res);
|
|
5671
|
+
return;
|
|
5672
|
+
}
|
|
5673
|
+
if (url.pathname === "/done" && method === "POST") {
|
|
5674
|
+
await handleDone(req, res);
|
|
5675
|
+
return;
|
|
5676
|
+
}
|
|
5677
|
+
if (method === "GET") {
|
|
5678
|
+
await handleStatic(url.pathname, res);
|
|
5679
|
+
return;
|
|
5680
|
+
}
|
|
5681
|
+
sendText(res, 404, "Not found");
|
|
5682
|
+
}
|
|
5683
|
+
const server = createServer((req, res) => {
|
|
5684
|
+
resetIdle();
|
|
5685
|
+
handle(req, res).catch((err) => {
|
|
5686
|
+
if (!res.headersSent) {
|
|
5687
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
5688
|
+
}
|
|
5689
|
+
res.end(`Internal error: ${err instanceof Error ? err.message : String(err)}`);
|
|
5690
|
+
});
|
|
5691
|
+
});
|
|
5692
|
+
await new Promise((res, reject) => {
|
|
5693
|
+
server.once("error", reject);
|
|
5694
|
+
server.listen(0, "127.0.0.1", () => res());
|
|
5695
|
+
});
|
|
5696
|
+
resetIdle();
|
|
5697
|
+
const address = server.address();
|
|
5698
|
+
if (address === null || typeof address === "string") {
|
|
5699
|
+
throw new Error("failed to bind the loopback apply server");
|
|
5700
|
+
}
|
|
5701
|
+
return {
|
|
5702
|
+
url: `http://127.0.0.1:${address.port}`,
|
|
5703
|
+
port: address.port,
|
|
5704
|
+
close,
|
|
5705
|
+
closed: closedPromise
|
|
5706
|
+
};
|
|
5707
|
+
}
|
|
5708
|
+
|
|
5709
|
+
// src/optimize-manifest.ts
|
|
5710
|
+
import { mkdir as mkdir5, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
|
|
5711
|
+
import { join as join8, resolve as resolve3 } from "path";
|
|
5712
|
+
var MANIFEST_NAME = "index.json";
|
|
5713
|
+
function defaultOptimizeRoot(home) {
|
|
5714
|
+
return join8(home, ".costclaw", "optimize");
|
|
5715
|
+
}
|
|
5716
|
+
function isRecord(value) {
|
|
5717
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5718
|
+
}
|
|
5719
|
+
async function readManifest(root) {
|
|
5720
|
+
let text2;
|
|
5721
|
+
try {
|
|
5722
|
+
text2 = await readFile8(join8(root, MANIFEST_NAME), "utf8");
|
|
5723
|
+
} catch {
|
|
5724
|
+
return null;
|
|
5725
|
+
}
|
|
5726
|
+
let parsed;
|
|
5727
|
+
try {
|
|
5728
|
+
parsed = JSON.parse(text2);
|
|
5729
|
+
} catch {
|
|
5730
|
+
return null;
|
|
5731
|
+
}
|
|
5732
|
+
if (!isRecord(parsed) || !Array.isArray(parsed["projects"])) return null;
|
|
5733
|
+
const projects = parsed["projects"].filter((p) => isRecord(p) && typeof p["projectDir"] === "string");
|
|
5734
|
+
return {
|
|
5735
|
+
generatedAt: typeof parsed["generatedAt"] === "string" ? parsed["generatedAt"] : "",
|
|
5736
|
+
root: typeof parsed["root"] === "string" ? parsed["root"] : root,
|
|
5737
|
+
projects
|
|
5738
|
+
};
|
|
5739
|
+
}
|
|
5740
|
+
async function writeManifest(root, m) {
|
|
5741
|
+
await mkdir5(root, { recursive: true });
|
|
5742
|
+
await writeFile5(join8(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
|
|
5743
|
+
}
|
|
5744
|
+
function normalizePath(p) {
|
|
5745
|
+
const r = resolve3(p);
|
|
5746
|
+
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
5747
|
+
}
|
|
5748
|
+
function findEntry(m, projectDir) {
|
|
5749
|
+
const want = normalizePath(projectDir);
|
|
5750
|
+
return m.projects.find((p) => normalizePath(p.projectDir) === want);
|
|
5751
|
+
}
|
|
5752
|
+
function fnv1a(text2) {
|
|
5753
|
+
let h = 2166136261;
|
|
5754
|
+
for (let i = 0; i < text2.length; i++) {
|
|
5755
|
+
h ^= text2.charCodeAt(i);
|
|
5756
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
5757
|
+
}
|
|
5758
|
+
return h.toString(16).padStart(8, "0");
|
|
5759
|
+
}
|
|
5760
|
+
function safeDirName(slug) {
|
|
5761
|
+
const cleaned = slug.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
|
|
5762
|
+
return cleaned.length > 0 ? cleaned : "project";
|
|
5763
|
+
}
|
|
5764
|
+
function artifactDirName(slug, projectDir, taken) {
|
|
5765
|
+
const base = safeDirName(slug);
|
|
5766
|
+
if (!taken.has(base)) return base;
|
|
5767
|
+
return `${base}-${fnv1a(normalizePath(projectDir))}`;
|
|
5768
|
+
}
|
|
5769
|
+
|
|
5126
5770
|
// src/optimize-command.ts
|
|
5127
5771
|
var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
|
|
5128
5772
|
var PLAYBOOK_NAME2 = "PLAYBOOK.md";
|
|
5129
5773
|
var SETTINGS_NAME2 = "settings.suggested.json";
|
|
5130
5774
|
var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
|
|
5131
|
-
var
|
|
5775
|
+
var DASHBOARD_NAME2 = "DASHBOARD.html";
|
|
5776
|
+
var INCLUDE_NAME2 = "costclaw.md";
|
|
5777
|
+
var DEFAULT_LIMIT = 10;
|
|
5132
5778
|
function usd6(n) {
|
|
5133
5779
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
5134
5780
|
}
|
|
5781
|
+
function num5(n) {
|
|
5782
|
+
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
5783
|
+
}
|
|
5135
5784
|
function describeDetection(project) {
|
|
5136
5785
|
const name = project.name?.trim() || "unnamed project";
|
|
5137
5786
|
const n = project.commands.length;
|
|
@@ -5146,276 +5795,321 @@ function unscannedWarning(projectDir) {
|
|
|
5146
5795
|
return [
|
|
5147
5796
|
`Warning: the scan found no stack and no commands in ${projectDir}.`,
|
|
5148
5797
|
"Are you in the right folder? optimize fills the scaffold from a project's own files,",
|
|
5149
|
-
"so
|
|
5798
|
+
"so point it at a project with --project <dir>."
|
|
5150
5799
|
];
|
|
5151
5800
|
}
|
|
5152
|
-
async function
|
|
5801
|
+
async function pathExists2(p) {
|
|
5153
5802
|
try {
|
|
5154
|
-
await
|
|
5803
|
+
await stat3(p);
|
|
5155
5804
|
return true;
|
|
5156
5805
|
} catch {
|
|
5157
5806
|
return false;
|
|
5158
5807
|
}
|
|
5159
5808
|
}
|
|
5160
|
-
function
|
|
5161
|
-
const
|
|
5162
|
-
|
|
5163
|
-
const oldSet = new Set(oldLines);
|
|
5164
|
-
const newSet = new Set(newLines);
|
|
5165
|
-
const lines = [];
|
|
5166
|
-
for (const line of oldLines) {
|
|
5167
|
-
if (!newSet.has(line)) lines.push(`- ${line}`);
|
|
5168
|
-
}
|
|
5169
|
-
for (const line of newLines) {
|
|
5170
|
-
if (!oldSet.has(line)) lines.push(`+ ${line}`);
|
|
5171
|
-
}
|
|
5172
|
-
if (lines.length === 0) lines.push(" (no line-level changes)");
|
|
5173
|
-
return lines.join("\n");
|
|
5809
|
+
function projectSpend(report, slug) {
|
|
5810
|
+
const p = report.projects.find((x) => x.slug === slug);
|
|
5811
|
+
return p ? p.cost_usd : null;
|
|
5174
5812
|
}
|
|
5175
|
-
function
|
|
5176
|
-
|
|
5813
|
+
function projectRecoverable(report, slug) {
|
|
5814
|
+
const row = cacheMissByProject(report).find((r) => r.slug === slug);
|
|
5815
|
+
return row ? row.usd : null;
|
|
5177
5816
|
}
|
|
5178
|
-
function
|
|
5179
|
-
const
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5190
|
-
out.push(v);
|
|
5817
|
+
async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
5818
|
+
const slug = basename2(resolve4(projectDir));
|
|
5819
|
+
let currentClaudeMd = ctx.claudeMdOverride;
|
|
5820
|
+
let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
|
|
5821
|
+
if (currentClaudeMd === void 0) {
|
|
5822
|
+
const own = join9(projectDir, "CLAUDE.md");
|
|
5823
|
+
if (await pathExists2(own)) {
|
|
5824
|
+
currentClaudeMd = await readFile9(own, "utf8");
|
|
5825
|
+
claudeMdSource = own;
|
|
5826
|
+
} else {
|
|
5827
|
+
currentClaudeMd = ctx.globalClaudeMd;
|
|
5828
|
+
claudeMdSource = ctx.globalClaudeMd === void 0 ? null : ctx.claudeMdFallbackSource;
|
|
5191
5829
|
}
|
|
5192
5830
|
}
|
|
5193
|
-
|
|
5194
|
-
|
|
5195
|
-
|
|
5196
|
-
|
|
5197
|
-
|
|
5198
|
-
|
|
5199
|
-
|
|
5200
|
-
|
|
5201
|
-
|
|
5202
|
-
|
|
5831
|
+
const project = await scanProject(projectDir);
|
|
5832
|
+
const result = optimize({
|
|
5833
|
+
report: ctx.report,
|
|
5834
|
+
scores: ctx.pillars,
|
|
5835
|
+
fixes: ctx.fixes,
|
|
5836
|
+
currentClaudeMd,
|
|
5837
|
+
project
|
|
5838
|
+
});
|
|
5839
|
+
await mkdir6(artifactsDir, { recursive: true });
|
|
5840
|
+
await writeFile6(join9(artifactsDir, OPTIMIZED_NAME2), result.optimizedClaudeMd, "utf8");
|
|
5841
|
+
await writeFile6(join9(artifactsDir, PLAYBOOK_NAME2), result.playbook, "utf8");
|
|
5842
|
+
await writeFile6(join9(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
|
|
5843
|
+
await writeFile6(join9(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
|
|
5844
|
+
await writeFile6(join9(artifactsDir, INCLUDE_NAME2), result.includeMd, "utf8");
|
|
5845
|
+
const spend = projectSpend(ctx.report, slug);
|
|
5846
|
+
const recoverable = projectRecoverable(ctx.report, slug);
|
|
5847
|
+
const applyCommand = `costclaw apply ${projectDir}`;
|
|
5848
|
+
if (ctx.dashboard) {
|
|
5849
|
+
const auditSpend = ctx.report.summary.cost_usd;
|
|
5850
|
+
const auditRecoverable2 = cacheMissExposureUsd(ctx.report);
|
|
5851
|
+
const html = renderOptimizeDashboard({
|
|
5852
|
+
version: ctx.version,
|
|
5853
|
+
projectName: project.name ?? slug,
|
|
5854
|
+
stack: project.stack,
|
|
5855
|
+
commandsCount: project.commands.length,
|
|
5856
|
+
artifactsDir,
|
|
5857
|
+
currentClaudeMd: currentClaudeMd ?? null,
|
|
5858
|
+
optimizedClaudeMd: result.optimizedClaudeMd,
|
|
5859
|
+
claudeMdTokens: result.claudeMdTokens,
|
|
5860
|
+
carriedTokens: result.carriedTokens,
|
|
5861
|
+
sectionDispositions: result.sectionDispositions,
|
|
5862
|
+
placeholdersRemaining: result.placeholdersRemaining,
|
|
5863
|
+
fixes: ctx.fixes,
|
|
5864
|
+
report: ctx.report,
|
|
5865
|
+
headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
|
|
5866
|
+
headlineWasteUsd: auditRecoverable2,
|
|
5867
|
+
applyCommand
|
|
5868
|
+
});
|
|
5869
|
+
await writeFile6(join9(artifactsDir, DASHBOARD_NAME2), html, "utf8");
|
|
5870
|
+
}
|
|
5871
|
+
const lines = ctx.lines;
|
|
5872
|
+
lines.push(slug);
|
|
5873
|
+
if (looksUnscanned(project)) lines.push(...unscannedWarning(projectDir));
|
|
5874
|
+
lines.push(describeDetection(project));
|
|
5875
|
+
if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
|
|
5876
|
+
const auditRecoverable = cacheMissExposureUsd(ctx.report);
|
|
5877
|
+
const shownRecoverable = recoverable ?? auditRecoverable;
|
|
5878
|
+
const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
|
|
5879
|
+
const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
|
|
5880
|
+
if (ctx.plan === "api") {
|
|
5881
|
+
lines.push(`Recoverable spend (cache-miss exposure) ${scopeLabel}: ${usd6(shownRecoverable)}`);
|
|
5882
|
+
} else {
|
|
5883
|
+
const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
|
|
5884
|
+
lines.push(
|
|
5885
|
+
`Recoverable usage (cache-miss exposure) ${scopeLabel}: ${share.toFixed(1)}% of analyzed usage (${usd6(shownRecoverable)} at API rates)`
|
|
5203
5886
|
);
|
|
5204
5887
|
}
|
|
5205
|
-
|
|
5206
|
-
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
|
|
5210
|
-
|
|
5211
|
-
|
|
5212
|
-
|
|
5213
|
-
|
|
5214
|
-
|
|
5215
|
-
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
if (!isPlainObject(parsed)) {
|
|
5219
|
-
throw new Error(
|
|
5220
|
-
`Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
|
|
5221
|
-
);
|
|
5222
|
-
}
|
|
5223
|
-
existing = parsed;
|
|
5888
|
+
const { before, after } = result.claudeMdTokens;
|
|
5889
|
+
if (before != null && before !== after) {
|
|
5890
|
+
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
5891
|
+
const dir = after > before ? "larger" : "smaller";
|
|
5892
|
+
lines.push(
|
|
5893
|
+
`Your CLAUDE.md: an estimated ${num5(before)} tokens to ${num5(after)} (${pct2}% ${dir}), paid on every turn.`
|
|
5894
|
+
);
|
|
5895
|
+
if (result.carriedTokens >= after / 2) {
|
|
5896
|
+
lines.push(
|
|
5897
|
+
`About ${num5(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
5898
|
+
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
5899
|
+
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
5900
|
+
);
|
|
5224
5901
|
}
|
|
5225
5902
|
}
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
5232
|
-
|
|
5233
|
-
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
|
|
5903
|
+
if (result.placeholdersRemaining > 0) {
|
|
5904
|
+
const n = result.placeholdersRemaining;
|
|
5905
|
+
lines.push(
|
|
5906
|
+
`${n} section${n === 1 ? "" : "s"} left as placeholder${n === 1 ? "" : "s"} (no evidence to fill ${n === 1 ? "it" : "them"}); search the scaffold for <!-- ... -->.`
|
|
5907
|
+
);
|
|
5908
|
+
}
|
|
5909
|
+
for (const note of result.notes) lines.push(` - ${note}`);
|
|
5910
|
+
lines.push(`Artifacts: ${artifactsDir}`);
|
|
5911
|
+
lines.push(`Apply: ${applyCommand}`);
|
|
5912
|
+
lines.push("");
|
|
5913
|
+
return {
|
|
5914
|
+
slug,
|
|
5915
|
+
dir: basename2(artifactsDir),
|
|
5916
|
+
projectDir,
|
|
5917
|
+
artifactsDir,
|
|
5918
|
+
spendUsd: spend ?? 0,
|
|
5919
|
+
recoverableUsd: recoverable ?? 0,
|
|
5920
|
+
tokens: result.claudeMdTokens,
|
|
5921
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5922
|
+
};
|
|
5246
5923
|
}
|
|
5247
5924
|
async function runOptimize(opts) {
|
|
5248
|
-
const
|
|
5249
|
-
let
|
|
5250
|
-
if (!
|
|
5251
|
-
const
|
|
5252
|
-
if (await
|
|
5925
|
+
const home = opts.home ?? homedir5();
|
|
5926
|
+
let inputsClaudeMdPath = opts.claudeMdPath;
|
|
5927
|
+
if (!inputsClaudeMdPath && opts.projectDir) {
|
|
5928
|
+
const own = join9(opts.projectDir, "CLAUDE.md");
|
|
5929
|
+
if (await pathExists2(own)) inputsClaudeMdPath = own;
|
|
5253
5930
|
}
|
|
5254
|
-
const { logs, claudeMd, claudeMdSource } = await loadAuditInputs({
|
|
5931
|
+
const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
|
|
5932
|
+
path: opts.path,
|
|
5933
|
+
claudeMdPath: inputsClaudeMdPath,
|
|
5934
|
+
home: opts.home
|
|
5935
|
+
});
|
|
5255
5936
|
const report = analyzeUploads(logs);
|
|
5256
5937
|
const cmd2 = analyzeClaudeMd(claudeMd);
|
|
5257
5938
|
const { pillars } = scorePillars(report, cmd2, {});
|
|
5258
|
-
const configDir =
|
|
5939
|
+
const configDir = join9(home, ".costclaw");
|
|
5259
5940
|
const { plan } = await resolvePlan(configDir, opts.plan);
|
|
5260
5941
|
const { fixes } = synthesize(report, pillars, cmd2, plan);
|
|
5261
|
-
const
|
|
5262
|
-
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
5263
|
-
const recoverable = cacheMissExposureUsd(report);
|
|
5942
|
+
const auditRecoverable = cacheMissExposureUsd(report);
|
|
5264
5943
|
const baselineSpend = report.summary.cost_usd;
|
|
5265
5944
|
await saveCliConfig(configDir, {
|
|
5266
5945
|
lastOptimize: {
|
|
5267
5946
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5268
5947
|
totals: { ...report.summary.totals },
|
|
5269
5948
|
cacheHitRate: report.summary.cacheHitRate,
|
|
5270
|
-
headlineWasteShare: baselineSpend > 0 ?
|
|
5949
|
+
headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
|
|
5271
5950
|
spendUsd: baselineSpend
|
|
5272
5951
|
}
|
|
5273
5952
|
});
|
|
5274
|
-
const
|
|
5275
|
-
|
|
5276
|
-
const
|
|
5277
|
-
|
|
5278
|
-
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
|
|
5283
|
-
|
|
5284
|
-
if (wantDashboard) {
|
|
5285
|
-
const spend = report.summary.cost_usd;
|
|
5286
|
-
const html = renderOptimizeDashboard({
|
|
5287
|
-
version: opts.version ?? "",
|
|
5288
|
-
projectName: project.name ?? "your project",
|
|
5289
|
-
stack: project.stack,
|
|
5290
|
-
commandsCount: project.commands.length,
|
|
5291
|
-
artifactsDir: outDir,
|
|
5292
|
-
currentClaudeMd: claudeMd ?? null,
|
|
5293
|
-
optimizedClaudeMd: result.optimizedClaudeMd,
|
|
5294
|
-
claudeMdTokens: result.claudeMdTokens,
|
|
5295
|
-
carriedTokens: result.carriedTokens,
|
|
5296
|
-
sectionDispositions: result.sectionDispositions,
|
|
5297
|
-
placeholdersRemaining: result.placeholdersRemaining,
|
|
5298
|
-
fixes,
|
|
5299
|
-
report,
|
|
5300
|
-
headlineWasteShare: spend > 0 ? recoverable / spend : 0,
|
|
5301
|
-
headlineWasteUsd: recoverable
|
|
5953
|
+
const single = opts.projectDir !== void 0;
|
|
5954
|
+
const manifestRoot = single ? defaultOptimizeRoot(home) : opts.out ?? defaultOptimizeRoot(home);
|
|
5955
|
+
const targets = [];
|
|
5956
|
+
let skippedMissing = 0;
|
|
5957
|
+
let overLimit = 0;
|
|
5958
|
+
const limit = opts.limit && opts.limit > 0 ? opts.limit : DEFAULT_LIMIT;
|
|
5959
|
+
if (opts.projectDir !== void 0) {
|
|
5960
|
+
targets.push({
|
|
5961
|
+
projectDir: opts.projectDir,
|
|
5962
|
+
artifactsDir: opts.out ?? join9(opts.projectDir, "costclaw-out")
|
|
5302
5963
|
});
|
|
5303
|
-
|
|
5304
|
-
|
|
5964
|
+
} else {
|
|
5965
|
+
const ranked = [...report.projects].sort((a, b) => b.cost_usd - a.cost_usd);
|
|
5966
|
+
const taken = /* @__PURE__ */ new Set();
|
|
5967
|
+
for (const p of ranked) {
|
|
5968
|
+
const dir = projectDirs.get(p.slug);
|
|
5969
|
+
if (!dir || !await pathExists2(dir)) {
|
|
5970
|
+
skippedMissing++;
|
|
5971
|
+
continue;
|
|
5972
|
+
}
|
|
5973
|
+
if (targets.length >= limit) {
|
|
5974
|
+
overLimit++;
|
|
5975
|
+
continue;
|
|
5976
|
+
}
|
|
5977
|
+
const name = artifactDirName(p.slug, dir, taken);
|
|
5978
|
+
taken.add(name);
|
|
5979
|
+
targets.push({ projectDir: dir, artifactsDir: join9(manifestRoot, name) });
|
|
5980
|
+
}
|
|
5305
5981
|
}
|
|
5306
|
-
const lines = [];
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
|
|
5310
|
-
|
|
5311
|
-
|
|
5982
|
+
const lines = ["CostClaw optimize", ""];
|
|
5983
|
+
if (!single) {
|
|
5984
|
+
lines.push(
|
|
5985
|
+
`Generated for ${targets.length} ${targets.length === 1 ? "project" : "projects"} from your audit, ranked by spend.`,
|
|
5986
|
+
"Nothing was written inside any project: that only happens on costclaw apply.",
|
|
5987
|
+
""
|
|
5988
|
+
);
|
|
5989
|
+
} else {
|
|
5990
|
+
lines.push("Generated (nothing of yours was changed).", "");
|
|
5312
5991
|
}
|
|
5313
|
-
|
|
5314
|
-
|
|
5315
|
-
|
|
5316
|
-
|
|
5317
|
-
|
|
5318
|
-
|
|
5319
|
-
|
|
5992
|
+
const ctx = {
|
|
5993
|
+
report,
|
|
5994
|
+
pillars,
|
|
5995
|
+
fixes,
|
|
5996
|
+
plan,
|
|
5997
|
+
globalClaudeMd: opts.claudeMdPath ? void 0 : claudeMd,
|
|
5998
|
+
claudeMdOverride: opts.claudeMdPath ? claudeMd : void 0,
|
|
5999
|
+
claudeMdFallbackSource: claudeMdSource,
|
|
6000
|
+
version: opts.version ?? "",
|
|
6001
|
+
dashboard: opts.dashboard !== false,
|
|
6002
|
+
lines
|
|
6003
|
+
};
|
|
6004
|
+
const entries = [];
|
|
6005
|
+
for (const t of targets) {
|
|
6006
|
+
entries.push(await generateForProject(ctx, t.projectDir, t.artifactsDir));
|
|
6007
|
+
}
|
|
6008
|
+
const previous = await readManifest(manifestRoot);
|
|
6009
|
+
const merged = entries.map((e) => {
|
|
6010
|
+
const old = previous ? findEntry(previous, e.projectDir) : void 0;
|
|
6011
|
+
return old?.appliedAt ? { ...e, appliedAt: old.appliedAt } : e;
|
|
6012
|
+
});
|
|
6013
|
+
if (single && previous) {
|
|
6014
|
+
const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
|
|
6015
|
+
for (const old of previous.projects) {
|
|
6016
|
+
if (!findEntry(sofar, old.projectDir)) merged.push(old);
|
|
5320
6017
|
}
|
|
5321
|
-
|
|
5322
|
-
|
|
5323
|
-
|
|
6018
|
+
}
|
|
6019
|
+
const manifest = {
|
|
6020
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6021
|
+
root: manifestRoot,
|
|
6022
|
+
projects: merged
|
|
6023
|
+
};
|
|
6024
|
+
await writeManifest(manifestRoot, manifest);
|
|
6025
|
+
let indexHtmlPath = null;
|
|
6026
|
+
if (!single && ctx.dashboard) {
|
|
6027
|
+
const rows = merged.map((e) => ({
|
|
6028
|
+
slug: e.slug,
|
|
6029
|
+
projectDir: e.projectDir,
|
|
6030
|
+
artifactsHref: `${e.dir}/${DASHBOARD_NAME2}`,
|
|
6031
|
+
spendUsd: e.spendUsd,
|
|
6032
|
+
recoverableUsd: e.recoverableUsd,
|
|
6033
|
+
tokens: e.tokens,
|
|
6034
|
+
...e.appliedAt ? { appliedAt: e.appliedAt } : {},
|
|
6035
|
+
applyCommand: `costclaw apply ${e.projectDir}`
|
|
6036
|
+
}));
|
|
6037
|
+
const html = renderOptimizeIndex({
|
|
6038
|
+
version: ctx.version,
|
|
6039
|
+
generatedAt: manifest.generatedAt,
|
|
6040
|
+
root: manifestRoot,
|
|
6041
|
+
rows
|
|
6042
|
+
});
|
|
6043
|
+
indexHtmlPath = join9(manifestRoot, DASHBOARD_NAME2);
|
|
6044
|
+
await writeFile6(indexHtmlPath, html, "utf8");
|
|
6045
|
+
}
|
|
6046
|
+
if (!single) {
|
|
6047
|
+
lines.push(
|
|
6048
|
+
`${entries.length} ${entries.length === 1 ? "project" : "projects"} generated, ${skippedMissing} skipped (folder not found).`
|
|
6049
|
+
);
|
|
6050
|
+
if (overLimit > 0) {
|
|
6051
|
+
lines.push(`${overLimit} more were left out by the limit of ${limit}; pass --limit N to include more.`);
|
|
5324
6052
|
}
|
|
5325
|
-
|
|
5326
|
-
|
|
5327
|
-
|
|
5328
|
-
|
|
5329
|
-
|
|
5330
|
-
|
|
5331
|
-
|
|
5332
|
-
lines.push("");
|
|
5333
|
-
lines.push("Diff (old vs new):");
|
|
5334
|
-
lines.push(lineDiff(original, result.optimizedClaudeMd));
|
|
6053
|
+
}
|
|
6054
|
+
lines.push(
|
|
6055
|
+
`The ${SETTINGS_NAME2} in each artifacts folder is a conservative permission allowlist derived from what you already run.`,
|
|
6056
|
+
"Review it, then merge it with costclaw apply <project-dir> --apply-settings. It is never applied unless you ask."
|
|
6057
|
+
);
|
|
6058
|
+
const top = entries[0];
|
|
6059
|
+
if (top) {
|
|
5335
6060
|
lines.push("");
|
|
5336
|
-
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
6061
|
+
lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
|
|
6062
|
+
lines.push(` claude "Follow ${join9(top.artifactsDir, HARNESS_NAME2)}"`);
|
|
6063
|
+
lines.push(
|
|
6064
|
+
"It slims the CLAUDE.md, applies the permissions you approve, and fixes the audit's harness-level findings. costclaw itself never calls a model."
|
|
6065
|
+
);
|
|
6066
|
+
}
|
|
6067
|
+
lines.push("");
|
|
6068
|
+
lines.push(`Manifest: ${join9(manifestRoot, "index.json")}`);
|
|
6069
|
+
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
6070
|
+
lines.push("Nothing left your machine.");
|
|
6071
|
+
const openPath = indexHtmlPath ?? (ctx.dashboard && top ? join9(top.artifactsDir, DASHBOARD_NAME2) : null);
|
|
6072
|
+
if (openPath) {
|
|
5348
6073
|
lines.push("");
|
|
5349
|
-
|
|
5350
|
-
if (
|
|
5351
|
-
|
|
5352
|
-
lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
|
|
5353
|
-
} else {
|
|
5354
|
-
const spend = report.summary.cost_usd;
|
|
5355
|
-
const share = spend > 0 ? recoverable / spend * 100 : 0;
|
|
6074
|
+
const canServe = opts.serve !== false && !process.env["VITEST"] && !process.env["CI"] && !process.env["COSTCLAW_NO_OPEN"] && manifest.projects.length > 0;
|
|
6075
|
+
if (!canServe) {
|
|
6076
|
+
lines.push(`Opening the summary dashboard: ${openPath}`);
|
|
5356
6077
|
lines.push(
|
|
5357
|
-
|
|
6078
|
+
indexHtmlPath ? "It lists every project with its receipt and the apply line. Pass --no-dashboard to skip it." : "It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it."
|
|
5358
6079
|
);
|
|
6080
|
+
} else {
|
|
6081
|
+
lines.push(`Summary dashboard saved to: ${openPath}`);
|
|
5359
6082
|
}
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
6083
|
+
if (canServe) {
|
|
6084
|
+
const srv = await startApplyServer({
|
|
6085
|
+
root: manifestRoot,
|
|
6086
|
+
manifest,
|
|
6087
|
+
version: ctx.version,
|
|
6088
|
+
apply: async (entry, action) => {
|
|
6089
|
+
const outcome = await runApply({
|
|
6090
|
+
projectDir: entry.projectDir,
|
|
6091
|
+
mode: action === "remove" ? "remove" : "include",
|
|
6092
|
+
artifactsDir: entry.artifactsDir,
|
|
6093
|
+
applySettings: action === "settings"
|
|
6094
|
+
});
|
|
6095
|
+
return outcome.lines;
|
|
6096
|
+
},
|
|
6097
|
+
onManifestChange: (m) => writeManifest(manifestRoot, m)
|
|
6098
|
+
});
|
|
5365
6099
|
lines.push(
|
|
5366
|
-
`
|
|
6100
|
+
`Apply page: ${srv.url} (Apply/Remove buttons; press Ctrl+C or click Done when finished; closes after 30 idle minutes)`
|
|
5367
6101
|
);
|
|
5368
|
-
|
|
5369
|
-
lines.push(
|
|
5370
|
-
`About ${g(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
5371
|
-
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
5372
|
-
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
5373
|
-
);
|
|
5374
|
-
}
|
|
5375
|
-
}
|
|
5376
|
-
lines.push("");
|
|
5377
|
-
if (result.placeholdersRemaining > 0) {
|
|
5378
|
-
const n = result.placeholdersRemaining;
|
|
5379
|
-
lines.push(`The optimized CLAUDE.md has ${n} section${n === 1 ? "" : "s"} left as placeholders (no evidence to fill them).`);
|
|
5380
|
-
lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
|
|
6102
|
+
openInBrowser(srv.url);
|
|
5381
6103
|
} else {
|
|
5382
|
-
|
|
5383
|
-
lines.push("Review it (the notes below say what changed), then apply it.");
|
|
6104
|
+
openInBrowser(openPath);
|
|
5384
6105
|
}
|
|
5385
|
-
lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
|
|
5386
|
-
lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied unless you ask.");
|
|
5387
|
-
lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
|
|
5388
|
-
lines.push("");
|
|
5389
|
-
lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
|
|
5390
|
-
lines.push(' claude "Follow costclaw-out/HARNESS-UPGRADE.md"');
|
|
5391
|
-
lines.push("It merges the CLAUDE.md, applies the permissions you approve, and fixes the audit's harness-level findings. costclaw itself never calls a model.");
|
|
5392
6106
|
}
|
|
5393
|
-
|
|
5394
|
-
const target = opts.applySettingsPath || join7(projectDir, ".claude", "settings.json");
|
|
5395
|
-
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
5396
|
-
lines.push("");
|
|
5397
|
-
lines.push(...applyLines);
|
|
5398
|
-
}
|
|
5399
|
-
if (result.notes.length > 0) {
|
|
5400
|
-
lines.push("");
|
|
5401
|
-
lines.push("Notes:");
|
|
5402
|
-
for (const note of result.notes) lines.push(` - ${note}`);
|
|
5403
|
-
}
|
|
5404
|
-
lines.push("");
|
|
5405
|
-
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
5406
|
-
lines.push("Nothing left your machine.");
|
|
5407
|
-
if (dashboardPath) {
|
|
5408
|
-
lines.push("");
|
|
5409
|
-
lines.push(`Opening the summary dashboard: ${dashboardPath}`);
|
|
5410
|
-
lines.push("It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it.");
|
|
5411
|
-
openInBrowser(dashboardPath);
|
|
5412
|
-
}
|
|
5413
|
-
return { output: lines.join("\n") };
|
|
6107
|
+
return { output: lines.join("\n"), root: manifestRoot, manifest, indexHtmlPath };
|
|
5414
6108
|
}
|
|
5415
6109
|
|
|
5416
6110
|
// src/badge-command.ts
|
|
5417
|
-
import { writeFile as
|
|
5418
|
-
import { resolve as
|
|
6111
|
+
import { writeFile as writeFile7 } from "fs/promises";
|
|
6112
|
+
import { resolve as resolve5 } from "path";
|
|
5419
6113
|
|
|
5420
6114
|
// src/badge.ts
|
|
5421
6115
|
var HEIGHT2 = 20;
|
|
@@ -5439,14 +6133,14 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
|
5439
6133
|
async function runBadge(opts) {
|
|
5440
6134
|
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
5441
6135
|
const svg = renderBadge(record);
|
|
5442
|
-
const target =
|
|
5443
|
-
await
|
|
6136
|
+
const target = resolve5(opts.out || DEFAULT_BADGE_FILE);
|
|
6137
|
+
await writeFile7(target, svg, "utf8");
|
|
5444
6138
|
return { output: `Badge written to ${target}`, record, target };
|
|
5445
6139
|
}
|
|
5446
6140
|
|
|
5447
6141
|
// src/diff-command.ts
|
|
5448
|
-
import { readdir as readdir4, readFile as
|
|
5449
|
-
import { join as
|
|
6142
|
+
import { readdir as readdir4, readFile as readFile10 } from "fs/promises";
|
|
6143
|
+
import { join as join10 } from "path";
|
|
5450
6144
|
import { homedir as homedir6 } from "os";
|
|
5451
6145
|
|
|
5452
6146
|
// src/format-diff.ts
|
|
@@ -5535,7 +6229,7 @@ function formatDiff(d) {
|
|
|
5535
6229
|
async function readRecord(path) {
|
|
5536
6230
|
let text2;
|
|
5537
6231
|
try {
|
|
5538
|
-
text2 = await
|
|
6232
|
+
text2 = await readFile10(path, "utf8");
|
|
5539
6233
|
} catch {
|
|
5540
6234
|
throw new Error(`Could not read ${path}.`);
|
|
5541
6235
|
}
|
|
@@ -5551,7 +6245,7 @@ async function runDiff(opts) {
|
|
|
5551
6245
|
let pathA = opts.fileA;
|
|
5552
6246
|
let pathB = opts.fileB;
|
|
5553
6247
|
if (!pathA || !pathB) {
|
|
5554
|
-
const dir =
|
|
6248
|
+
const dir = join10(opts.home ?? homedir6(), ".costclaw", "history");
|
|
5555
6249
|
let files = [];
|
|
5556
6250
|
try {
|
|
5557
6251
|
files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
@@ -5562,8 +6256,8 @@ async function runDiff(opts) {
|
|
|
5562
6256
|
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
5563
6257
|
);
|
|
5564
6258
|
}
|
|
5565
|
-
pathA =
|
|
5566
|
-
pathB =
|
|
6259
|
+
pathA = join10(dir, files[files.length - 2]);
|
|
6260
|
+
pathB = join10(dir, files[files.length - 1]);
|
|
5567
6261
|
}
|
|
5568
6262
|
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
5569
6263
|
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
@@ -5616,8 +6310,24 @@ function parseBadgeFlags(args) {
|
|
|
5616
6310
|
out: getFlag(args, "--out")
|
|
5617
6311
|
};
|
|
5618
6312
|
}
|
|
6313
|
+
function parseApplyFlags(args) {
|
|
6314
|
+
const from = getFlag(args, "--from");
|
|
6315
|
+
const applySettings = args.includes("--apply-settings");
|
|
6316
|
+
const applySettingsPath = applySettings ? optionalPathAfter(args, "--apply-settings") : void 0;
|
|
6317
|
+
const consumed = new Set([from, applySettingsPath].filter((v) => v !== void 0));
|
|
6318
|
+
const positional = args.find((a) => !a.startsWith("-") && !consumed.has(a));
|
|
6319
|
+
const mode = args.includes("--remove") ? "remove" : args.includes("--replace") ? "replace" : "include";
|
|
6320
|
+
return {
|
|
6321
|
+
projectDir: positional ?? process.cwd(),
|
|
6322
|
+
mode,
|
|
6323
|
+
from,
|
|
6324
|
+
applySettings,
|
|
6325
|
+
applySettingsPath,
|
|
6326
|
+
force: args.includes("--force")
|
|
6327
|
+
};
|
|
6328
|
+
}
|
|
5619
6329
|
function cliVersion() {
|
|
5620
|
-
return true ? "0.
|
|
6330
|
+
return true ? "0.10.0" : "0.0.0-dev";
|
|
5621
6331
|
}
|
|
5622
6332
|
function isHelpRequest(command, args) {
|
|
5623
6333
|
if (command === void 0) return false;
|
|
@@ -5632,7 +6342,8 @@ function helpText() {
|
|
|
5632
6342
|
" costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
|
|
5633
6343
|
" costclaw diff [<baseline.json> <current.json>] [--json]",
|
|
5634
6344
|
" costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
|
|
5635
|
-
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--
|
|
6345
|
+
" costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
|
|
6346
|
+
" costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
|
|
5636
6347
|
" costclaw activate <license-key> [--name <machine-name>]",
|
|
5637
6348
|
" costclaw deactivate",
|
|
5638
6349
|
" costclaw --version",
|
|
@@ -5662,20 +6373,37 @@ function helpText() {
|
|
|
5662
6373
|
"costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
|
|
5663
6374
|
"in a README with an <img> tag; it is a static, self-contained file.",
|
|
5664
6375
|
"",
|
|
5665
|
-
"optimize
|
|
5666
|
-
"scaffold
|
|
5667
|
-
"
|
|
5668
|
-
"
|
|
5669
|
-
"
|
|
5670
|
-
"
|
|
5671
|
-
"
|
|
5672
|
-
"the
|
|
5673
|
-
"
|
|
5674
|
-
"
|
|
5675
|
-
"
|
|
5676
|
-
"
|
|
5677
|
-
"
|
|
5678
|
-
"
|
|
6376
|
+
"optimize generates, for every project your audit saw, five artifacts: an",
|
|
6377
|
+
"optimized CLAUDE.md scaffold, a prioritized fix playbook, a conservative,",
|
|
6378
|
+
"project-derived settings.suggested.json permission allowlist, a",
|
|
6379
|
+
"HARNESS-UPGRADE.md work order for your own Claude Code, and costclaw.md (the",
|
|
6380
|
+
"generated sections as a standalone include). It never writes inside a",
|
|
6381
|
+
"project; only costclaw apply does that, on an explicit command.",
|
|
6382
|
+
"By default it runs globally: it ranks your audited projects by spend,",
|
|
6383
|
+
"generates for the top ones (cap 10, override with --limit N) into",
|
|
6384
|
+
"~/.costclaw/optimize/<project>/, and writes one DASHBOARD.html index plus a",
|
|
6385
|
+
"local apply page you can click through instead of the command line",
|
|
6386
|
+
"(Ctrl+C, its Done button, or --no-serve to skip it). --project <dir> keeps",
|
|
6387
|
+
"the single-project run, writing into ./costclaw-out (or --out <dir>)",
|
|
6388
|
+
"instead. --no-dashboard skips the HTML.",
|
|
6389
|
+
"",
|
|
6390
|
+
"apply [<dir>] (default: the current directory) is the only command that",
|
|
6391
|
+
"writes inside a project, and only additively: it writes the generated",
|
|
6392
|
+
"sections to .claude/costclaw.md and adds one @.claude/costclaw.md import",
|
|
6393
|
+
"line to your CLAUDE.md, leaving every line you wrote untouched. --remove",
|
|
6394
|
+
"undoes that. --replace is the old wholesale rewrite, now gated behind a git",
|
|
6395
|
+
"repository so the undo is `git checkout -- CLAUDE.md` (it still keeps a",
|
|
6396
|
+
".bak too). --apply-settings [file] additively merges the derived permission",
|
|
6397
|
+
"allowlist into .claude/settings.json (or [file]); it only touches",
|
|
6398
|
+
"permissions.allow and permissions.deny, backs up the original, and prints a",
|
|
6399
|
+
"diff. --from <dir> points apply at a specific artifacts folder instead of",
|
|
6400
|
+
"looking one up by project; without it, apply finds artifacts from the last",
|
|
6401
|
+
"optimize run, or generates them cold if none exist yet. --force allows",
|
|
6402
|
+
"overwriting an existing .bak backup for --replace and --apply-settings.",
|
|
6403
|
+
"",
|
|
6404
|
+
"optimize and apply need a one-time license: buy at https://costclaw.io, then",
|
|
6405
|
+
"run costclaw activate <key>. activate and deactivate move that license",
|
|
6406
|
+
"between machines. audit never needs a license.",
|
|
5679
6407
|
"",
|
|
5680
6408
|
"Everything runs locally. Nothing is uploaded. Activation is a signed license",
|
|
5681
6409
|
"key verified on this machine: there is no license server and no network call.",
|
|
@@ -5733,6 +6461,14 @@ Run: costclaw optimize
|
|
|
5733
6461
|
return;
|
|
5734
6462
|
}
|
|
5735
6463
|
if (command === "optimize") {
|
|
6464
|
+
if (args.includes("--write")) {
|
|
6465
|
+
process.stderr.write("--write moved: run costclaw apply <dir> --replace\n");
|
|
6466
|
+
process.exit(1);
|
|
6467
|
+
}
|
|
6468
|
+
if (args.includes("--apply-settings")) {
|
|
6469
|
+
process.stderr.write("--apply-settings moved: run costclaw apply <dir> --apply-settings\n");
|
|
6470
|
+
process.exit(1);
|
|
6471
|
+
}
|
|
5736
6472
|
const gate = await checkLicense();
|
|
5737
6473
|
if (!gate.ok) {
|
|
5738
6474
|
process.stderr.write(gate.message + "\n");
|
|
@@ -5742,18 +6478,61 @@ Run: costclaw optimize
|
|
|
5742
6478
|
path: getFlag(args, "--path"),
|
|
5743
6479
|
claudeMdPath: getFlag(args, "--claude-md"),
|
|
5744
6480
|
plan: planFlag(args),
|
|
5745
|
-
projectDir: getFlag(args, "--project")
|
|
6481
|
+
projectDir: getFlag(args, "--project"),
|
|
5746
6482
|
out: getFlag(args, "--out"),
|
|
5747
|
-
|
|
6483
|
+
limit: Number(getFlag(args, "--limit")) || void 0,
|
|
5748
6484
|
force: args.includes("--force"),
|
|
5749
6485
|
dashboard: !args.includes("--no-dashboard"),
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
|
|
6486
|
+
serve: !args.includes("--no-serve"),
|
|
6487
|
+
version: cliVersion()
|
|
5753
6488
|
});
|
|
5754
6489
|
process.stdout.write(output + "\n");
|
|
5755
6490
|
return;
|
|
5756
6491
|
}
|
|
6492
|
+
if (command === "apply") {
|
|
6493
|
+
const gate = await checkLicense();
|
|
6494
|
+
if (!gate.ok) {
|
|
6495
|
+
process.stderr.write(gate.message + "\n");
|
|
6496
|
+
process.exit(1);
|
|
6497
|
+
}
|
|
6498
|
+
const flags = parseApplyFlags(args);
|
|
6499
|
+
const root = defaultOptimizeRoot(homedir7());
|
|
6500
|
+
let artifactsDir = flags.from;
|
|
6501
|
+
if (!artifactsDir) {
|
|
6502
|
+
const manifest = await readManifest(root);
|
|
6503
|
+
artifactsDir = manifest ? findEntry(manifest, flags.projectDir)?.artifactsDir : void 0;
|
|
6504
|
+
}
|
|
6505
|
+
if (!artifactsDir) {
|
|
6506
|
+
const run = await runOptimize({
|
|
6507
|
+
projectDir: flags.projectDir,
|
|
6508
|
+
serve: false,
|
|
6509
|
+
dashboard: false,
|
|
6510
|
+
version: cliVersion()
|
|
6511
|
+
});
|
|
6512
|
+
artifactsDir = findEntry(run.manifest, flags.projectDir)?.artifactsDir;
|
|
6513
|
+
}
|
|
6514
|
+
if (!artifactsDir) {
|
|
6515
|
+
throw new Error(`Could not find or generate artifacts for ${flags.projectDir}`);
|
|
6516
|
+
}
|
|
6517
|
+
const outcome = await runApply({
|
|
6518
|
+
projectDir: flags.projectDir,
|
|
6519
|
+
mode: flags.mode,
|
|
6520
|
+
artifactsDir,
|
|
6521
|
+
applySettings: flags.applySettings,
|
|
6522
|
+
applySettingsPath: flags.applySettingsPath,
|
|
6523
|
+
force: flags.force
|
|
6524
|
+
});
|
|
6525
|
+
process.stdout.write(outcome.lines.join("\n") + "\n");
|
|
6526
|
+
if (flags.mode === "include") {
|
|
6527
|
+
const manifest = await readManifest(root);
|
|
6528
|
+
const entry = manifest ? findEntry(manifest, flags.projectDir) : void 0;
|
|
6529
|
+
if (manifest && entry) {
|
|
6530
|
+
entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
6531
|
+
await writeManifest(root, manifest);
|
|
6532
|
+
}
|
|
6533
|
+
}
|
|
6534
|
+
return;
|
|
6535
|
+
}
|
|
5757
6536
|
process.stderr.write(helpText() + "\n");
|
|
5758
6537
|
process.exit(command ? 1 : 0);
|
|
5759
6538
|
}
|
|
@@ -5768,6 +6547,7 @@ export {
|
|
|
5768
6547
|
cliVersion,
|
|
5769
6548
|
helpText,
|
|
5770
6549
|
isHelpRequest,
|
|
6550
|
+
parseApplyFlags,
|
|
5771
6551
|
parseAuditFlags,
|
|
5772
6552
|
parseBadgeFlags,
|
|
5773
6553
|
planFlag
|