costclaw 0.10.0 → 0.12.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 +326 -303
- package/dist/index.js +855 -127
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -833,7 +833,7 @@ function analyzeClaudeMd(text2) {
|
|
|
833
833
|
};
|
|
834
834
|
}
|
|
835
835
|
const chars = raw.length;
|
|
836
|
-
const
|
|
836
|
+
const estTokens2 = Math.round(chars / 4);
|
|
837
837
|
const headings = (raw.match(/^#{1,6}\s/gm) || []).length;
|
|
838
838
|
const bullets = (raw.match(/^\s*[-*]\s/gm) || []).length;
|
|
839
839
|
const dateMarkers = (raw.match(/\b\d{4}-\d{2}-\d{2}\b/g) || []).length;
|
|
@@ -842,7 +842,7 @@ function analyzeClaudeMd(text2) {
|
|
|
842
842
|
return {
|
|
843
843
|
present: true,
|
|
844
844
|
chars,
|
|
845
|
-
estTokens,
|
|
845
|
+
estTokens: estTokens2,
|
|
846
846
|
headings,
|
|
847
847
|
bullets,
|
|
848
848
|
volatileMarkers,
|
|
@@ -1888,6 +1888,7 @@ function carriedIntro(currentClaudeMd) {
|
|
|
1888
1888
|
}
|
|
1889
1889
|
return { title, intro, introDropped };
|
|
1890
1890
|
}
|
|
1891
|
+
var SECTION_HEADING_RE = /^##\s+(.+?)\s*$/;
|
|
1891
1892
|
function parseSections(md) {
|
|
1892
1893
|
const lines = md.split(/\r?\n/);
|
|
1893
1894
|
const sections = [];
|
|
@@ -1902,7 +1903,7 @@ function parseSections(md) {
|
|
|
1902
1903
|
};
|
|
1903
1904
|
};
|
|
1904
1905
|
for (const line of lines) {
|
|
1905
|
-
const m = line.match(
|
|
1906
|
+
const m = line.match(SECTION_HEADING_RE);
|
|
1906
1907
|
if (m) {
|
|
1907
1908
|
if (current) sections.push(finish(current));
|
|
1908
1909
|
current = { heading: m[1], body: [] };
|
|
@@ -3057,6 +3058,463 @@ var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
|
3057
3058
|
var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
3058
3059
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
3059
3060
|
|
|
3061
|
+
// ../../packages/engine/src/review.ts
|
|
3062
|
+
var IMPORT_LINE = "@.claude/costclaw.md";
|
|
3063
|
+
function estTokens(text2) {
|
|
3064
|
+
return Math.round(text2.length / 4);
|
|
3065
|
+
}
|
|
3066
|
+
function num4(n) {
|
|
3067
|
+
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3068
|
+
}
|
|
3069
|
+
function normalize(line) {
|
|
3070
|
+
return line.trim().replace(/\s+/g, " ").toLowerCase();
|
|
3071
|
+
}
|
|
3072
|
+
function slugifyHeading(heading) {
|
|
3073
|
+
const slug = heading.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
3074
|
+
return slug.length > 0 ? slug : "notes";
|
|
3075
|
+
}
|
|
3076
|
+
function indexSections(lines) {
|
|
3077
|
+
const top = [];
|
|
3078
|
+
const sections = [];
|
|
3079
|
+
let current = null;
|
|
3080
|
+
for (let i = 0; i < lines.length; i++) {
|
|
3081
|
+
const line = lines[i] ?? "";
|
|
3082
|
+
const m = line.match(SECTION_HEADING_RE);
|
|
3083
|
+
if (m) {
|
|
3084
|
+
current = { heading: (m[1] ?? "").trim(), headingLine: i, bodyLines: [] };
|
|
3085
|
+
sections.push(current);
|
|
3086
|
+
} else if (current) {
|
|
3087
|
+
current.bodyLines.push(i);
|
|
3088
|
+
} else {
|
|
3089
|
+
top.push(i);
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
return { top, sections };
|
|
3093
|
+
}
|
|
3094
|
+
function bodyText(lines, idx) {
|
|
3095
|
+
return idx.map((i) => lines[i] ?? "").join("\n").trim();
|
|
3096
|
+
}
|
|
3097
|
+
var ReviewBuilder = class {
|
|
3098
|
+
marks = /* @__PURE__ */ new Map();
|
|
3099
|
+
changes = [];
|
|
3100
|
+
adds = [];
|
|
3101
|
+
seq = 0;
|
|
3102
|
+
nextId(prefix) {
|
|
3103
|
+
this.seq += 1;
|
|
3104
|
+
return `${prefix}-${this.seq}`;
|
|
3105
|
+
}
|
|
3106
|
+
/** First mark on a line wins, so two rules never claim the same line. */
|
|
3107
|
+
mark(indexes, mark, reason, changeId) {
|
|
3108
|
+
for (const i of indexes) if (!this.marks.has(i)) this.marks.set(i, { mark, reason, changeId });
|
|
3109
|
+
}
|
|
3110
|
+
change(c) {
|
|
3111
|
+
this.changes.push({ ...c, instruction: sanitizeText(c.instruction), reason: sanitizeText(c.reason) });
|
|
3112
|
+
}
|
|
3113
|
+
/** An add carries its own lines: there is no existing line to mark. */
|
|
3114
|
+
add(change) {
|
|
3115
|
+
this.change(change);
|
|
3116
|
+
for (const line of (change.text ?? "").replace(/\s+$/, "").split("\n")) {
|
|
3117
|
+
this.adds.push({ text: line, mark: "add", reason: change.reason, changeId: change.id });
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
};
|
|
3121
|
+
function markGeneratorComments(lines, b) {
|
|
3122
|
+
for (let i = 0; i < lines.length; i++) {
|
|
3123
|
+
if (!/<!--\s*costclaw/i.test(lines[i] ?? "")) continue;
|
|
3124
|
+
const block = [];
|
|
3125
|
+
let j = i;
|
|
3126
|
+
for (; j < lines.length; j++) {
|
|
3127
|
+
block.push(j);
|
|
3128
|
+
if ((lines[j] ?? "").includes("-->")) break;
|
|
3129
|
+
}
|
|
3130
|
+
const id = b.nextId("gen");
|
|
3131
|
+
b.mark(block, "remove", "generator comment", id);
|
|
3132
|
+
b.change({
|
|
3133
|
+
id,
|
|
3134
|
+
kind: "remove",
|
|
3135
|
+
heading: "(top)",
|
|
3136
|
+
instruction: "Delete this generator comment block: costclaw rewrites it on every run, so it steers nothing.",
|
|
3137
|
+
reason: "a generated marker block, not a rule",
|
|
3138
|
+
tokens: estTokens(block.map((k) => lines[k] ?? "").join("\n"))
|
|
3139
|
+
});
|
|
3140
|
+
i = j;
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
var VOLATILE_WHY = "dated or status text busts the prompt cache on every edit";
|
|
3144
|
+
function markVolatile(lines, sections, b, destDir) {
|
|
3145
|
+
for (const s of sections) {
|
|
3146
|
+
const dest = `${destDir}${slugifyHeading(s.heading)}.md`;
|
|
3147
|
+
if (VOLATILE_HEADING.test(s.heading)) {
|
|
3148
|
+
const id2 = b.nextId("vol");
|
|
3149
|
+
b.mark([s.headingLine, ...s.bodyLines], "move", "status section", id2);
|
|
3150
|
+
b.change({
|
|
3151
|
+
id: id2,
|
|
3152
|
+
kind: "move",
|
|
3153
|
+
heading: s.heading,
|
|
3154
|
+
instruction: `Move the whole "${s.heading}" section to ${dest} and link it from the file it left.`,
|
|
3155
|
+
reason: VOLATILE_WHY,
|
|
3156
|
+
tokens: estTokens(bodyText(lines, s.bodyLines)),
|
|
3157
|
+
destination: dest
|
|
3158
|
+
});
|
|
3159
|
+
continue;
|
|
3160
|
+
}
|
|
3161
|
+
const dated = s.bodyLines.filter((i) => VOLATILE_MARKER.test(lines[i] ?? ""));
|
|
3162
|
+
if (dated.length === 0) continue;
|
|
3163
|
+
const id = b.nextId("dated");
|
|
3164
|
+
b.mark(dated, "move", "dated line", id);
|
|
3165
|
+
b.change({
|
|
3166
|
+
id,
|
|
3167
|
+
kind: "move",
|
|
3168
|
+
heading: s.heading,
|
|
3169
|
+
instruction: `Move the ${num4(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
|
|
3170
|
+
reason: VOLATILE_WHY,
|
|
3171
|
+
tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
|
|
3172
|
+
destination: dest
|
|
3173
|
+
});
|
|
3174
|
+
}
|
|
3175
|
+
}
|
|
3176
|
+
function importAdd() {
|
|
3177
|
+
return {
|
|
3178
|
+
heading: "(top)",
|
|
3179
|
+
text: `${IMPORT_LINE}
|
|
3180
|
+
`,
|
|
3181
|
+
reason: "the generated sections live in their own file, imported once"
|
|
3182
|
+
};
|
|
3183
|
+
}
|
|
3184
|
+
function tokenDisciplineAdd() {
|
|
3185
|
+
return {
|
|
3186
|
+
heading: "Token discipline",
|
|
3187
|
+
text: [
|
|
3188
|
+
"## Token discipline",
|
|
3189
|
+
"",
|
|
3190
|
+
"- State a stop condition before any search or edit loop, then stop at it.",
|
|
3191
|
+
"- Read the narrowest thing that answers the question: a range, not a file;",
|
|
3192
|
+
" one file, not a tree.",
|
|
3193
|
+
"- Do not re-read a file you just wrote.",
|
|
3194
|
+
""
|
|
3195
|
+
].join("\n"),
|
|
3196
|
+
reason: "the audit found tool loops running far past a sane bound"
|
|
3197
|
+
};
|
|
3198
|
+
}
|
|
3199
|
+
function modelRoutingAdd() {
|
|
3200
|
+
return {
|
|
3201
|
+
heading: "Model routing",
|
|
3202
|
+
text: [
|
|
3203
|
+
"## Model routing",
|
|
3204
|
+
"",
|
|
3205
|
+
"- Short, mechanical tasks (a lookup, a rename, a formatting pass) run on the",
|
|
3206
|
+
" cheap model. Premium models are for hard reasoning and final review.",
|
|
3207
|
+
"- Say which model a task needs when it is not obvious.",
|
|
3208
|
+
""
|
|
3209
|
+
].join("\n"),
|
|
3210
|
+
reason: "the audit found short, trivial sessions running on a premium model"
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
function sessionHygieneAdd() {
|
|
3214
|
+
return {
|
|
3215
|
+
heading: "Session hygiene",
|
|
3216
|
+
text: [
|
|
3217
|
+
"## Session hygiene",
|
|
3218
|
+
"",
|
|
3219
|
+
"- Run /compact before the context outgrows the cache, not after.",
|
|
3220
|
+
"- Run /clear between unrelated tasks: a fresh session is cheaper than a",
|
|
3221
|
+
" long one carrying a dead context.",
|
|
3222
|
+
""
|
|
3223
|
+
].join("\n"),
|
|
3224
|
+
reason: "the audit found long sessions whose per-turn cache decayed"
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
function stopConditionsAdd(tools) {
|
|
3228
|
+
return {
|
|
3229
|
+
heading: "Stop conditions",
|
|
3230
|
+
text: [
|
|
3231
|
+
"## Stop conditions",
|
|
3232
|
+
"",
|
|
3233
|
+
`- Before a loop with ${tools.join(", ")}, state the bound out loud (how many`,
|
|
3234
|
+
" calls, or what result ends it), then honor it.",
|
|
3235
|
+
"- If the bound is hit without an answer, stop and report what is missing",
|
|
3236
|
+
" instead of widening the search.",
|
|
3237
|
+
""
|
|
3238
|
+
].join("\n"),
|
|
3239
|
+
reason: `the audit found ${tools.join(", ")} firing far past a sane loop bound`
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
function hasHeading(sections, heading) {
|
|
3243
|
+
return sections.some((s) => normalize(s.heading) === normalize(heading));
|
|
3244
|
+
}
|
|
3245
|
+
function applyAdds(blocks, sections, lines, b) {
|
|
3246
|
+
for (const block of blocks) {
|
|
3247
|
+
if (block.heading === "(top)") {
|
|
3248
|
+
if (lines.some((l) => l.trim() === block.text.trim())) continue;
|
|
3249
|
+
} else if (hasHeading(sections, block.heading)) continue;
|
|
3250
|
+
const id = b.nextId("add");
|
|
3251
|
+
b.add({
|
|
3252
|
+
id,
|
|
3253
|
+
kind: "add",
|
|
3254
|
+
heading: block.heading,
|
|
3255
|
+
instruction: block.heading === "(top)" ? `Add the line \`${IMPORT_LINE}\` to CLAUDE.md (\`npx costclaw apply <dir>\` does it for you).` : `Add this "${block.heading}" section at the end of the file, exactly as written.`,
|
|
3256
|
+
reason: block.reason,
|
|
3257
|
+
tokens: estTokens(block.text),
|
|
3258
|
+
text: block.text
|
|
3259
|
+
});
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
function assemble(scope, label, lines, b, tokens, importCount = 0) {
|
|
3263
|
+
const reviewed = lines.map((text2, i) => {
|
|
3264
|
+
const m = b.marks.get(i);
|
|
3265
|
+
return m ? { text: text2, mark: m.mark, reason: m.reason, changeId: m.changeId } : { text: text2, mark: "keep" };
|
|
3266
|
+
});
|
|
3267
|
+
const sum = (kind) => b.changes.filter((c) => c.kind === kind).reduce((s, c) => s + c.tokens, 0);
|
|
3268
|
+
const total = tokens.file + tokens.imports;
|
|
3269
|
+
return {
|
|
3270
|
+
scope,
|
|
3271
|
+
label,
|
|
3272
|
+
missing: false,
|
|
3273
|
+
lines: [...reviewed, ...b.adds],
|
|
3274
|
+
changes: b.changes,
|
|
3275
|
+
tokens: { ...tokens, total, afterChanges: Math.max(0, total - sum("remove") - sum("move") + sum("add")) },
|
|
3276
|
+
importCount
|
|
3277
|
+
};
|
|
3278
|
+
}
|
|
3279
|
+
function reviewProjectClaudeMd(input) {
|
|
3280
|
+
const has = (id) => input.report.findings.some((f) => f.ruleId === id);
|
|
3281
|
+
const blocks = [importAdd()];
|
|
3282
|
+
if (has("HEAVY_TOOL_LOOPS") || has("REDUNDANT_TARGET_THRASH")) blocks.push(tokenDisciplineAdd());
|
|
3283
|
+
if (input.text === null || input.text.trim() === "") {
|
|
3284
|
+
const b2 = new ReviewBuilder();
|
|
3285
|
+
applyAdds(blocks, [], [], b2);
|
|
3286
|
+
return { ...assemble("project", input.label, [], b2, { file: 0, imports: 0 }), missing: true };
|
|
3287
|
+
}
|
|
3288
|
+
const lines = input.text.split(/\r?\n/);
|
|
3289
|
+
const { sections } = indexSections(lines);
|
|
3290
|
+
const b = new ReviewBuilder();
|
|
3291
|
+
const includeLines = new Set(input.includeMd.split(/\r?\n/).map(normalize).filter((l) => l.length > 0));
|
|
3292
|
+
for (const s of sections) {
|
|
3293
|
+
if (!INCLUDE_HEADING.some((re) => re.test(s.heading))) continue;
|
|
3294
|
+
const content = s.bodyLines.filter((i) => (lines[i] ?? "").trim().length > 0);
|
|
3295
|
+
if (content.length === 0) continue;
|
|
3296
|
+
const covered = content.filter((i) => includeLines.has(normalize(lines[i] ?? "")));
|
|
3297
|
+
if (covered.length === 0) continue;
|
|
3298
|
+
const id = b.nextId("inc");
|
|
3299
|
+
const all = covered.length === content.length;
|
|
3300
|
+
const kept = content.length - covered.length;
|
|
3301
|
+
b.mark(all ? [s.headingLine, ...s.bodyLines] : covered, "remove", "covered by the include", id);
|
|
3302
|
+
b.change({
|
|
3303
|
+
id,
|
|
3304
|
+
kind: "remove",
|
|
3305
|
+
heading: s.heading,
|
|
3306
|
+
instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${num4(covered.length)} covered ${covered.length === 1 ? "line" : "lines"} under "${s.heading}" and keep these ${num4(kept)} lines under the heading: the include ${IMPORT_LINE} does not have them.`,
|
|
3307
|
+
reason: `${num4(covered.length)} of ${num4(content.length)} lines appear verbatim in the generated include`,
|
|
3308
|
+
tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
|
|
3309
|
+
});
|
|
3310
|
+
}
|
|
3311
|
+
const globals = new Map(input.globalSections.map((s) => [normalize(s.heading), normalize(s.body)]));
|
|
3312
|
+
for (const s of sections) {
|
|
3313
|
+
if (b.marks.has(s.headingLine)) continue;
|
|
3314
|
+
const g = globals.get(normalize(s.heading));
|
|
3315
|
+
if (g === void 0 || g !== normalize(bodyText(lines, s.bodyLines))) continue;
|
|
3316
|
+
const id = b.nextId("dup");
|
|
3317
|
+
b.mark([s.headingLine, ...s.bodyLines], "remove", "duplicates the global file", id);
|
|
3318
|
+
b.change({
|
|
3319
|
+
id,
|
|
3320
|
+
kind: "remove",
|
|
3321
|
+
heading: s.heading,
|
|
3322
|
+
instruction: `Delete the "${s.heading}" section from this file: it is identical to the one in the global CLAUDE.md.`,
|
|
3323
|
+
reason: "the global CLAUDE.md is loaded in this project too, so this copy is paid twice",
|
|
3324
|
+
tokens: estTokens(bodyText(lines, s.bodyLines))
|
|
3325
|
+
});
|
|
3326
|
+
}
|
|
3327
|
+
markGeneratorComments(lines, b);
|
|
3328
|
+
markVolatile(lines, sections, b, "docs/");
|
|
3329
|
+
applyAdds(blocks, sections, lines, b);
|
|
3330
|
+
return assemble("project", input.label, lines, b, { file: estTokens(input.text.trim()), imports: 0 });
|
|
3331
|
+
}
|
|
3332
|
+
var IMPORT_WEIGHT_LIMIT = 6e3;
|
|
3333
|
+
var SLUG_MIN = 4;
|
|
3334
|
+
function paragraphs(lines, idx) {
|
|
3335
|
+
const out = [];
|
|
3336
|
+
let cur = [];
|
|
3337
|
+
for (const i of idx) {
|
|
3338
|
+
if ((lines[i] ?? "").trim() === "") {
|
|
3339
|
+
if (cur.length > 0) out.push(cur);
|
|
3340
|
+
cur = [];
|
|
3341
|
+
} else cur.push(i);
|
|
3342
|
+
}
|
|
3343
|
+
if (cur.length > 0) out.push(cur);
|
|
3344
|
+
return out;
|
|
3345
|
+
}
|
|
3346
|
+
function escapeRe(text2) {
|
|
3347
|
+
return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3348
|
+
}
|
|
3349
|
+
function namedSlugs(text2, slugs) {
|
|
3350
|
+
const found = [];
|
|
3351
|
+
for (const slug of slugs) {
|
|
3352
|
+
if (slug.length < SLUG_MIN || found.includes(slug)) continue;
|
|
3353
|
+
const re = new RegExp(`(^|[^a-z0-9])${escapeRe(slug)}([^a-z0-9]|$)`, "i");
|
|
3354
|
+
if (re.test(text2)) found.push(slug);
|
|
3355
|
+
}
|
|
3356
|
+
return found;
|
|
3357
|
+
}
|
|
3358
|
+
function reviewGlobalClaudeMd(input) {
|
|
3359
|
+
const has = (id) => input.report.findings.some((f) => f.ruleId === id);
|
|
3360
|
+
const heavyTools = [...new Set(input.report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS").map((f) => String(f.evidence?.["tool"] ?? "")).filter((t) => t.length > 0))].sort();
|
|
3361
|
+
const blocks = [];
|
|
3362
|
+
if (has("HEAVY_TOOL_LOOPS") || has("REDUNDANT_TARGET_THRASH")) blocks.push(tokenDisciplineAdd());
|
|
3363
|
+
if (has("MODEL_MISROUTE")) blocks.push(modelRoutingAdd());
|
|
3364
|
+
if (has("MARATHON_SESSION")) blocks.push(sessionHygieneAdd());
|
|
3365
|
+
if (heavyTools.length > 0) blocks.push(stopConditionsAdd(heavyTools));
|
|
3366
|
+
const importTokens = input.imports.reduce((s, i) => s + estTokens(i.text), 0);
|
|
3367
|
+
if (input.text === null || input.text.trim() === "") {
|
|
3368
|
+
const b2 = new ReviewBuilder();
|
|
3369
|
+
applyAdds(blocks, [], [], b2);
|
|
3370
|
+
return {
|
|
3371
|
+
...assemble("global", input.label, [], b2, { file: 0, imports: importTokens }, input.imports.length),
|
|
3372
|
+
missing: true
|
|
3373
|
+
};
|
|
3374
|
+
}
|
|
3375
|
+
const lines = input.text.split(/\r?\n/);
|
|
3376
|
+
const { top, sections } = indexSections(lines);
|
|
3377
|
+
const b = new ReviewBuilder();
|
|
3378
|
+
markGeneratorComments(lines, b);
|
|
3379
|
+
markVolatile(lines, sections, b, "~/.claude/notes/");
|
|
3380
|
+
const blocksToScan = [
|
|
3381
|
+
{ heading: "(top)", idx: top },
|
|
3382
|
+
...sections.map((s) => ({ heading: s.heading, idx: s.bodyLines }))
|
|
3383
|
+
];
|
|
3384
|
+
for (const block of blocksToScan) {
|
|
3385
|
+
for (const para of paragraphs(lines, block.idx)) {
|
|
3386
|
+
if (para.some((i) => b.marks.has(i))) continue;
|
|
3387
|
+
const text2 = para.map((i) => lines[i] ?? "").join("\n");
|
|
3388
|
+
const named = namedSlugs(text2, input.projectSlugs);
|
|
3389
|
+
if (named.length !== 1) continue;
|
|
3390
|
+
const slug = named[0] ?? "";
|
|
3391
|
+
const dest = `${slug}/CLAUDE.md`;
|
|
3392
|
+
const id = b.nextId("one");
|
|
3393
|
+
b.mark(para, "move", `only about ${slug}`, id);
|
|
3394
|
+
b.change({
|
|
3395
|
+
id,
|
|
3396
|
+
kind: "move",
|
|
3397
|
+
heading: block.heading,
|
|
3398
|
+
instruction: `Move this paragraph to ${dest}: it names only ${slug}.`,
|
|
3399
|
+
reason: "a single project's rule in the global file is loaded on every turn of every other project",
|
|
3400
|
+
tokens: estTokens(text2),
|
|
3401
|
+
destination: dest
|
|
3402
|
+
});
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
const byBody = /* @__PURE__ */ new Map();
|
|
3406
|
+
for (const s of input.projectSections) {
|
|
3407
|
+
const key = `${normalize(s.heading)}|${normalize(s.body)}`;
|
|
3408
|
+
byBody.set(key, [...byBody.get(key) ?? [], s.label]);
|
|
3409
|
+
}
|
|
3410
|
+
for (const s of sections) {
|
|
3411
|
+
const labels = byBody.get(`${normalize(s.heading)}|${normalize(bodyText(lines, s.bodyLines))}`);
|
|
3412
|
+
if (!labels || labels.length === 0) continue;
|
|
3413
|
+
const id = b.nextId("proj-dup");
|
|
3414
|
+
b.change({
|
|
3415
|
+
id,
|
|
3416
|
+
kind: "remove",
|
|
3417
|
+
heading: s.heading,
|
|
3418
|
+
instruction: `Keep this section here and delete the identical copy from ${labels.join(", ")}.`,
|
|
3419
|
+
reason: "the global file is loaded in those projects too, so the copy is paid twice",
|
|
3420
|
+
tokens: 0
|
|
3421
|
+
});
|
|
3422
|
+
}
|
|
3423
|
+
const heaviest = [...input.imports].sort((x, y) => estTokens(y.text) - estTokens(x.text))[0];
|
|
3424
|
+
const total = estTokens(input.text.trim()) + importTokens;
|
|
3425
|
+
if (total > IMPORT_WEIGHT_LIMIT && heaviest) {
|
|
3426
|
+
const id = b.nextId("weight");
|
|
3427
|
+
b.change({
|
|
3428
|
+
id,
|
|
3429
|
+
kind: "move",
|
|
3430
|
+
heading: "(top)",
|
|
3431
|
+
instruction: `Split ${heaviest.label} (about ${num4(estTokens(heaviest.text))} tokens) into docs the agent opens on demand, and keep only the rules that prevent mistakes.`,
|
|
3432
|
+
reason: `this file plus its imports is about ${num4(total)} tokens on every turn of every project`,
|
|
3433
|
+
tokens: 0,
|
|
3434
|
+
destination: "on-demand docs"
|
|
3435
|
+
});
|
|
3436
|
+
}
|
|
3437
|
+
applyAdds(blocks, sections, lines, b);
|
|
3438
|
+
return assemble(
|
|
3439
|
+
"global",
|
|
3440
|
+
input.label,
|
|
3441
|
+
lines,
|
|
3442
|
+
b,
|
|
3443
|
+
{ file: estTokens(input.text.trim()), imports: importTokens },
|
|
3444
|
+
input.imports.length
|
|
3445
|
+
);
|
|
3446
|
+
}
|
|
3447
|
+
function changeList(review) {
|
|
3448
|
+
if (review.changes.length === 0) return ["No changes proposed."];
|
|
3449
|
+
const out = [];
|
|
3450
|
+
review.changes.forEach((c, i) => {
|
|
3451
|
+
const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
|
|
3452
|
+
const weight = c.tokens > 0 ? `, about ${num4(c.tokens)} tokens` : "";
|
|
3453
|
+
out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
|
|
3454
|
+
out.push(` Why: ${c.reason}`);
|
|
3455
|
+
if (c.destination) out.push(` Destination: ${c.destination}`);
|
|
3456
|
+
if (c.text) {
|
|
3457
|
+
out.push("", " Insert exactly this block:", "", " ```markdown");
|
|
3458
|
+
for (const line of c.text.replace(/\s+$/, "").split("\n")) out.push(` ${line}`);
|
|
3459
|
+
out.push(" ```");
|
|
3460
|
+
}
|
|
3461
|
+
out.push("");
|
|
3462
|
+
});
|
|
3463
|
+
return out;
|
|
3464
|
+
}
|
|
3465
|
+
function tokenTarget(review, what) {
|
|
3466
|
+
return `- ${what}: about ${num4(review.tokens.afterChanges)} tokens per turn after these changes (about ${num4(review.tokens.total)} now).`;
|
|
3467
|
+
}
|
|
3468
|
+
function buildUpgradeAll(input) {
|
|
3469
|
+
const parts = [];
|
|
3470
|
+
parts.push("# CostClaw setup upgrade");
|
|
3471
|
+
parts.push([
|
|
3472
|
+
"You are Claude Code. costclaw generated this work order locally from an audit",
|
|
3473
|
+
"of real usage logs plus a scan of each project; every change below is grounded",
|
|
3474
|
+
"in that evidence. Work through the sections in order and report what changed.",
|
|
3475
|
+
`Generated ${input.generatedAt}.`
|
|
3476
|
+
].join("\n"));
|
|
3477
|
+
parts.push([
|
|
3478
|
+
"## Ground rules",
|
|
3479
|
+
"",
|
|
3480
|
+
"- Never invent project facts. When a merge choice is unclear, ask.",
|
|
3481
|
+
"- Show a diff before writing any human-written file, and back it up first.",
|
|
3482
|
+
"- Move content, do not delete it: history goes to docs/, rules stay.",
|
|
3483
|
+
'- Keep every file lean by the test "would removing this make the agent make a',
|
|
3484
|
+
' mistake?" There is no target number of lines.'
|
|
3485
|
+
].join("\n"));
|
|
3486
|
+
parts.push([
|
|
3487
|
+
`## Global: ${input.global.path}`,
|
|
3488
|
+
"",
|
|
3489
|
+
input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${num4(input.global.changes.length)} ${input.global.changes.length === 1 ? "change" : "changes"} proposed.`,
|
|
3490
|
+
"",
|
|
3491
|
+
...changeList(input.global)
|
|
3492
|
+
].join("\n"));
|
|
3493
|
+
for (const p of input.projects) {
|
|
3494
|
+
parts.push([
|
|
3495
|
+
`## Project: ${p.slug} (${p.projectDir})`,
|
|
3496
|
+
"",
|
|
3497
|
+
`First run \`${p.applyCommand}\`: it writes the generated sections to`,
|
|
3498
|
+
"`.claude/costclaw.md` and adds one `@.claude/costclaw.md` import line, leaving",
|
|
3499
|
+
"every line you wrote alone. Then, in that project's CLAUDE.md:",
|
|
3500
|
+
"",
|
|
3501
|
+
...changeList(p.review)
|
|
3502
|
+
].join("\n"));
|
|
3503
|
+
}
|
|
3504
|
+
const verify = ["## Verify", ""];
|
|
3505
|
+
verify.push("- Every section marked remove appears exactly once across the file and its include.");
|
|
3506
|
+
verify.push("- Every moved block exists at its destination and is linked from the file it left.");
|
|
3507
|
+
verify.push("- Every added block appears once, with no duplicate heading.");
|
|
3508
|
+
verify.push(tokenTarget(input.global, input.global.path));
|
|
3509
|
+
for (const p of input.projects) verify.push(tokenTarget(p.review, `${p.slug}/CLAUDE.md`));
|
|
3510
|
+
verify.push(
|
|
3511
|
+
'- After about a week of normal usage, run `npx costclaw audit`: the "Since optimize"',
|
|
3512
|
+
" line measures the cache-hit movement these changes are meant to produce."
|
|
3513
|
+
);
|
|
3514
|
+
parts.push(verify.join("\n"));
|
|
3515
|
+
return sanitizeText(parts.join("\n\n").trimEnd() + "\n");
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3060
3518
|
// src/audit-command.ts
|
|
3061
3519
|
import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
3062
3520
|
import { join as join5, resolve } from "path";
|
|
@@ -4127,19 +4585,94 @@ async function deactivateLicense(opts = {}) {
|
|
|
4127
4585
|
await clearStoredLicense(configDir);
|
|
4128
4586
|
}
|
|
4129
4587
|
|
|
4588
|
+
// src/plan-prompt.ts
|
|
4589
|
+
import { createInterface } from "readline/promises";
|
|
4590
|
+
var PLAN_PROMPT_LINES = [
|
|
4591
|
+
"How do you pay for Claude Code? This decides whether the report talks in",
|
|
4592
|
+
"dollars or in rate-limit headroom.",
|
|
4593
|
+
"",
|
|
4594
|
+
" 1) API, pay per token",
|
|
4595
|
+
" 2) Pro subscription",
|
|
4596
|
+
" 3) Max 5x subscription",
|
|
4597
|
+
" 4) Max 20x subscription",
|
|
4598
|
+
""
|
|
4599
|
+
];
|
|
4600
|
+
var BY_NUMBER = ["api", "pro", "max5x", "max20x"];
|
|
4601
|
+
function isCI(env) {
|
|
4602
|
+
const value = env["CI"];
|
|
4603
|
+
if (!value) return false;
|
|
4604
|
+
return value !== "false" && value !== "0";
|
|
4605
|
+
}
|
|
4606
|
+
function shouldAskForPlan(gate) {
|
|
4607
|
+
if (gate.flag || gate.savedPlan) return false;
|
|
4608
|
+
if (gate.json) return false;
|
|
4609
|
+
if (!gate.stdinIsTTY || !gate.stdoutIsTTY) return false;
|
|
4610
|
+
return !isCI(gate.env);
|
|
4611
|
+
}
|
|
4612
|
+
function parsePlan(answer) {
|
|
4613
|
+
const value = answer.trim().toLowerCase();
|
|
4614
|
+
if (!value) return void 0;
|
|
4615
|
+
const index = Number(value);
|
|
4616
|
+
if (Number.isInteger(index) && index >= 1 && index <= BY_NUMBER.length) return BY_NUMBER[index - 1];
|
|
4617
|
+
return PLANS.includes(value) ? value : void 0;
|
|
4618
|
+
}
|
|
4619
|
+
async function askForPlan(ask, write) {
|
|
4620
|
+
write(PLAN_PROMPT_LINES.join("\n") + "\n");
|
|
4621
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
4622
|
+
let answer;
|
|
4623
|
+
try {
|
|
4624
|
+
answer = await ask();
|
|
4625
|
+
} catch {
|
|
4626
|
+
return void 0;
|
|
4627
|
+
}
|
|
4628
|
+
const plan = parsePlan(answer);
|
|
4629
|
+
if (plan) return plan;
|
|
4630
|
+
if (attempt === 0) write("Pick 1, 2, 3 or 4.\n");
|
|
4631
|
+
}
|
|
4632
|
+
return void 0;
|
|
4633
|
+
}
|
|
4634
|
+
async function askForPlanOnStdin() {
|
|
4635
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
4636
|
+
try {
|
|
4637
|
+
return await askForPlan(() => rl.question("Plan [1-4]: "), (text2) => process.stdout.write(text2));
|
|
4638
|
+
} finally {
|
|
4639
|
+
rl.close();
|
|
4640
|
+
}
|
|
4641
|
+
}
|
|
4642
|
+
|
|
4130
4643
|
// src/audit-command.ts
|
|
4131
|
-
async function resolvePlan(configDir, flag) {
|
|
4132
|
-
|
|
4644
|
+
async function resolvePlan(configDir, flag, ask) {
|
|
4645
|
+
const persist = async (plan) => {
|
|
4133
4646
|
try {
|
|
4134
|
-
await saveCliConfig(configDir, { plan
|
|
4647
|
+
await saveCliConfig(configDir, { plan });
|
|
4135
4648
|
} catch (err) {
|
|
4136
4649
|
process.stderr.write(`Could not save the plan setting: ${err instanceof Error ? err.message : String(err)}
|
|
4137
4650
|
`);
|
|
4138
4651
|
}
|
|
4652
|
+
};
|
|
4653
|
+
if (flag) {
|
|
4654
|
+
await persist(flag);
|
|
4139
4655
|
return { plan: flag, planSource: "flag" };
|
|
4140
4656
|
}
|
|
4141
4657
|
const saved = (await readCliConfig(configDir)).plan;
|
|
4142
|
-
|
|
4658
|
+
if (saved) return { plan: saved, planSource: "config" };
|
|
4659
|
+
const prompt = ask?.prompt;
|
|
4660
|
+
if (prompt && shouldAskForPlan({
|
|
4661
|
+
flag,
|
|
4662
|
+
savedPlan: saved,
|
|
4663
|
+
json: ask?.json,
|
|
4664
|
+
stdinIsTTY: process.stdin.isTTY === true,
|
|
4665
|
+
stdoutIsTTY: process.stdout.isTTY === true,
|
|
4666
|
+
env: process.env
|
|
4667
|
+
})) {
|
|
4668
|
+
const answered = await prompt();
|
|
4669
|
+
if (answered) {
|
|
4670
|
+
await persist(answered);
|
|
4671
|
+
return { plan: answered, planSource: "asked" };
|
|
4672
|
+
}
|
|
4673
|
+
process.stdout.write("Assuming API rates. Rerun with --plan pro, max5x or max20x to reframe.\n\n");
|
|
4674
|
+
}
|
|
4675
|
+
return { plan: "api", planSource: "default" };
|
|
4143
4676
|
}
|
|
4144
4677
|
var DEFAULT_HTML_FILE = "costclaw-report.html";
|
|
4145
4678
|
var DEFAULT_CARD_FILE = "costclaw-card.svg";
|
|
@@ -4173,7 +4706,10 @@ async function runAudit(opts) {
|
|
|
4173
4706
|
});
|
|
4174
4707
|
const setup = await readSetup();
|
|
4175
4708
|
const configDir = join5(opts.home ?? homedir4(), ".costclaw");
|
|
4176
|
-
const { plan, planSource } = await resolvePlan(configDir, opts.plan
|
|
4709
|
+
const { plan, planSource } = await resolvePlan(configDir, opts.plan, {
|
|
4710
|
+
json: opts.json,
|
|
4711
|
+
prompt: opts.promptForPlan ?? askForPlanOnStdin
|
|
4712
|
+
});
|
|
4177
4713
|
const record = buildAudit({
|
|
4178
4714
|
logs,
|
|
4179
4715
|
claudeMd,
|
|
@@ -4227,14 +4763,40 @@ async function runAudit(opts) {
|
|
|
4227
4763
|
}
|
|
4228
4764
|
|
|
4229
4765
|
// src/optimize-command.ts
|
|
4230
|
-
import { mkdir as mkdir6, writeFile as writeFile6, readFile as
|
|
4231
|
-
import { basename as basename2, join as
|
|
4766
|
+
import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
|
|
4767
|
+
import { basename as basename2, join as join10, resolve as resolve5 } from "path";
|
|
4232
4768
|
import { homedir as homedir5 } from "os";
|
|
4233
4769
|
|
|
4770
|
+
// src/claude-md-imports.ts
|
|
4771
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
4772
|
+
import { dirname, isAbsolute, join as join6, resolve as resolve2 } from "path";
|
|
4773
|
+
var IMPORT_RE = /^@(\S+)\s*$/;
|
|
4774
|
+
async function resolveClaudeMdImports(claudeMdPath, text2, home) {
|
|
4775
|
+
const out = { imports: [], notes: [] };
|
|
4776
|
+
if (!claudeMdPath || !text2) return out;
|
|
4777
|
+
const base = dirname(resolve2(claudeMdPath));
|
|
4778
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4779
|
+
for (const line of text2.split(/\r?\n/)) {
|
|
4780
|
+
const m = line.match(IMPORT_RE);
|
|
4781
|
+
const raw = m?.[1];
|
|
4782
|
+
if (!raw) continue;
|
|
4783
|
+
const expanded = raw === "~" || raw.startsWith("~/") ? join6(home, raw.slice(1)) : raw;
|
|
4784
|
+
const full = isAbsolute(expanded) ? resolve2(expanded) : resolve2(base, expanded);
|
|
4785
|
+
if (seen.has(full)) continue;
|
|
4786
|
+
seen.add(full);
|
|
4787
|
+
try {
|
|
4788
|
+
out.imports.push({ label: full, text: await readFile5(full, "utf8") });
|
|
4789
|
+
} catch {
|
|
4790
|
+
out.notes.push(`Skipped the import ${raw}: ${full} could not be read.`);
|
|
4791
|
+
}
|
|
4792
|
+
}
|
|
4793
|
+
return out;
|
|
4794
|
+
}
|
|
4795
|
+
|
|
4234
4796
|
// src/apply-command.ts
|
|
4235
|
-
import { mkdir as mkdir4, writeFile as writeFile4, readFile as
|
|
4236
|
-
import { join as
|
|
4237
|
-
var
|
|
4797
|
+
import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
|
|
4798
|
+
import { join as join7, dirname as dirname2 } from "path";
|
|
4799
|
+
var IMPORT_LINE2 = "@.claude/costclaw.md";
|
|
4238
4800
|
var INCLUDE_REL = ".claude/costclaw.md";
|
|
4239
4801
|
var APPLY_DIR_REL = ".claude/costclaw";
|
|
4240
4802
|
var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
|
|
@@ -4249,20 +4811,20 @@ async function pathExists(p) {
|
|
|
4249
4811
|
}
|
|
4250
4812
|
}
|
|
4251
4813
|
function ensureImportLine(claudeMd) {
|
|
4252
|
-
if (claudeMd === null) return { text: `${
|
|
4814
|
+
if (claudeMd === null) return { text: `${IMPORT_LINE2}
|
|
4253
4815
|
`, added: true };
|
|
4254
|
-
const has = claudeMd.split(/\r?\n/).some((l) => l.trim() ===
|
|
4816
|
+
const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE2);
|
|
4255
4817
|
if (has) return { text: claudeMd, added: false };
|
|
4256
4818
|
const base = claudeMd.replace(/\s*$/, "");
|
|
4257
|
-
return { text: base.length === 0 ? `${
|
|
4819
|
+
return { text: base.length === 0 ? `${IMPORT_LINE2}
|
|
4258
4820
|
` : `${base}
|
|
4259
4821
|
|
|
4260
|
-
${
|
|
4822
|
+
${IMPORT_LINE2}
|
|
4261
4823
|
`, added: true };
|
|
4262
4824
|
}
|
|
4263
4825
|
function stripImportLine(claudeMd) {
|
|
4264
4826
|
const lines = claudeMd.split(/\r?\n/);
|
|
4265
|
-
const i = lines.findIndex((l) => l.trim() ===
|
|
4827
|
+
const i = lines.findIndex((l) => l.trim() === IMPORT_LINE2);
|
|
4266
4828
|
if (i < 0) return { text: claudeMd, removed: false };
|
|
4267
4829
|
lines.splice(i, 1);
|
|
4268
4830
|
if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
|
|
@@ -4272,33 +4834,33 @@ function stripImportLine(claudeMd) {
|
|
|
4272
4834
|
}
|
|
4273
4835
|
async function runInclude(opts) {
|
|
4274
4836
|
const { projectDir, artifactsDir } = opts;
|
|
4275
|
-
const includeSrc =
|
|
4837
|
+
const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
|
|
4276
4838
|
if (!await pathExists(includeSrc)) {
|
|
4277
4839
|
throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
|
|
4278
4840
|
}
|
|
4279
|
-
const includeMd = await
|
|
4280
|
-
const claudeDir =
|
|
4841
|
+
const includeMd = await readFile6(includeSrc, "utf8");
|
|
4842
|
+
const claudeDir = join7(projectDir, ".claude");
|
|
4281
4843
|
await mkdir4(claudeDir, { recursive: true });
|
|
4282
|
-
const includeDest =
|
|
4844
|
+
const includeDest = join7(projectDir, INCLUDE_REL);
|
|
4283
4845
|
await writeFile4(includeDest, includeMd, "utf8");
|
|
4284
4846
|
const wrote = [includeDest];
|
|
4285
4847
|
const lines = [`Wrote ${INCLUDE_REL}`];
|
|
4286
|
-
const claudeMdPath =
|
|
4287
|
-
const existing = await pathExists(claudeMdPath) ? await
|
|
4848
|
+
const claudeMdPath = join7(projectDir, "CLAUDE.md");
|
|
4849
|
+
const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
|
|
4288
4850
|
const { text: text2, added } = ensureImportLine(existing);
|
|
4289
4851
|
if (added) {
|
|
4290
4852
|
await writeFile4(claudeMdPath, text2, "utf8");
|
|
4291
4853
|
wrote.push(claudeMdPath);
|
|
4292
|
-
lines.push(`Added "${
|
|
4854
|
+
lines.push(`Added "${IMPORT_LINE2}" to CLAUDE.md`);
|
|
4293
4855
|
} else {
|
|
4294
4856
|
lines.push("CLAUDE.md already imports it");
|
|
4295
4857
|
}
|
|
4296
|
-
const companionDir =
|
|
4858
|
+
const companionDir = join7(projectDir, APPLY_DIR_REL);
|
|
4297
4859
|
await mkdir4(companionDir, { recursive: true });
|
|
4298
4860
|
for (const name of COMPANIONS) {
|
|
4299
|
-
const src =
|
|
4861
|
+
const src = join7(artifactsDir, name);
|
|
4300
4862
|
if (await pathExists(src)) {
|
|
4301
|
-
const dest =
|
|
4863
|
+
const dest = join7(companionDir, name);
|
|
4302
4864
|
await copyFile(src, dest);
|
|
4303
4865
|
wrote.push(dest);
|
|
4304
4866
|
}
|
|
@@ -4307,9 +4869,9 @@ async function runInclude(opts) {
|
|
|
4307
4869
|
lines.push(`Undo: costclaw apply ${projectDir} --remove`);
|
|
4308
4870
|
lines.push('Next: claude "Follow .claude/costclaw/HARNESS-UPGRADE.md"');
|
|
4309
4871
|
if (opts.applySettings) {
|
|
4310
|
-
const settingsSrc =
|
|
4311
|
-
const suggestedJson = await
|
|
4312
|
-
const target = opts.applySettingsPath ??
|
|
4872
|
+
const settingsSrc = join7(artifactsDir, "settings.suggested.json");
|
|
4873
|
+
const suggestedJson = await readFile6(settingsSrc, "utf8");
|
|
4874
|
+
const target = opts.applySettingsPath ?? join7(projectDir, ".claude", "settings.json");
|
|
4313
4875
|
const settingsLines = await applyDerivedSettings(target, suggestedJson, opts.force ?? false);
|
|
4314
4876
|
lines.push(...settingsLines);
|
|
4315
4877
|
wrote.push(target);
|
|
@@ -4318,8 +4880,8 @@ async function runInclude(opts) {
|
|
|
4318
4880
|
}
|
|
4319
4881
|
async function runRemove(opts) {
|
|
4320
4882
|
const { projectDir } = opts;
|
|
4321
|
-
const includeDest =
|
|
4322
|
-
const companionDir =
|
|
4883
|
+
const includeDest = join7(projectDir, INCLUDE_REL);
|
|
4884
|
+
const companionDir = join7(projectDir, APPLY_DIR_REL);
|
|
4323
4885
|
const removed = [];
|
|
4324
4886
|
if (await pathExists(includeDest)) {
|
|
4325
4887
|
await rm3(includeDest, { force: true });
|
|
@@ -4330,9 +4892,9 @@ async function runRemove(opts) {
|
|
|
4330
4892
|
removed.push(companionDir);
|
|
4331
4893
|
}
|
|
4332
4894
|
const lines = [`Removed ${INCLUDE_REL} and ${APPLY_DIR_REL}/`];
|
|
4333
|
-
const claudeMdPath =
|
|
4895
|
+
const claudeMdPath = join7(projectDir, "CLAUDE.md");
|
|
4334
4896
|
if (await pathExists(claudeMdPath)) {
|
|
4335
|
-
const existing = await
|
|
4897
|
+
const existing = await readFile6(claudeMdPath, "utf8");
|
|
4336
4898
|
const { text: text2, removed: didRemove } = stripImportLine(existing);
|
|
4337
4899
|
if (didRemove) {
|
|
4338
4900
|
if (text2 === "") {
|
|
@@ -4341,7 +4903,7 @@ async function runRemove(opts) {
|
|
|
4341
4903
|
lines.push("Removed CLAUDE.md (it held only the import line)");
|
|
4342
4904
|
} else {
|
|
4343
4905
|
await writeFile4(claudeMdPath, text2, "utf8");
|
|
4344
|
-
lines.push(`Removed "${
|
|
4906
|
+
lines.push(`Removed "${IMPORT_LINE2}" from CLAUDE.md`);
|
|
4345
4907
|
}
|
|
4346
4908
|
}
|
|
4347
4909
|
}
|
|
@@ -4349,24 +4911,24 @@ async function runRemove(opts) {
|
|
|
4349
4911
|
}
|
|
4350
4912
|
async function runReplace(opts) {
|
|
4351
4913
|
const { projectDir, artifactsDir, force } = opts;
|
|
4352
|
-
if (!await pathExists(
|
|
4914
|
+
if (!await pathExists(join7(projectDir, ".git"))) {
|
|
4353
4915
|
throw new Error(
|
|
4354
4916
|
"apply --replace needs a git repository so the change can be undone with git checkout -- CLAUDE.md. Use the default include mode instead."
|
|
4355
4917
|
);
|
|
4356
4918
|
}
|
|
4357
|
-
const optimizedSrc =
|
|
4919
|
+
const optimizedSrc = join7(artifactsDir, OPTIMIZED_ARTIFACT);
|
|
4358
4920
|
if (!await pathExists(optimizedSrc)) {
|
|
4359
4921
|
throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
|
|
4360
4922
|
}
|
|
4361
|
-
const optimized = await
|
|
4362
|
-
const claudeMdPath =
|
|
4923
|
+
const optimized = await readFile6(optimizedSrc, "utf8");
|
|
4924
|
+
const claudeMdPath = join7(projectDir, "CLAUDE.md");
|
|
4363
4925
|
const backup = `${claudeMdPath}.bak`;
|
|
4364
4926
|
if (await pathExists(backup) && !force) {
|
|
4365
4927
|
throw new Error(
|
|
4366
4928
|
`A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
|
|
4367
4929
|
);
|
|
4368
4930
|
}
|
|
4369
|
-
const original = await pathExists(claudeMdPath) ? await
|
|
4931
|
+
const original = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : "";
|
|
4370
4932
|
await writeFile4(backup, original, "utf8");
|
|
4371
4933
|
await writeFile4(claudeMdPath, optimized, "utf8");
|
|
4372
4934
|
const lines = [
|
|
@@ -4433,7 +4995,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
4433
4995
|
let existingText = "";
|
|
4434
4996
|
let existing = {};
|
|
4435
4997
|
if (await pathExists(target)) {
|
|
4436
|
-
existingText = await
|
|
4998
|
+
existingText = await readFile6(target, "utf8");
|
|
4437
4999
|
if (existingText.trim() !== "") {
|
|
4438
5000
|
let parsed;
|
|
4439
5001
|
try {
|
|
@@ -4460,7 +5022,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
4460
5022
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
4461
5023
|
const merged = { ...existing, permissions: mergedPerms };
|
|
4462
5024
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
4463
|
-
await mkdir4(
|
|
5025
|
+
await mkdir4(dirname2(target), { recursive: true });
|
|
4464
5026
|
await writeFile4(backup, existingText, "utf8");
|
|
4465
5027
|
await writeFile4(target, mergedText, "utf8");
|
|
4466
5028
|
return [
|
|
@@ -4496,7 +5058,7 @@ function approxTokens(n) {
|
|
|
4496
5058
|
function plural2(n, noun) {
|
|
4497
5059
|
return n === 1 ? noun : `${noun}s`;
|
|
4498
5060
|
}
|
|
4499
|
-
function
|
|
5061
|
+
function num5(n) {
|
|
4500
5062
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
4501
5063
|
}
|
|
4502
5064
|
var STYLE2 = `
|
|
@@ -4835,7 +5397,7 @@ function renderCarriedDisclosure(sections, carriedTokens) {
|
|
|
4835
5397
|
const carried = sections.filter((s) => s.disposition === "carried");
|
|
4836
5398
|
if (carried.length === 0) return "";
|
|
4837
5399
|
const names = carried.map((s) => esc(s.name)).join(" · ");
|
|
4838
|
-
const weight = carriedTokens > 0 ? `, about ${
|
|
5400
|
+
const weight = carriedTokens > 0 ? `, about ${num5(carriedTokens)} tokens` : "";
|
|
4839
5401
|
const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
|
|
4840
5402
|
return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
|
|
4841
5403
|
}
|
|
@@ -4854,7 +5416,7 @@ function renderOptimizeDashboard(input) {
|
|
|
4854
5416
|
<meta charset="utf-8">
|
|
4855
5417
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4856
5418
|
<title>CostClaw optimize: ${esc(input.projectName)}</title>
|
|
4857
|
-
<style>${STYLE2}</style>
|
|
5419
|
+
<style>${STYLE2}${input.review ? REVIEW_STYLE : ""}</style>
|
|
4858
5420
|
</head>
|
|
4859
5421
|
<body>
|
|
4860
5422
|
<div class="wrap">
|
|
@@ -4865,6 +5427,9 @@ ${renderReceipt(input)}
|
|
|
4865
5427
|
|
|
4866
5428
|
<h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
|
|
4867
5429
|
<div class="panel">${renderComparisonTabs(input)}</div>
|
|
5430
|
+
${input.review ? `
|
|
5431
|
+
<h2>What to change in your CLAUDE.md<span class="n">${num5(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
|
|
5432
|
+
<div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
|
|
4868
5433
|
|
|
4869
5434
|
<h2>Fixes, ranked by what they recover</h2>
|
|
4870
5435
|
${renderFixes(input.fixes, input.report)}
|
|
@@ -4888,6 +5453,85 @@ No network calls, no telemetry, no model calls.</footer>
|
|
|
4888
5453
|
</html>
|
|
4889
5454
|
`;
|
|
4890
5455
|
}
|
|
5456
|
+
var KEEP_RUN_MAX = 12;
|
|
5457
|
+
var TRUNCATE_OVER_LINES = 800;
|
|
5458
|
+
var REVIEW_STYLE = `
|
|
5459
|
+
pre.review{font-family:var(--mono);font-size:.78rem;line-height:1.55;margin:0;padding:14px 0;
|
|
5460
|
+
background:color-mix(in srgb,var(--ink) 4%,transparent);border-radius:8px;overflow-x:auto}
|
|
5461
|
+
pre.review .ln{display:block;padding:0 14px;white-space:pre-wrap;word-break:break-word}
|
|
5462
|
+
pre.review .g{display:inline-block;width:3.2em;color:var(--ink2);user-select:none;text-align:right;margin-right:10px}
|
|
5463
|
+
pre.review .why{color:var(--ink2);font-size:.72rem;margin-left:10px}
|
|
5464
|
+
pre.review .mark-remove{background:color-mix(in srgb,var(--bad) 14%,transparent)}
|
|
5465
|
+
pre.review .mark-remove .t{text-decoration:line-through}
|
|
5466
|
+
pre.review .mark-move{background:color-mix(in srgb,var(--warn) 14%,transparent)}
|
|
5467
|
+
pre.review .mark-add{background:color-mix(in srgb,var(--good) 14%,transparent)}
|
|
5468
|
+
pre.review .skip{color:var(--ink2);font-style:italic}
|
|
5469
|
+
.legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
|
|
5470
|
+
.legend b{font-weight:650}
|
|
5471
|
+
.legend .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 12px}
|
|
5472
|
+
.legend .sw.r{background:color-mix(in srgb,var(--bad) 50%,transparent)}
|
|
5473
|
+
.legend .sw.m{background:color-mix(in srgb,var(--warn) 50%,transparent)}
|
|
5474
|
+
.legend .sw.a{background:color-mix(in srgb,var(--good) 50%,transparent)}
|
|
5475
|
+
textarea.prompt{width:100%;min-height:190px;font-family:var(--mono);font-size:.76rem;line-height:1.5;
|
|
5476
|
+
border:1px solid var(--line);border-radius:8px;padding:12px;background:var(--bg);color:var(--ink);resize:vertical}
|
|
5477
|
+
button.copy{font:inherit;font-size:.84rem;padding:7px 14px;border-radius:7px;border:1px solid var(--accent);
|
|
5478
|
+
background:var(--accent);color:#fff;font-weight:600;cursor:pointer;margin-bottom:10px}
|
|
5479
|
+
.revhead{font-size:.86rem;color:var(--ink2);margin:0 0 12px}
|
|
5480
|
+
.revhead b{color:var(--ink);font-weight:650}
|
|
5481
|
+
`;
|
|
5482
|
+
var COPY_SCRIPT = 'function ccCopy(b){var t=b.parentNode.querySelector("textarea");t.select();if(navigator.clipboard){navigator.clipboard.writeText(t.value)}else{document.execCommand("copy")}b.textContent="Copied";}';
|
|
5483
|
+
function lineHtml(line, gutter) {
|
|
5484
|
+
const why = line.reason ? `<span class="why">${esc(line.reason)}</span>` : "";
|
|
5485
|
+
const cls = line.mark === "keep" ? "mark-keep" : `mark-${line.mark}`;
|
|
5486
|
+
return `<span class="ln ${cls}"><span class="g">${esc(gutter === null ? "+" : String(gutter))}</span><span class="t">${esc(line.text)}</span>${why}</span>`;
|
|
5487
|
+
}
|
|
5488
|
+
function renderLines(lines, keepRunMax) {
|
|
5489
|
+
const out = [];
|
|
5490
|
+
let run = [];
|
|
5491
|
+
const flush = () => {
|
|
5492
|
+
if (run.length === 0) return;
|
|
5493
|
+
const half = Math.floor(keepRunMax / 2);
|
|
5494
|
+
if (keepRunMax > 0 && run.length > keepRunMax) {
|
|
5495
|
+
const head = run.slice(0, half);
|
|
5496
|
+
const tail = run.slice(run.length - half);
|
|
5497
|
+
for (const i of head) out.push(lineHtml(lines[i], i + 1));
|
|
5498
|
+
out.push(
|
|
5499
|
+
`<span class="ln skip"><span class="g"></span>... ${num5(run.length - head.length - tail.length)} unchanged lines ...</span>`
|
|
5500
|
+
);
|
|
5501
|
+
for (const i of tail) out.push(lineHtml(lines[i], i + 1));
|
|
5502
|
+
} else {
|
|
5503
|
+
for (const i of run) out.push(lineHtml(lines[i], i + 1));
|
|
5504
|
+
}
|
|
5505
|
+
run = [];
|
|
5506
|
+
};
|
|
5507
|
+
for (let i = 0; i < lines.length; i++) {
|
|
5508
|
+
const l = lines[i];
|
|
5509
|
+
if (l.mark === "keep") {
|
|
5510
|
+
run.push(i);
|
|
5511
|
+
continue;
|
|
5512
|
+
}
|
|
5513
|
+
flush();
|
|
5514
|
+
out.push(lineHtml(l, l.mark === "add" ? null : i + 1));
|
|
5515
|
+
}
|
|
5516
|
+
flush();
|
|
5517
|
+
return `<pre class="review">${out.join("")}</pre>`;
|
|
5518
|
+
}
|
|
5519
|
+
function renderAnnotatedFile(review) {
|
|
5520
|
+
const legend = `<p class="legend"><b>Legend</b><span class="sw r"></span>remove<span class="sw m"></span>move out<span class="sw a"></span>add</p>`;
|
|
5521
|
+
if (review.missing) {
|
|
5522
|
+
const adds = review.lines.filter((l) => l.mark === "add");
|
|
5523
|
+
if (adds.length === 0) {
|
|
5524
|
+
return `<p class="note">${esc(review.label)} does not exist yet, and nothing needs adding.</p>`;
|
|
5525
|
+
}
|
|
5526
|
+
return legend + `<p class="note">${esc(review.label)} does not exist yet. Proposed content:</p>` + renderLines(adds, 0);
|
|
5527
|
+
}
|
|
5528
|
+
return legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
|
|
5529
|
+
}
|
|
5530
|
+
function reviewCountLine(review) {
|
|
5531
|
+
const n = review.changes.length;
|
|
5532
|
+
if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
|
|
5533
|
+
return `<b>${num5(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
|
|
5534
|
+
}
|
|
4891
5535
|
var INDEX_STYLE = `
|
|
4892
5536
|
.rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
|
|
4893
5537
|
.acts{display:flex;gap:8px;flex-wrap:wrap}
|
|
@@ -4921,6 +5565,27 @@ function indexActions(row, serve) {
|
|
|
4921
5565
|
}
|
|
4922
5566
|
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
5567
|
}
|
|
5568
|
+
function renderPromptPanel(review) {
|
|
5569
|
+
return `<div class="panel"><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="14" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run the line below. It covers your global CLAUDE.md and every project on this page, so there is one prompt, not one per project.</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code><p class="note">costclaw never calls a model: this work order is deterministic text built from your own audit. Your agent does the editing, with your approval.</p></div>`;
|
|
5570
|
+
}
|
|
5571
|
+
function renderGlobalPanel(review) {
|
|
5572
|
+
const t = review.tokens;
|
|
5573
|
+
const importCount = review.importCount;
|
|
5574
|
+
const imported = importCount > 0 ? ` plus ${num5(importCount)} imported ${plural2(importCount, "file")}` : "";
|
|
5575
|
+
const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${num5(t.total)} tokens on every turn of every project, about ${num5(t.afterChanges)} after these changes. ${reviewCountLine(review)}.</p>`;
|
|
5576
|
+
return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
|
|
5577
|
+
}
|
|
5578
|
+
function renderProjectPanels(input, review) {
|
|
5579
|
+
const out = [];
|
|
5580
|
+
input.rows.forEach((row, i) => {
|
|
5581
|
+
const r = review.projects.get(row.slug);
|
|
5582
|
+
if (!r) return;
|
|
5583
|
+
out.push(
|
|
5584
|
+
`<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${num5(r.changes.length)} proposed ${plural2(r.changes.length, "change")}</summary><div class="panel" style="margin-top:10px"><p class="revhead">${reviewCountLine(r)}. About ${num5(r.tokens.total)} tokens per turn, about ${num5(r.tokens.afterChanges)} after these changes.</p>` + renderAnnotatedFile(r) + `<div style="margin-top:14px">${indexActions(row, input.serve)}</div></div></details>`
|
|
5585
|
+
);
|
|
5586
|
+
});
|
|
5587
|
+
return out.join("");
|
|
5588
|
+
}
|
|
4924
5589
|
function renderOptimizeIndex(input) {
|
|
4925
5590
|
const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
|
|
4926
5591
|
const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
|
|
@@ -4937,7 +5602,8 @@ function renderOptimizeIndex(input) {
|
|
|
4937
5602
|
<meta charset="utf-8">
|
|
4938
5603
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4939
5604
|
<title>CostClaw optimize: ${input.rows.length} ${plural2(input.rows.length, "project")}</title>
|
|
4940
|
-
<style>${STYLE2}${INDEX_STYLE}</style>
|
|
5605
|
+
<style>${STYLE2}${INDEX_STYLE}${input.review ? REVIEW_STYLE : ""}</style>
|
|
5606
|
+
${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
|
|
4941
5607
|
</head>
|
|
4942
5608
|
<body>
|
|
4943
5609
|
<div class="wrap">
|
|
@@ -4947,9 +5613,16 @@ function renderOptimizeIndex(input) {
|
|
|
4947
5613
|
artifacts in ${esc(input.root)}/</p></header>
|
|
4948
5614
|
|
|
4949
5615
|
${banner}${done}
|
|
5616
|
+
${input.review ? `<h2>Your upgrade prompt<span class="n">one paste applies all of it</span></h2>
|
|
5617
|
+
${renderPromptPanel(input.review)}
|
|
5618
|
+
|
|
5619
|
+
<h2>Global CLAUDE.md<span class="n">loaded on every turn of every project</span></h2>
|
|
5620
|
+
${renderGlobalPanel(input.review.global)}` : ""}
|
|
5621
|
+
|
|
4950
5622
|
<h2>Your projects<span class="n">ranked by spend</span></h2>
|
|
4951
5623
|
${body}
|
|
4952
5624
|
${how}
|
|
5625
|
+
${input.review ? renderProjectPanels(input, input.review) : ""}
|
|
4953
5626
|
|
|
4954
5627
|
<footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
|
|
4955
5628
|
Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
|
|
@@ -4961,8 +5634,8 @@ Nothing was written inside any project. No network calls, no telemetry, no model
|
|
|
4961
5634
|
}
|
|
4962
5635
|
|
|
4963
5636
|
// src/project-scan.ts
|
|
4964
|
-
import { readdir as readdir3, readFile as
|
|
4965
|
-
import { join as
|
|
5637
|
+
import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
|
|
5638
|
+
import { join as join8, basename } from "path";
|
|
4966
5639
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
4967
5640
|
"node_modules",
|
|
4968
5641
|
".git",
|
|
@@ -4991,7 +5664,7 @@ var DIR_NOTES = {
|
|
|
4991
5664
|
};
|
|
4992
5665
|
async function readText(p) {
|
|
4993
5666
|
try {
|
|
4994
|
-
return await
|
|
5667
|
+
return await readFile7(p, "utf8");
|
|
4995
5668
|
} catch {
|
|
4996
5669
|
return null;
|
|
4997
5670
|
}
|
|
@@ -5101,7 +5774,7 @@ async function containsTestFiles(dir) {
|
|
|
5101
5774
|
const top = await listEntries(dir);
|
|
5102
5775
|
if (top.files.some((f) => TEST_FILE.test(f))) return true;
|
|
5103
5776
|
for (const sub of top.dirs) {
|
|
5104
|
-
const inner = await listEntries(
|
|
5777
|
+
const inner = await listEntries(join8(dir, sub));
|
|
5105
5778
|
if (inner.files.some((f) => TEST_FILE.test(f))) return true;
|
|
5106
5779
|
}
|
|
5107
5780
|
return false;
|
|
@@ -5111,14 +5784,14 @@ async function detectTestsLocation(dir, files, dirs) {
|
|
|
5111
5784
|
if (candidates.length > 0) {
|
|
5112
5785
|
const withTests = [];
|
|
5113
5786
|
for (const c of candidates) {
|
|
5114
|
-
if (await containsTestFiles(
|
|
5787
|
+
if (await containsTestFiles(join8(dir, c))) withTests.push(c);
|
|
5115
5788
|
}
|
|
5116
5789
|
const chosen = withTests.length > 0 ? withTests : candidates;
|
|
5117
5790
|
return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
|
|
5118
5791
|
}
|
|
5119
5792
|
if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
5120
5793
|
if (dirs.includes("src")) {
|
|
5121
|
-
const sub = await listEntries(
|
|
5794
|
+
const sub = await listEntries(join8(dir, "src"));
|
|
5122
5795
|
if (sub.files.some((f) => TEST_FILE.test(f))) {
|
|
5123
5796
|
return "tests alongside source (*.test.* / *.spec.*)";
|
|
5124
5797
|
}
|
|
@@ -5201,7 +5874,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
5201
5874
|
if (oneFileCmd !== null && "test" in scripts) {
|
|
5202
5875
|
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
5203
5876
|
}
|
|
5204
|
-
const tsconfig = parseJson(await readText(
|
|
5877
|
+
const tsconfig = parseJson(await readText(join8(dir, "tsconfig.json")));
|
|
5205
5878
|
if (tsconfig) {
|
|
5206
5879
|
const co = tsconfig.compilerOptions;
|
|
5207
5880
|
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
@@ -5304,7 +5977,7 @@ async function scanPython(dir, files, profile) {
|
|
|
5304
5977
|
const deps = [];
|
|
5305
5978
|
const tables = /* @__PURE__ */ new Set();
|
|
5306
5979
|
let hasPoetry = false;
|
|
5307
|
-
const pyprojectText = await readText(
|
|
5980
|
+
const pyprojectText = await readText(join8(dir, "pyproject.toml"));
|
|
5308
5981
|
if (pyprojectText !== null) {
|
|
5309
5982
|
const parsed = parsePyproject(pyprojectText);
|
|
5310
5983
|
name = parsed.name;
|
|
@@ -5314,7 +5987,7 @@ async function scanPython(dir, files, profile) {
|
|
|
5314
5987
|
hasPoetry = parsed.hasPoetry;
|
|
5315
5988
|
}
|
|
5316
5989
|
if (files.includes("requirements.txt")) {
|
|
5317
|
-
const reqText = await readText(
|
|
5990
|
+
const reqText = await readText(join8(dir, "requirements.txt"));
|
|
5318
5991
|
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
5319
5992
|
}
|
|
5320
5993
|
if (name !== null && name.trim() !== "") profile.name = name;
|
|
@@ -5348,7 +6021,7 @@ async function scanPython(dir, files, profile) {
|
|
|
5348
6021
|
}
|
|
5349
6022
|
}
|
|
5350
6023
|
async function scanRust(dir, profile) {
|
|
5351
|
-
const text2 = await readText(
|
|
6024
|
+
const text2 = await readText(join8(dir, "Cargo.toml"));
|
|
5352
6025
|
pushUnique(profile.stack, "Rust");
|
|
5353
6026
|
profile.packageManager = "cargo";
|
|
5354
6027
|
if (text2 !== null) {
|
|
@@ -5374,7 +6047,7 @@ async function scanRust(dir, profile) {
|
|
|
5374
6047
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
5375
6048
|
}
|
|
5376
6049
|
async function scanGo(dir, profile) {
|
|
5377
|
-
const text2 = await readText(
|
|
6050
|
+
const text2 = await readText(join8(dir, "go.mod"));
|
|
5378
6051
|
pushUnique(profile.stack, "Go");
|
|
5379
6052
|
profile.packageManager = "go";
|
|
5380
6053
|
if (text2 !== null) {
|
|
@@ -5439,7 +6112,7 @@ async function scanProject(dir) {
|
|
|
5439
6112
|
const profile = emptyProfile(basename(dir));
|
|
5440
6113
|
const { files, dirs } = await listEntries(dir);
|
|
5441
6114
|
if (files.includes("package.json")) {
|
|
5442
|
-
const pkg = parseJson(await readText(
|
|
6115
|
+
const pkg = parseJson(await readText(join8(dir, "package.json")));
|
|
5443
6116
|
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
5444
6117
|
}
|
|
5445
6118
|
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
@@ -5452,7 +6125,7 @@ async function scanProject(dir) {
|
|
|
5452
6125
|
await scanGo(dir, profile);
|
|
5453
6126
|
}
|
|
5454
6127
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
5455
|
-
const text2 = await readText(
|
|
6128
|
+
const text2 = await readText(join8(dir, "Makefile"));
|
|
5456
6129
|
if (text2 !== null) {
|
|
5457
6130
|
for (const t of parseMakefile(text2)) {
|
|
5458
6131
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
@@ -5462,7 +6135,7 @@ async function scanProject(dir) {
|
|
|
5462
6135
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
5463
6136
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
5464
6137
|
if (readmeName) {
|
|
5465
|
-
const text2 = await readText(
|
|
6138
|
+
const text2 = await readText(join8(dir, readmeName));
|
|
5466
6139
|
if (text2 !== null) {
|
|
5467
6140
|
const parsed = parseReadme(text2);
|
|
5468
6141
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
@@ -5475,7 +6148,7 @@ async function scanProject(dir) {
|
|
|
5475
6148
|
profile.structure = await detectStructure(dir, dirs);
|
|
5476
6149
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
5477
6150
|
if (envFile) {
|
|
5478
|
-
const text2 = await readText(
|
|
6151
|
+
const text2 = await readText(join8(dir, envFile));
|
|
5479
6152
|
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
5480
6153
|
}
|
|
5481
6154
|
return profile;
|
|
@@ -5484,8 +6157,8 @@ async function scanProject(dir) {
|
|
|
5484
6157
|
// src/serve.ts
|
|
5485
6158
|
import { createServer } from "http";
|
|
5486
6159
|
import { randomBytes } from "crypto";
|
|
5487
|
-
import { readFile as
|
|
5488
|
-
import { extname, resolve as
|
|
6160
|
+
import { readFile as readFile8 } from "fs/promises";
|
|
6161
|
+
import { extname, resolve as resolve3, sep as sep2 } from "path";
|
|
5489
6162
|
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
5490
6163
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
5491
6164
|
var DASHBOARD_NAME = "DASHBOARD.html";
|
|
@@ -5510,8 +6183,8 @@ function safeArtifactPath(root, urlPath) {
|
|
|
5510
6183
|
return null;
|
|
5511
6184
|
}
|
|
5512
6185
|
if (decoded.includes("\0")) return null;
|
|
5513
|
-
const resolvedRoot =
|
|
5514
|
-
const full =
|
|
6186
|
+
const resolvedRoot = resolve3(root);
|
|
6187
|
+
const full = resolve3(resolvedRoot, "." + decoded);
|
|
5515
6188
|
if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
|
|
5516
6189
|
return full;
|
|
5517
6190
|
}
|
|
@@ -5652,7 +6325,7 @@ async function startApplyServer(opts) {
|
|
|
5652
6325
|
return;
|
|
5653
6326
|
}
|
|
5654
6327
|
try {
|
|
5655
|
-
const data = await
|
|
6328
|
+
const data = await readFile8(filePath);
|
|
5656
6329
|
res.writeHead(200, { "content-type": contentTypeFor(filePath) });
|
|
5657
6330
|
res.end(data);
|
|
5658
6331
|
} catch {
|
|
@@ -5707,11 +6380,11 @@ async function startApplyServer(opts) {
|
|
|
5707
6380
|
}
|
|
5708
6381
|
|
|
5709
6382
|
// src/optimize-manifest.ts
|
|
5710
|
-
import { mkdir as mkdir5, readFile as
|
|
5711
|
-
import { join as
|
|
6383
|
+
import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
|
|
6384
|
+
import { join as join9, resolve as resolve4 } from "path";
|
|
5712
6385
|
var MANIFEST_NAME = "index.json";
|
|
5713
6386
|
function defaultOptimizeRoot(home) {
|
|
5714
|
-
return
|
|
6387
|
+
return join9(home, ".costclaw", "optimize");
|
|
5715
6388
|
}
|
|
5716
6389
|
function isRecord(value) {
|
|
5717
6390
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -5719,7 +6392,7 @@ function isRecord(value) {
|
|
|
5719
6392
|
async function readManifest(root) {
|
|
5720
6393
|
let text2;
|
|
5721
6394
|
try {
|
|
5722
|
-
text2 = await
|
|
6395
|
+
text2 = await readFile9(join9(root, MANIFEST_NAME), "utf8");
|
|
5723
6396
|
} catch {
|
|
5724
6397
|
return null;
|
|
5725
6398
|
}
|
|
@@ -5739,10 +6412,10 @@ async function readManifest(root) {
|
|
|
5739
6412
|
}
|
|
5740
6413
|
async function writeManifest(root, m) {
|
|
5741
6414
|
await mkdir5(root, { recursive: true });
|
|
5742
|
-
await writeFile5(
|
|
6415
|
+
await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
|
|
5743
6416
|
}
|
|
5744
6417
|
function normalizePath(p) {
|
|
5745
|
-
const r =
|
|
6418
|
+
const r = resolve4(p);
|
|
5746
6419
|
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
5747
6420
|
}
|
|
5748
6421
|
function findEntry(m, projectDir) {
|
|
@@ -5773,12 +6446,13 @@ var PLAYBOOK_NAME2 = "PLAYBOOK.md";
|
|
|
5773
6446
|
var SETTINGS_NAME2 = "settings.suggested.json";
|
|
5774
6447
|
var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
|
|
5775
6448
|
var DASHBOARD_NAME2 = "DASHBOARD.html";
|
|
6449
|
+
var UPGRADE_ALL_NAME = "UPGRADE-ALL.md";
|
|
5776
6450
|
var INCLUDE_NAME2 = "costclaw.md";
|
|
5777
6451
|
var DEFAULT_LIMIT = 10;
|
|
5778
6452
|
function usd6(n) {
|
|
5779
6453
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
5780
6454
|
}
|
|
5781
|
-
function
|
|
6455
|
+
function num6(n) {
|
|
5782
6456
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
5783
6457
|
}
|
|
5784
6458
|
function describeDetection(project) {
|
|
@@ -5815,17 +6489,14 @@ function projectRecoverable(report, slug) {
|
|
|
5815
6489
|
return row ? row.usd : null;
|
|
5816
6490
|
}
|
|
5817
6491
|
async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
5818
|
-
const slug = basename2(
|
|
6492
|
+
const slug = basename2(resolve5(projectDir));
|
|
5819
6493
|
let currentClaudeMd = ctx.claudeMdOverride;
|
|
5820
6494
|
let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
|
|
5821
6495
|
if (currentClaudeMd === void 0) {
|
|
5822
|
-
const own =
|
|
6496
|
+
const own = join10(projectDir, "CLAUDE.md");
|
|
5823
6497
|
if (await pathExists2(own)) {
|
|
5824
|
-
currentClaudeMd = await
|
|
6498
|
+
currentClaudeMd = await readFile10(own, "utf8");
|
|
5825
6499
|
claudeMdSource = own;
|
|
5826
|
-
} else {
|
|
5827
|
-
currentClaudeMd = ctx.globalClaudeMd;
|
|
5828
|
-
claudeMdSource = ctx.globalClaudeMd === void 0 ? null : ctx.claudeMdFallbackSource;
|
|
5829
6500
|
}
|
|
5830
6501
|
}
|
|
5831
6502
|
const project = await scanProject(projectDir);
|
|
@@ -5837,11 +6508,19 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
5837
6508
|
project
|
|
5838
6509
|
});
|
|
5839
6510
|
await mkdir6(artifactsDir, { recursive: true });
|
|
5840
|
-
await writeFile6(
|
|
5841
|
-
await writeFile6(
|
|
5842
|
-
await writeFile6(
|
|
5843
|
-
await writeFile6(
|
|
5844
|
-
await writeFile6(
|
|
6511
|
+
await writeFile6(join10(artifactsDir, OPTIMIZED_NAME2), result.optimizedClaudeMd, "utf8");
|
|
6512
|
+
await writeFile6(join10(artifactsDir, PLAYBOOK_NAME2), result.playbook, "utf8");
|
|
6513
|
+
await writeFile6(join10(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
|
|
6514
|
+
await writeFile6(join10(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
|
|
6515
|
+
await writeFile6(join10(artifactsDir, INCLUDE_NAME2), result.includeMd, "utf8");
|
|
6516
|
+
const review = reviewProjectClaudeMd({
|
|
6517
|
+
text: currentClaudeMd ?? null,
|
|
6518
|
+
report: ctx.report,
|
|
6519
|
+
includeSections: result.includeSections,
|
|
6520
|
+
includeMd: result.includeMd,
|
|
6521
|
+
globalSections: ctx.globalSections,
|
|
6522
|
+
label: claudeMdSource ?? join10(projectDir, "CLAUDE.md")
|
|
6523
|
+
});
|
|
5845
6524
|
const spend = projectSpend(ctx.report, slug);
|
|
5846
6525
|
const recoverable = projectRecoverable(ctx.report, slug);
|
|
5847
6526
|
const applyCommand = `costclaw apply ${projectDir}`;
|
|
@@ -5864,9 +6543,10 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
5864
6543
|
report: ctx.report,
|
|
5865
6544
|
headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
|
|
5866
6545
|
headlineWasteUsd: auditRecoverable2,
|
|
5867
|
-
applyCommand
|
|
6546
|
+
applyCommand,
|
|
6547
|
+
review
|
|
5868
6548
|
});
|
|
5869
|
-
await writeFile6(
|
|
6549
|
+
await writeFile6(join10(artifactsDir, DASHBOARD_NAME2), html, "utf8");
|
|
5870
6550
|
}
|
|
5871
6551
|
const lines = ctx.lines;
|
|
5872
6552
|
lines.push(slug);
|
|
@@ -5890,11 +6570,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
5890
6570
|
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
5891
6571
|
const dir = after > before ? "larger" : "smaller";
|
|
5892
6572
|
lines.push(
|
|
5893
|
-
`Your CLAUDE.md: an estimated ${
|
|
6573
|
+
`Your CLAUDE.md: an estimated ${num6(before)} tokens to ${num6(after)} (${pct2}% ${dir}), paid on every turn.`
|
|
5894
6574
|
);
|
|
5895
6575
|
if (result.carriedTokens >= after / 2) {
|
|
5896
6576
|
lines.push(
|
|
5897
|
-
`About ${
|
|
6577
|
+
`About ${num6(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
5898
6578
|
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
5899
6579
|
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
5900
6580
|
);
|
|
@@ -5907,25 +6587,37 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
5907
6587
|
);
|
|
5908
6588
|
}
|
|
5909
6589
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
6590
|
+
if (review.changes.length > 0) {
|
|
6591
|
+
const n = review.changes.length;
|
|
6592
|
+
lines.push(`Review: ${num6(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
|
|
6593
|
+
}
|
|
5910
6594
|
lines.push(`Artifacts: ${artifactsDir}`);
|
|
5911
6595
|
lines.push(`Apply: ${applyCommand}`);
|
|
5912
6596
|
lines.push("");
|
|
5913
6597
|
return {
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
|
|
5921
|
-
|
|
6598
|
+
entry: {
|
|
6599
|
+
slug,
|
|
6600
|
+
dir: basename2(artifactsDir),
|
|
6601
|
+
projectDir,
|
|
6602
|
+
artifactsDir,
|
|
6603
|
+
spendUsd: spend ?? 0,
|
|
6604
|
+
recoverableUsd: recoverable ?? 0,
|
|
6605
|
+
tokens: result.claudeMdTokens,
|
|
6606
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6607
|
+
},
|
|
6608
|
+
review,
|
|
6609
|
+
sections: (currentClaudeMd ? parseSections(currentClaudeMd) : []).map((sec) => ({
|
|
6610
|
+
label: `${slug}/CLAUDE.md`,
|
|
6611
|
+
heading: sec.heading,
|
|
6612
|
+
body: sec.body
|
|
6613
|
+
}))
|
|
5922
6614
|
};
|
|
5923
6615
|
}
|
|
5924
6616
|
async function runOptimize(opts) {
|
|
5925
6617
|
const home = opts.home ?? homedir5();
|
|
5926
6618
|
let inputsClaudeMdPath = opts.claudeMdPath;
|
|
5927
6619
|
if (!inputsClaudeMdPath && opts.projectDir) {
|
|
5928
|
-
const own =
|
|
6620
|
+
const own = join10(opts.projectDir, "CLAUDE.md");
|
|
5929
6621
|
if (await pathExists2(own)) inputsClaudeMdPath = own;
|
|
5930
6622
|
}
|
|
5931
6623
|
const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
|
|
@@ -5936,7 +6628,7 @@ async function runOptimize(opts) {
|
|
|
5936
6628
|
const report = analyzeUploads(logs);
|
|
5937
6629
|
const cmd2 = analyzeClaudeMd(claudeMd);
|
|
5938
6630
|
const { pillars } = scorePillars(report, cmd2, {});
|
|
5939
|
-
const configDir =
|
|
6631
|
+
const configDir = join10(home, ".costclaw");
|
|
5940
6632
|
const { plan } = await resolvePlan(configDir, opts.plan);
|
|
5941
6633
|
const { fixes } = synthesize(report, pillars, cmd2, plan);
|
|
5942
6634
|
const auditRecoverable = cacheMissExposureUsd(report);
|
|
@@ -5959,7 +6651,7 @@ async function runOptimize(opts) {
|
|
|
5959
6651
|
if (opts.projectDir !== void 0) {
|
|
5960
6652
|
targets.push({
|
|
5961
6653
|
projectDir: opts.projectDir,
|
|
5962
|
-
artifactsDir: opts.out ??
|
|
6654
|
+
artifactsDir: opts.out ?? join10(opts.projectDir, "costclaw-out")
|
|
5963
6655
|
});
|
|
5964
6656
|
} else {
|
|
5965
6657
|
const ranked = [...report.projects].sort((a, b) => b.cost_usd - a.cost_usd);
|
|
@@ -5976,7 +6668,7 @@ async function runOptimize(opts) {
|
|
|
5976
6668
|
}
|
|
5977
6669
|
const name = artifactDirName(p.slug, dir, taken);
|
|
5978
6670
|
taken.add(name);
|
|
5979
|
-
targets.push({ projectDir: dir, artifactsDir:
|
|
6671
|
+
targets.push({ projectDir: dir, artifactsDir: join10(manifestRoot, name) });
|
|
5980
6672
|
}
|
|
5981
6673
|
}
|
|
5982
6674
|
const lines = ["CostClaw optimize", ""];
|
|
@@ -5989,22 +6681,28 @@ async function runOptimize(opts) {
|
|
|
5989
6681
|
} else {
|
|
5990
6682
|
lines.push("Generated (nothing of yours was changed).", "");
|
|
5991
6683
|
}
|
|
6684
|
+
const globalClaudeMd = opts.claudeMdPath ? void 0 : claudeMd;
|
|
6685
|
+
const globalPath = opts.claudeMdPath ? null : claudeMdSource;
|
|
6686
|
+
const { imports, notes: importNotes } = await resolveClaudeMdImports(globalPath, globalClaudeMd, home);
|
|
6687
|
+
const globalSections = globalClaudeMd ? parseSections(globalClaudeMd).map((sec) => ({ heading: sec.heading, body: sec.body })) : [];
|
|
5992
6688
|
const ctx = {
|
|
5993
6689
|
report,
|
|
5994
6690
|
pillars,
|
|
5995
6691
|
fixes,
|
|
5996
6692
|
plan,
|
|
5997
|
-
globalClaudeMd
|
|
6693
|
+
globalClaudeMd,
|
|
5998
6694
|
claudeMdOverride: opts.claudeMdPath ? claudeMd : void 0,
|
|
5999
6695
|
claudeMdFallbackSource: claudeMdSource,
|
|
6000
6696
|
version: opts.version ?? "",
|
|
6001
6697
|
dashboard: opts.dashboard !== false,
|
|
6698
|
+
globalSections,
|
|
6002
6699
|
lines
|
|
6003
6700
|
};
|
|
6004
|
-
const
|
|
6701
|
+
const outcomes = [];
|
|
6005
6702
|
for (const t of targets) {
|
|
6006
|
-
|
|
6703
|
+
outcomes.push(await generateForProject(ctx, t.projectDir, t.artifactsDir));
|
|
6007
6704
|
}
|
|
6705
|
+
const entries = outcomes.map((o) => o.entry);
|
|
6008
6706
|
const previous = await readManifest(manifestRoot);
|
|
6009
6707
|
const merged = entries.map((e) => {
|
|
6010
6708
|
const old = previous ? findEntry(previous, e.projectDir) : void 0;
|
|
@@ -6022,6 +6720,30 @@ async function runOptimize(opts) {
|
|
|
6022
6720
|
projects: merged
|
|
6023
6721
|
};
|
|
6024
6722
|
await writeManifest(manifestRoot, manifest);
|
|
6723
|
+
const globalLabel = globalPath ?? join10(home, ".claude", "CLAUDE.md");
|
|
6724
|
+
const globalReview = reviewGlobalClaudeMd({
|
|
6725
|
+
text: globalClaudeMd ?? null,
|
|
6726
|
+
imports,
|
|
6727
|
+
report,
|
|
6728
|
+
projectSections: outcomes.flatMap((o) => o.sections),
|
|
6729
|
+
projectSlugs: report.projects.map((p) => p.slug),
|
|
6730
|
+
label: globalLabel
|
|
6731
|
+
});
|
|
6732
|
+
const reviewsBySlug = new Map(outcomes.map((o) => [o.entry.slug, o.review]));
|
|
6733
|
+
const upgradeAll = buildUpgradeAll({
|
|
6734
|
+
generatedAt: manifest.generatedAt,
|
|
6735
|
+
global: { ...globalReview, path: globalLabel },
|
|
6736
|
+
projects: outcomes.map((o) => ({
|
|
6737
|
+
slug: o.entry.slug,
|
|
6738
|
+
projectDir: o.entry.projectDir,
|
|
6739
|
+
review: o.review,
|
|
6740
|
+
applyCommand: `npx costclaw apply ${o.entry.projectDir}`
|
|
6741
|
+
}))
|
|
6742
|
+
});
|
|
6743
|
+
const upgradeRoot = single ? targets[0]?.artifactsDir ?? manifestRoot : manifestRoot;
|
|
6744
|
+
const upgradeAllPath = join10(upgradeRoot, UPGRADE_ALL_NAME);
|
|
6745
|
+
await mkdir6(upgradeRoot, { recursive: true });
|
|
6746
|
+
await writeFile6(upgradeAllPath, upgradeAll, "utf8");
|
|
6025
6747
|
let indexHtmlPath = null;
|
|
6026
6748
|
if (!single && ctx.dashboard) {
|
|
6027
6749
|
const rows = merged.map((e) => ({
|
|
@@ -6038,9 +6760,10 @@ async function runOptimize(opts) {
|
|
|
6038
6760
|
version: ctx.version,
|
|
6039
6761
|
generatedAt: manifest.generatedAt,
|
|
6040
6762
|
root: manifestRoot,
|
|
6041
|
-
rows
|
|
6763
|
+
rows,
|
|
6764
|
+
review: { global: globalReview, projects: reviewsBySlug, upgradeAll, upgradeAllPath }
|
|
6042
6765
|
});
|
|
6043
|
-
indexHtmlPath =
|
|
6766
|
+
indexHtmlPath = join10(manifestRoot, DASHBOARD_NAME2);
|
|
6044
6767
|
await writeFile6(indexHtmlPath, html, "utf8");
|
|
6045
6768
|
}
|
|
6046
6769
|
if (!single) {
|
|
@@ -6056,19 +6779,22 @@ async function runOptimize(opts) {
|
|
|
6056
6779
|
"Review it, then merge it with costclaw apply <project-dir> --apply-settings. It is never applied unless you ask."
|
|
6057
6780
|
);
|
|
6058
6781
|
const top = entries[0];
|
|
6059
|
-
|
|
6060
|
-
|
|
6061
|
-
|
|
6062
|
-
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6782
|
+
const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
|
|
6783
|
+
lines.push("");
|
|
6784
|
+
lines.push(
|
|
6785
|
+
`Your CLAUDE.md review: ${num6(globalReview.changes.length)} ${globalReview.changes.length === 1 ? "change" : "changes"} to ${globalLabel}, ${num6(projectChanges)} across your ${outcomes.length === 1 ? "project" : "projects"}.`
|
|
6786
|
+
);
|
|
6787
|
+
lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
|
|
6788
|
+
lines.push(` claude "Follow ${upgradeAllPath}"`);
|
|
6789
|
+
lines.push(
|
|
6790
|
+
`It slims each CLAUDE.md, moves the dated lines out, applies the permissions you approve, and fixes the audit's harness-level findings. Per-project detail stays in each ${HARNESS_NAME2}. costclaw itself never calls a model.`
|
|
6791
|
+
);
|
|
6792
|
+
for (const note of importNotes) lines.push(` - ${note}`);
|
|
6067
6793
|
lines.push("");
|
|
6068
|
-
lines.push(`Manifest: ${
|
|
6794
|
+
lines.push(`Manifest: ${join10(manifestRoot, "index.json")}`);
|
|
6069
6795
|
lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
|
|
6070
6796
|
lines.push("Nothing left your machine.");
|
|
6071
|
-
const openPath = indexHtmlPath ?? (ctx.dashboard && top ?
|
|
6797
|
+
const openPath = indexHtmlPath ?? (ctx.dashboard && top ? join10(top.artifactsDir, DASHBOARD_NAME2) : null);
|
|
6072
6798
|
if (openPath) {
|
|
6073
6799
|
lines.push("");
|
|
6074
6800
|
const canServe = opts.serve !== false && !process.env["VITEST"] && !process.env["CI"] && !process.env["COSTCLAW_NO_OPEN"] && manifest.projects.length > 0;
|
|
@@ -6104,12 +6830,12 @@ async function runOptimize(opts) {
|
|
|
6104
6830
|
openInBrowser(openPath);
|
|
6105
6831
|
}
|
|
6106
6832
|
}
|
|
6107
|
-
return { output: lines.join("\n"), root: manifestRoot, manifest, indexHtmlPath };
|
|
6833
|
+
return { output: lines.join("\n"), root: manifestRoot, manifest, indexHtmlPath, upgradeAllPath };
|
|
6108
6834
|
}
|
|
6109
6835
|
|
|
6110
6836
|
// src/badge-command.ts
|
|
6111
6837
|
import { writeFile as writeFile7 } from "fs/promises";
|
|
6112
|
-
import { resolve as
|
|
6838
|
+
import { resolve as resolve6 } from "path";
|
|
6113
6839
|
|
|
6114
6840
|
// src/badge.ts
|
|
6115
6841
|
var HEIGHT2 = 20;
|
|
@@ -6133,14 +6859,14 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
|
|
|
6133
6859
|
async function runBadge(opts) {
|
|
6134
6860
|
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
6135
6861
|
const svg = renderBadge(record);
|
|
6136
|
-
const target =
|
|
6862
|
+
const target = resolve6(opts.out || DEFAULT_BADGE_FILE);
|
|
6137
6863
|
await writeFile7(target, svg, "utf8");
|
|
6138
6864
|
return { output: `Badge written to ${target}`, record, target };
|
|
6139
6865
|
}
|
|
6140
6866
|
|
|
6141
6867
|
// src/diff-command.ts
|
|
6142
|
-
import { readdir as readdir4, readFile as
|
|
6143
|
-
import { join as
|
|
6868
|
+
import { readdir as readdir4, readFile as readFile11 } from "fs/promises";
|
|
6869
|
+
import { join as join11 } from "path";
|
|
6144
6870
|
import { homedir as homedir6 } from "os";
|
|
6145
6871
|
|
|
6146
6872
|
// src/format-diff.ts
|
|
@@ -6229,7 +6955,7 @@ function formatDiff(d) {
|
|
|
6229
6955
|
async function readRecord(path) {
|
|
6230
6956
|
let text2;
|
|
6231
6957
|
try {
|
|
6232
|
-
text2 = await
|
|
6958
|
+
text2 = await readFile11(path, "utf8");
|
|
6233
6959
|
} catch {
|
|
6234
6960
|
throw new Error(`Could not read ${path}.`);
|
|
6235
6961
|
}
|
|
@@ -6245,7 +6971,7 @@ async function runDiff(opts) {
|
|
|
6245
6971
|
let pathA = opts.fileA;
|
|
6246
6972
|
let pathB = opts.fileB;
|
|
6247
6973
|
if (!pathA || !pathB) {
|
|
6248
|
-
const dir =
|
|
6974
|
+
const dir = join11(opts.home ?? homedir6(), ".costclaw", "history");
|
|
6249
6975
|
let files = [];
|
|
6250
6976
|
try {
|
|
6251
6977
|
files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
@@ -6256,8 +6982,8 @@ async function runDiff(opts) {
|
|
|
6256
6982
|
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
6257
6983
|
);
|
|
6258
6984
|
}
|
|
6259
|
-
pathA =
|
|
6260
|
-
pathB =
|
|
6985
|
+
pathA = join11(dir, files[files.length - 2]);
|
|
6986
|
+
pathB = join11(dir, files[files.length - 1]);
|
|
6261
6987
|
}
|
|
6262
6988
|
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
6263
6989
|
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
@@ -6327,7 +7053,7 @@ function parseApplyFlags(args) {
|
|
|
6327
7053
|
};
|
|
6328
7054
|
}
|
|
6329
7055
|
function cliVersion() {
|
|
6330
|
-
return true ? "0.
|
|
7056
|
+
return true ? "0.12.0" : "0.0.0-dev";
|
|
6331
7057
|
}
|
|
6332
7058
|
function isHelpRequest(command, args) {
|
|
6333
7059
|
if (command === void 0) return false;
|
|
@@ -6361,7 +7087,9 @@ function helpText() {
|
|
|
6361
7087
|
"money back, so the audit reframes the headline as recoverable usage: the share",
|
|
6362
7088
|
"of your token consumption (and rate-limit headroom) you could win back. The",
|
|
6363
7089
|
"value is saved to ~/.costclaw/config.json so later runs remember it;",
|
|
6364
|
-
"--plan api switches back.",
|
|
7090
|
+
"--plan api switches back. Pass nothing and the first interactive run asks",
|
|
7091
|
+
"once and saves the answer; piped, --json and CI runs are never asked and",
|
|
7092
|
+
"assume API rates.",
|
|
6365
7093
|
"",
|
|
6366
7094
|
"diff compares two audits and shows the movement: new spend since the baseline,",
|
|
6367
7095
|
"the marginal cache hit rate for just that period, score changes per pillar, and",
|