costclaw 0.8.1 → 0.9.1
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 +3 -1
- package/dist/index.js +518 -218
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -113,7 +113,9 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--h
|
|
|
113
113
|
disable). `--html <file>` picks the path; `--no-html` skips the file;
|
|
114
114
|
`--json` runs stay file-free unless `--html` is passed explicitly. Set
|
|
115
115
|
`COSTCLAW_NO_OPEN=1` to write reports without launching a browser (CI and
|
|
116
|
-
test runners are detected and never open one).
|
|
116
|
+
test runners are detected and never open one). The report ends with a
|
|
117
|
+
"What to do next" ramp: the commands to run next, how the optimize license
|
|
118
|
+
works, and a command reference.
|
|
117
119
|
- `--card [file]` also write a shareable score card SVG (default
|
|
118
120
|
`costclaw-card.svg`): your score, band, recoverable spend, cache hit rate, and
|
|
119
121
|
strongest pillar. A static file, no fonts or network calls.
|
package/dist/index.js
CHANGED
|
@@ -153,6 +153,39 @@ function targetFor(name, input) {
|
|
|
153
153
|
if (name === "Agent") return s(input.subagent_type ?? input.description, 60);
|
|
154
154
|
return null;
|
|
155
155
|
}
|
|
156
|
+
var PLAN_TOOLS = /* @__PURE__ */ new Set(["EnterPlanMode", "ExitPlanMode", "TodoWrite", "TaskCreate", "Skill", "Workflow"]);
|
|
157
|
+
var VERIFY_RE = /^(?:(?:npm|pnpm|yarn|bun|deno|npx|python3?|py|make|dotnet|mvn|gradle|cargo|go)(?:\s+\S+)*?\s+(?:test|tests|vitest|jest|pytest|typecheck|tsc|lint|build|check|verify|clippy|vet)(?:[:\s]|$)|(?:pytest|tsc|vitest|jest|eslint|ruff|mypy|golangci-lint)(?:\s|$))/i;
|
|
158
|
+
var CORRECTION_RE = /^(?:no[,.!\s]|nope\b|wrong\b|that'?s (?:not|wrong)|not what i|undo\b|revert\b|stop\b|don'?t\b|why did you|you broke|still (?:broken|failing|wrong|not))/i;
|
|
159
|
+
var RICH_RE = /(?:^|\s)@\S|[A-Za-z]:[\\/]|(?:^|\s)\.?\/\S+\/|https?:\/\/|```|\n\s*[-*]\s/;
|
|
160
|
+
var SLASH_PREFIXES = ["<command-name>", "<local-command", "<command-message>"];
|
|
161
|
+
var INTERRUPT_MARK = "[Request interrupted by user";
|
|
162
|
+
function isVerifyCommand(command) {
|
|
163
|
+
let s = command.trim();
|
|
164
|
+
const hop = /^(?:cd|Set-Location|pushd)\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/i;
|
|
165
|
+
for (; ; ) {
|
|
166
|
+
const next = s.replace(hop, "");
|
|
167
|
+
if (next === s) break;
|
|
168
|
+
s = next;
|
|
169
|
+
}
|
|
170
|
+
return VERIFY_RE.test(s);
|
|
171
|
+
}
|
|
172
|
+
function humanText(rec) {
|
|
173
|
+
if (rec.isMeta) return null;
|
|
174
|
+
const c = rec.message?.content;
|
|
175
|
+
if (typeof c === "string") return c.trim() ? { text: c, hasImage: false } : null;
|
|
176
|
+
if (!Array.isArray(c)) return null;
|
|
177
|
+
let text2 = "";
|
|
178
|
+
let hasImage = false;
|
|
179
|
+
for (const b of c) {
|
|
180
|
+
if (!b || typeof b !== "object") continue;
|
|
181
|
+
if (b.type === "text" && typeof b.text === "string") text2 += (text2 ? "\n" : "") + b.text;
|
|
182
|
+
else if (b.type === "image") hasImage = true;
|
|
183
|
+
}
|
|
184
|
+
return text2.trim() || hasImage ? { text: text2, hasImage } : null;
|
|
185
|
+
}
|
|
186
|
+
function emptyPromptSignals() {
|
|
187
|
+
return { humanPrompts: 0, openerWords: null, openerRich: false, corrections: 0, interrupts: 0, slashCommands: 0, planEvents: 0, verifyRuns: 0 };
|
|
188
|
+
}
|
|
156
189
|
var isToolUse = (b) => !!b && typeof b === "object" && b.type === "tool_use" && typeof b.name === "string";
|
|
157
190
|
function extractTools(content) {
|
|
158
191
|
const names = [];
|
|
@@ -192,8 +225,10 @@ function parseSession(text2, opts = {}) {
|
|
|
192
225
|
kind: opts.kind ?? "main",
|
|
193
226
|
parentSessionId: opts.parentSessionId ?? null,
|
|
194
227
|
turnCache: [],
|
|
195
|
-
costBuckets: []
|
|
228
|
+
costBuckets: [],
|
|
229
|
+
prompting: emptyPromptSignals()
|
|
196
230
|
};
|
|
231
|
+
const ps = s.prompting;
|
|
197
232
|
const seen = /* @__PURE__ */ new Set();
|
|
198
233
|
const buckets = /* @__PURE__ */ new Map();
|
|
199
234
|
const BUCKET_MS = 15 * 60 * 1e3;
|
|
@@ -215,13 +250,36 @@ function parseSession(text2, opts = {}) {
|
|
|
215
250
|
if (s.endedAt === null || rec.timestamp > s.endedAt) s.endedAt = rec.timestamp;
|
|
216
251
|
}
|
|
217
252
|
if (rec.type !== "user" && rec.type !== "assistant") continue;
|
|
218
|
-
if (rec.type === "user")
|
|
219
|
-
|
|
253
|
+
if (rec.type === "user") {
|
|
254
|
+
s.userRecords += 1;
|
|
255
|
+
const h = humanText(rec);
|
|
256
|
+
if (h) {
|
|
257
|
+
const t = h.text.trimStart();
|
|
258
|
+
if (t.includes(INTERRUPT_MARK)) ps.interrupts += 1;
|
|
259
|
+
else if (SLASH_PREFIXES.some((p) => t.startsWith(p))) ps.slashCommands += 1;
|
|
260
|
+
else if (!t.startsWith("<") || h.hasImage) {
|
|
261
|
+
ps.humanPrompts += 1;
|
|
262
|
+
if (ps.openerWords === null) {
|
|
263
|
+
ps.openerWords = t.split(/\s+/).filter(Boolean).length;
|
|
264
|
+
ps.openerRich = h.hasImage || RICH_RE.test(h.text);
|
|
265
|
+
}
|
|
266
|
+
if (CORRECTION_RE.test(t)) ps.corrections += 1;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
} else s.assistantRecords += 1;
|
|
220
270
|
const model = rec.message?.model;
|
|
221
271
|
if (model && model !== "<synthetic>") modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);
|
|
222
272
|
if (rec.type === "assistant") {
|
|
223
273
|
const { names, events } = extractTools(rec.message?.content);
|
|
224
|
-
for (const n of names)
|
|
274
|
+
for (const n of names) {
|
|
275
|
+
s.toolUsage[n] = (s.toolUsage[n] ?? 0) + 1;
|
|
276
|
+
if (PLAN_TOOLS.has(n)) ps.planEvents += 1;
|
|
277
|
+
}
|
|
278
|
+
if (Array.isArray(rec.message?.content)) {
|
|
279
|
+
for (const b of rec.message.content) {
|
|
280
|
+
if (isToolUse(b) && (b.name === "Bash" || b.name === "PowerShell") && typeof b.input?.command === "string" && isVerifyCommand(b.input.command)) ps.verifyRuns += 1;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
225
283
|
const requestId = rec.requestId || rec.message?.requestId || null;
|
|
226
284
|
for (const e of events) s.toolEvents.push({ name: e.name, requestId, target: e.target });
|
|
227
285
|
const usage = rec.message?.usage;
|
|
@@ -813,7 +871,7 @@ var PILLARS = {
|
|
|
813
871
|
id: "prompting",
|
|
814
872
|
name: "Prompting patterns",
|
|
815
873
|
weight: 0.15,
|
|
816
|
-
description: "Whether you plan before
|
|
874
|
+
description: "Whether you give the agent a check to run, plan before big changes, open with specifics, correct early, and reuse skills instead of retyping.",
|
|
817
875
|
color: "#60A5FA"
|
|
818
876
|
},
|
|
819
877
|
session_mgmt: {
|
|
@@ -964,6 +1022,70 @@ function optionScore(question, optionId) {
|
|
|
964
1022
|
return opt ? opt.score : null;
|
|
965
1023
|
}
|
|
966
1024
|
|
|
1025
|
+
// ../../packages/engine/src/prompting.ts
|
|
1026
|
+
var SUBSTANTIAL_MIN_TURNS = 20;
|
|
1027
|
+
var SHORT_OPENER_MAX_WORDS = 12;
|
|
1028
|
+
var CHURN_MIN_CORRECTIONS = 3;
|
|
1029
|
+
var EDIT_TOOLS = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
|
|
1030
|
+
var REUSE_TOOLS = ["Skill", "Workflow", "Agent"];
|
|
1031
|
+
function editCalls(s) {
|
|
1032
|
+
let n = 0;
|
|
1033
|
+
for (const t of EDIT_TOOLS) n += s.toolUsage[t] ?? 0;
|
|
1034
|
+
return n;
|
|
1035
|
+
}
|
|
1036
|
+
function reuseCalls(s) {
|
|
1037
|
+
let n = 0;
|
|
1038
|
+
for (const t of REUSE_TOOLS) n += s.toolUsage[t] ?? 0;
|
|
1039
|
+
return n;
|
|
1040
|
+
}
|
|
1041
|
+
function aggregatePrompting(report) {
|
|
1042
|
+
const out = {
|
|
1043
|
+
sessions: 0,
|
|
1044
|
+
editSessions: 0,
|
|
1045
|
+
verifiedSessions: 0,
|
|
1046
|
+
substantialSessions: 0,
|
|
1047
|
+
plannedSessions: 0,
|
|
1048
|
+
openerSessions: 0,
|
|
1049
|
+
shortOpeners: 0,
|
|
1050
|
+
medianOpenerWords: null,
|
|
1051
|
+
promptedSessions: 0,
|
|
1052
|
+
churnSessions: 0,
|
|
1053
|
+
reuseSessions: 0
|
|
1054
|
+
};
|
|
1055
|
+
const openers = [];
|
|
1056
|
+
for (const p of report.projects) {
|
|
1057
|
+
for (const s of p.sessions) {
|
|
1058
|
+
if (s.kind !== "main" || !s.prompting) continue;
|
|
1059
|
+
const ps = s.prompting;
|
|
1060
|
+
out.sessions += 1;
|
|
1061
|
+
const edits = editCalls(s);
|
|
1062
|
+
if (edits > 0) {
|
|
1063
|
+
out.editSessions += 1;
|
|
1064
|
+
if (ps.verifyRuns > 0) out.verifiedSessions += 1;
|
|
1065
|
+
if (s.assistantRecords >= SUBSTANTIAL_MIN_TURNS) {
|
|
1066
|
+
out.substantialSessions += 1;
|
|
1067
|
+
if (ps.planEvents > 0) out.plannedSessions += 1;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (ps.openerWords !== null) {
|
|
1071
|
+
out.openerSessions += 1;
|
|
1072
|
+
openers.push(ps.openerWords);
|
|
1073
|
+
if (ps.openerWords < SHORT_OPENER_MAX_WORDS && !ps.openerRich) out.shortOpeners += 1;
|
|
1074
|
+
}
|
|
1075
|
+
if (ps.humanPrompts > 0) {
|
|
1076
|
+
out.promptedSessions += 1;
|
|
1077
|
+
if (ps.corrections + ps.interrupts >= CHURN_MIN_CORRECTIONS) out.churnSessions += 1;
|
|
1078
|
+
}
|
|
1079
|
+
if (ps.slashCommands > 0 || reuseCalls(s) > 0) out.reuseSessions += 1;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
if (openers.length > 0) {
|
|
1083
|
+
openers.sort((a, b) => a - b);
|
|
1084
|
+
out.medianOpenerWords = openers[Math.floor(openers.length / 2)] ?? null;
|
|
1085
|
+
}
|
|
1086
|
+
return out;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
967
1089
|
// ../../packages/engine/src/scoring.ts
|
|
968
1090
|
function clamp2(n, lo = 0, hi = 100) {
|
|
969
1091
|
return Math.max(lo, Math.min(hi, n));
|
|
@@ -1011,7 +1133,7 @@ function hasAnyDuration(report) {
|
|
|
1011
1133
|
}
|
|
1012
1134
|
return false;
|
|
1013
1135
|
}
|
|
1014
|
-
function buildChecks(report,
|
|
1136
|
+
function buildChecks(report, cmd2, answers, setup) {
|
|
1015
1137
|
const checks = [];
|
|
1016
1138
|
const s = report.summary;
|
|
1017
1139
|
checks.push(
|
|
@@ -1019,8 +1141,8 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
1019
1141
|
"cmd_size",
|
|
1020
1142
|
"claude_md",
|
|
1021
1143
|
"Size",
|
|
1022
|
-
|
|
1023
|
-
|
|
1144
|
+
cmd2.present ? cmd2.sizeScore : null,
|
|
1145
|
+
cmd2.present ? `Your CLAUDE.md is ${cmd2.chars.toLocaleString()} characters, about ${cmd2.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
|
|
1024
1146
|
"claudemd"
|
|
1025
1147
|
)
|
|
1026
1148
|
);
|
|
@@ -1029,8 +1151,8 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
1029
1151
|
"cmd_structure",
|
|
1030
1152
|
"claude_md",
|
|
1031
1153
|
"Structure",
|
|
1032
|
-
|
|
1033
|
-
|
|
1154
|
+
cmd2.present ? cmd2.structureScore : null,
|
|
1155
|
+
cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${cmd2.chars.toLocaleString()} characters.` : "No CLAUDE.md was provided.",
|
|
1034
1156
|
"claudemd"
|
|
1035
1157
|
)
|
|
1036
1158
|
);
|
|
@@ -1039,8 +1161,8 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
1039
1161
|
"cmd_stability",
|
|
1040
1162
|
"claude_md",
|
|
1041
1163
|
"Cache stability",
|
|
1042
|
-
|
|
1043
|
-
|
|
1164
|
+
cmd2.present ? cmd2.stabilityScore : null,
|
|
1165
|
+
cmd2.present ? `${cmd2.volatileMarkers} volatile marker${cmd2.volatileMarkers === 1 ? "" : "s"} (dates, TODOs, "updated" notes) that change between sessions and reset the cache.` : "No CLAUDE.md was provided.",
|
|
1044
1166
|
"claudemd"
|
|
1045
1167
|
)
|
|
1046
1168
|
);
|
|
@@ -1072,6 +1194,64 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
1072
1194
|
)
|
|
1073
1195
|
);
|
|
1074
1196
|
checks.push(questionnaireCheck("clear_between", "Clearing between tasks", answers));
|
|
1197
|
+
const pr = aggregatePrompting(report);
|
|
1198
|
+
const pct2 = (n, d) => d > 0 ? Math.round(n / d * 100) : 0;
|
|
1199
|
+
const plural3 = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
|
|
1200
|
+
const verifiedShare = pr.editSessions > 0 ? pr.verifiedSessions / pr.editSessions : 0;
|
|
1201
|
+
checks.push(
|
|
1202
|
+
makeCheck(
|
|
1203
|
+
"verify_loop",
|
|
1204
|
+
"prompting",
|
|
1205
|
+
"Verification loop",
|
|
1206
|
+
pr.editSessions > 0 ? clamp2(verifiedShare / 0.6 * 100) : null,
|
|
1207
|
+
pr.editSessions === 0 ? "No session edited files, so there is nothing to verify." : `${pr.verifiedSessions} of ${plural3(pr.editSessions, "session")} that edited files (${pct2(pr.verifiedSessions, pr.editSessions)}%) also ran a test, build, typecheck, or lint. Without a check the agent can run, "looks done" is the only signal and you become the verification loop.`,
|
|
1208
|
+
"metrics"
|
|
1209
|
+
)
|
|
1210
|
+
);
|
|
1211
|
+
const plannedShare = pr.substantialSessions > 0 ? pr.plannedSessions / pr.substantialSessions : 0;
|
|
1212
|
+
checks.push(
|
|
1213
|
+
makeCheck(
|
|
1214
|
+
"plan_before_code",
|
|
1215
|
+
"prompting",
|
|
1216
|
+
"Plan before code",
|
|
1217
|
+
pr.substantialSessions > 0 ? clamp2(plannedShare / 0.6 * 100) : null,
|
|
1218
|
+
pr.substantialSessions === 0 ? `No session reached ${SUBSTANTIAL_MIN_TURNS} turns with edits, so planning was not assessed.` : `${pr.plannedSessions} of ${plural3(pr.substantialSessions, "substantial session")} (${SUBSTANTIAL_MIN_TURNS}+ turns with edits, ${pct2(pr.plannedSessions, pr.substantialSessions)}%) used plan mode, a task list, a skill, or a workflow before building. Small clear fixes are excluded on purpose.`,
|
|
1219
|
+
"metrics"
|
|
1220
|
+
)
|
|
1221
|
+
);
|
|
1222
|
+
const shortShare = pr.openerSessions > 0 ? pr.shortOpeners / pr.openerSessions : 0;
|
|
1223
|
+
checks.push(
|
|
1224
|
+
makeCheck(
|
|
1225
|
+
"prompt_specificity",
|
|
1226
|
+
"prompting",
|
|
1227
|
+
"Prompt specificity",
|
|
1228
|
+
pr.openerSessions > 0 ? clamp2(100 - shortShare * 180) : null,
|
|
1229
|
+
pr.openerSessions === 0 ? "No human opening prompt was found." : `${pr.shortOpeners} of ${plural3(pr.openerSessions, "session")} (${pct2(pr.shortOpeners, pr.openerSessions)}%) opened with under ${SHORT_OPENER_MAX_WORDS} words and no file, path, link, image, or pasted context; the median opener is ${pr.medianOpenerWords ?? 0} words. Vague openers cost corrections later.`,
|
|
1230
|
+
"metrics"
|
|
1231
|
+
)
|
|
1232
|
+
);
|
|
1233
|
+
const churnShare = pr.promptedSessions > 0 ? pr.churnSessions / pr.promptedSessions : 0;
|
|
1234
|
+
checks.push(
|
|
1235
|
+
makeCheck(
|
|
1236
|
+
"correction_churn",
|
|
1237
|
+
"prompting",
|
|
1238
|
+
"Correction churn",
|
|
1239
|
+
pr.promptedSessions > 0 ? clamp2(100 - churnShare * 300) : null,
|
|
1240
|
+
pr.promptedSessions === 0 ? "No human prompts were found." : `${pr.churnSessions} of ${plural3(pr.promptedSessions, "session")} (${pct2(pr.churnSessions, pr.promptedSessions)}%) hit ${CHURN_MIN_CORRECTIONS} or more corrections or interrupts. After two failed corrections the context is full of failed approaches; clear and re-prompt with what you learned.`,
|
|
1241
|
+
"metrics"
|
|
1242
|
+
)
|
|
1243
|
+
);
|
|
1244
|
+
const reuseShare = pr.sessions > 0 ? pr.reuseSessions / pr.sessions : 0;
|
|
1245
|
+
checks.push(
|
|
1246
|
+
makeCheck(
|
|
1247
|
+
"reusable_workflows",
|
|
1248
|
+
"prompting",
|
|
1249
|
+
"Reusable workflows",
|
|
1250
|
+
pr.sessions > 0 ? clamp2(reuseShare / 0.3 * 100) : null,
|
|
1251
|
+
pr.sessions === 0 ? "No sessions carried prompt signals." : `${pr.reuseSessions} of ${plural3(pr.sessions, "session")} (${pct2(pr.reuseSessions, pr.sessions)}%) used a slash command, skill, workflow, or subagent. Repeated work belongs in a skill so the prompt is written once and the research stays out of your main context.`,
|
|
1252
|
+
"metrics"
|
|
1253
|
+
)
|
|
1254
|
+
);
|
|
1075
1255
|
checks.push(questionnaireCheck("plan_first", "Planning first", answers));
|
|
1076
1256
|
checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
|
|
1077
1257
|
const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS" || f.ruleId === "REDUNDANT_TARGET_THRASH");
|
|
@@ -1204,8 +1384,8 @@ function buildChecks(report, cmd, answers, setup) {
|
|
|
1204
1384
|
checks.push(questionnaireCheck("model_choice", "Model fit", answers));
|
|
1205
1385
|
return checks;
|
|
1206
1386
|
}
|
|
1207
|
-
function scorePillars(report,
|
|
1208
|
-
const checks = buildChecks(report,
|
|
1387
|
+
function scorePillars(report, cmd2, answers, setup) {
|
|
1388
|
+
const checks = buildChecks(report, cmd2, answers, setup);
|
|
1209
1389
|
const pillars = PILLAR_ORDER.map((id) => {
|
|
1210
1390
|
const cfg = PILLARS[id];
|
|
1211
1391
|
const pillarChecks = checks.filter((c) => c.pillar === id);
|
|
@@ -1228,6 +1408,26 @@ function scorePillars(report, cmd, answers, setup) {
|
|
|
1228
1408
|
|
|
1229
1409
|
// ../../packages/engine/src/synthesize.ts
|
|
1230
1410
|
var CHECK_FIX = {
|
|
1411
|
+
verify_loop: {
|
|
1412
|
+
title: "Give the agent a check it can run",
|
|
1413
|
+
action: "End the prompt with the check: 'run the tests after implementing', 'verify the build succeeds', or a screenshot to compare. The loop then closes on its own instead of waiting for you to notice a mistake."
|
|
1414
|
+
},
|
|
1415
|
+
plan_before_code: {
|
|
1416
|
+
title: "Plan before multi-file changes",
|
|
1417
|
+
action: "For work that touches several files or unfamiliar code, start in plan mode (Shift+Tab) or ask for a plan first, approve it, then implement. Skip the plan when you could describe the diff in one sentence."
|
|
1418
|
+
},
|
|
1419
|
+
prompt_specificity: {
|
|
1420
|
+
title: "Open with specifics, not a headline",
|
|
1421
|
+
action: "Name the file with @, paste the error or screenshot, state the scenario and what 'fixed' looks like. 'fix the login bug' becomes 'login fails after session timeout; check src/auth token refresh; write a failing test, then fix it'."
|
|
1422
|
+
},
|
|
1423
|
+
correction_churn: {
|
|
1424
|
+
title: "Clear and re-prompt after two corrections",
|
|
1425
|
+
action: "When a session needs a third correction, run /clear and write a fresh prompt that includes what you learned. A clean session with a better prompt beats a long one full of failed approaches."
|
|
1426
|
+
},
|
|
1427
|
+
reusable_workflows: {
|
|
1428
|
+
title: "Turn repeated prompts into skills",
|
|
1429
|
+
action: "Put any workflow you have typed twice into .claude/skills/<name>/SKILL.md and invoke it with /name. Delegate broad investigation to a subagent so the reading stays out of your main context."
|
|
1430
|
+
},
|
|
1231
1431
|
cmd_structure: {
|
|
1232
1432
|
title: "Give CLAUDE.md clear structure",
|
|
1233
1433
|
action: "Break the file into sections with headings and short bulleted rules so the agent finds the right guidance fast instead of scanning a wall of text."
|
|
@@ -1284,11 +1484,11 @@ function severityRank(s) {
|
|
|
1284
1484
|
function num2(n) {
|
|
1285
1485
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1286
1486
|
}
|
|
1287
|
-
function sizeFix(
|
|
1288
|
-
if (
|
|
1487
|
+
function sizeFix(cmd2) {
|
|
1488
|
+
if (cmd2.chars > 6e3) {
|
|
1289
1489
|
return {
|
|
1290
1490
|
title: "Trim your CLAUDE.md",
|
|
1291
|
-
action: `Your CLAUDE.md is an estimated ${num2(
|
|
1491
|
+
action: `Your CLAUDE.md is an estimated ${num2(cmd2.estTokens)} tokens (${num2(cmd2.chars)} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
|
|
1292
1492
|
};
|
|
1293
1493
|
}
|
|
1294
1494
|
return {
|
|
@@ -1296,7 +1496,7 @@ function sizeFix(cmd) {
|
|
|
1296
1496
|
action: "Your CLAUDE.md is thin. Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
|
|
1297
1497
|
};
|
|
1298
1498
|
}
|
|
1299
|
-
function synthesize(report, pillars,
|
|
1499
|
+
function synthesize(report, pillars, cmd2, plan = "api") {
|
|
1300
1500
|
const headlineWasteUsd = cacheMissExposureUsd(report);
|
|
1301
1501
|
const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
|
|
1302
1502
|
const spend = report.summary.cost_usd;
|
|
@@ -1376,8 +1576,8 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1376
1576
|
let action;
|
|
1377
1577
|
if (marathonBest && marathonUsd >= 0.25 * exposure && marathonBest.lateHit < marathonBest.earlyHit) {
|
|
1378
1578
|
action = `The longest sessions started at ${pct2(marathonBest.earlyHit)}% cache reuse and finished at ${pct2(marathonBest.lateHit)}%. Compact or start a fresh session before the context outgrows the cache: the later turns re-pay for context you already bought.`;
|
|
1379
|
-
} else if (
|
|
1380
|
-
action = `Your CLAUDE.md carries ${
|
|
1579
|
+
} else if (cmd2.present && cmd2.stabilityScore != null && cmd2.stabilityScore < GAP_THRESHOLD && cmd2.volatileMarkers >= 5) {
|
|
1580
|
+
action = `Your CLAUDE.md carries ${cmd2.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
|
|
1381
1581
|
} else if (badCacheBest) {
|
|
1382
1582
|
action = `The last ${badCacheBest.sessionsConsidered} sessions in ${badCacheBest.slug} reused only ${pct2(badCacheBest.recentHitRate)}% from the cache. Open each session the same way (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price.`;
|
|
1383
1583
|
} else {
|
|
@@ -1491,7 +1691,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
|
|
|
1491
1691
|
for (const p of pillars) {
|
|
1492
1692
|
for (const c of p.checks) {
|
|
1493
1693
|
if (!c.gap || covered.has(c.id)) continue;
|
|
1494
|
-
const tmpl = c.id === "cmd_size" ? sizeFix(
|
|
1694
|
+
const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) : CHECK_FIX[c.id];
|
|
1495
1695
|
if (!tmpl) continue;
|
|
1496
1696
|
const severity = (c.score ?? 100) < 40 ? "warn" : "info";
|
|
1497
1697
|
fixes.push({
|
|
@@ -1791,7 +1991,7 @@ var NOTE_MAX = 80;
|
|
|
1791
1991
|
function extractCommandNotes(body) {
|
|
1792
1992
|
const notes = /* @__PURE__ */ new Map();
|
|
1793
1993
|
if (!body) return notes;
|
|
1794
|
-
const keyOf = (
|
|
1994
|
+
const keyOf = (cmd2) => cmd2.trim().replace(/\s+/g, " ");
|
|
1795
1995
|
for (const raw of body.split("\n")) {
|
|
1796
1996
|
const line = raw.trim();
|
|
1797
1997
|
if (!line || line.startsWith("```") || line.startsWith("#")) continue;
|
|
@@ -2351,9 +2551,9 @@ function buildSettings(project) {
|
|
|
2351
2551
|
const projectAllow = /* @__PURE__ */ new Set();
|
|
2352
2552
|
for (const c of project?.commands ?? []) {
|
|
2353
2553
|
if (!SAFE_COMMAND_LABELS.has(c.label)) continue;
|
|
2354
|
-
const
|
|
2355
|
-
if (!
|
|
2356
|
-
projectAllow.add(`Bash(${
|
|
2554
|
+
const cmd2 = c.command.trim();
|
|
2555
|
+
if (!cmd2 || cmd2.includes("<")) continue;
|
|
2556
|
+
projectAllow.add(`Bash(${cmd2}:*)`);
|
|
2357
2557
|
}
|
|
2358
2558
|
const allow = [...BASE_ALLOW, ...[...projectAllow].sort()];
|
|
2359
2559
|
const settings = { permissions: { allow, deny: [...BASE_DENY] } };
|
|
@@ -2668,10 +2868,10 @@ function cleanPillar(p) {
|
|
|
2668
2868
|
}
|
|
2669
2869
|
function buildAudit(input, opts = {}) {
|
|
2670
2870
|
const report = analyzeUploads(input.logs);
|
|
2671
|
-
const
|
|
2672
|
-
const { pillars, overall, band } = scorePillars(report,
|
|
2871
|
+
const cmd2 = analyzeClaudeMd(input.claudeMd);
|
|
2872
|
+
const { pillars, overall, band } = scorePillars(report, cmd2, input.questionnaire, input.setup);
|
|
2673
2873
|
const plan = input.plan ?? "api";
|
|
2674
|
-
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars,
|
|
2874
|
+
const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd2, plan);
|
|
2675
2875
|
const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
|
|
2676
2876
|
return {
|
|
2677
2877
|
schemaVersion: "1",
|
|
@@ -2680,8 +2880,8 @@ function buildAudit(input, opts = {}) {
|
|
|
2680
2880
|
contactEmail: input.contactEmail?.trim() || null,
|
|
2681
2881
|
inputsSummary: {
|
|
2682
2882
|
logFiles: input.logs.length,
|
|
2683
|
-
hasClaudeMd:
|
|
2684
|
-
claudeMdChars:
|
|
2883
|
+
hasClaudeMd: cmd2.present,
|
|
2884
|
+
claudeMdChars: cmd2.chars,
|
|
2685
2885
|
questionnaireAnswered: answered
|
|
2686
2886
|
},
|
|
2687
2887
|
usageMetrics: toUsageMetrics(report),
|
|
@@ -2821,9 +3021,9 @@ var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
|
|
|
2821
3021
|
var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
|
|
2822
3022
|
|
|
2823
3023
|
// src/audit-command.ts
|
|
2824
|
-
import { mkdir as
|
|
2825
|
-
import { join as
|
|
2826
|
-
import { homedir as
|
|
3024
|
+
import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
3025
|
+
import { join as join5, resolve } from "path";
|
|
3026
|
+
import { homedir as homedir4 } from "os";
|
|
2827
3027
|
|
|
2828
3028
|
// src/open.ts
|
|
2829
3029
|
import { spawn } from "child_process";
|
|
@@ -2831,8 +3031,8 @@ function openInBrowser(target) {
|
|
|
2831
3031
|
if (process.env["VITEST"] || process.env["CI"] || process.env["COSTCLAW_NO_OPEN"]) return;
|
|
2832
3032
|
try {
|
|
2833
3033
|
const platform = process.platform;
|
|
2834
|
-
const [
|
|
2835
|
-
const child = spawn(
|
|
3034
|
+
const [cmd2, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
3035
|
+
const child = spawn(cmd2, args, { detached: true, stdio: "ignore" });
|
|
2836
3036
|
child.on("error", () => {
|
|
2837
3037
|
});
|
|
2838
3038
|
child.unref();
|
|
@@ -3339,6 +3539,61 @@ function dollarFixCard(f) {
|
|
|
3339
3539
|
function otherFixCard(f) {
|
|
3340
3540
|
return `<li class="fix other"><div class="fix-head"><span class="fix-title">${esc(f.title)}</span></div><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
|
|
3341
3541
|
}
|
|
3542
|
+
var SITE_URL = "https://costclaw.io";
|
|
3543
|
+
var PRICING_URL = "https://costclaw.io/#pricing";
|
|
3544
|
+
var CHECKOUT_URL = "https://buy.stripe.com/00wfZhgCH3X62v0cX9ew807";
|
|
3545
|
+
var SUPPORT_EMAIL = "wes@dashclaw.io";
|
|
3546
|
+
var LICENSE_PRICE = "$39";
|
|
3547
|
+
function cmd(c) {
|
|
3548
|
+
return `<pre class="cmd"><code>${esc(c)}</code></pre>`;
|
|
3549
|
+
}
|
|
3550
|
+
function step(n, title, body) {
|
|
3551
|
+
return `<li class="step"><div class="step-n">${n}</div><div class="step-body"><h3>${esc(title)}</h3>${body}</div></li>`;
|
|
3552
|
+
}
|
|
3553
|
+
function nextStepsSection(record, meta) {
|
|
3554
|
+
const licensed = meta.license?.active === true;
|
|
3555
|
+
const steps = [];
|
|
3556
|
+
let n = 1;
|
|
3557
|
+
if (meta.planSource === "default") {
|
|
3558
|
+
steps.push(step(
|
|
3559
|
+
n++,
|
|
3560
|
+
"Tell costclaw how you pay",
|
|
3561
|
+
`<p>On a Claude subscription the dollar figures above are token value, not money back. Declare your plan once and the report reframes everything as usage you win back.</p>` + cmd("npx costclaw audit --plan max20x # or pro, max5x, api")
|
|
3562
|
+
));
|
|
3563
|
+
}
|
|
3564
|
+
const waste = record.headlineWasteUsd;
|
|
3565
|
+
const wasteLine = waste > 0 ? `This audit found <strong>${esc(usd3(waste))}</strong> of recoverable input spend. ` : "";
|
|
3566
|
+
if (licensed) {
|
|
3567
|
+
const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
|
|
3568
|
+
steps.push(step(
|
|
3569
|
+
n++,
|
|
3570
|
+
"Apply the fixes with optimize",
|
|
3571
|
+
`<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize inside each project you work in. It scans the project, writes a filled-in CLAUDE.md, a ranked playbook, suggested settings, a work order, and a dashboard into <span class="mono">./costclaw-out</span>, then opens the dashboard.</p>` + cmd("cd <your-project>\nnpx costclaw optimize") + `<p>Happy with the dry run? Apply it in place (both back up the original and print a diff), then hand the work order to your own Claude Code:</p>` + cmd('npx costclaw optimize --write CLAUDE.md --apply-settings\nclaude "Follow costclaw-out/HARNESS-UPGRADE.md"') + `<p class="fine">Moving machines? <span class="mono">costclaw deactivate</span> here, <span class="mono">costclaw activate <key></span> there.</p>`
|
|
3572
|
+
));
|
|
3573
|
+
} else {
|
|
3574
|
+
steps.push(step(
|
|
3575
|
+
n++,
|
|
3576
|
+
"Apply the fixes with optimize",
|
|
3577
|
+
`<p>${wasteLine}<strong>costclaw optimize</strong> turns this audit into the files that recover it: a filled-in CLAUDE.md, a ranked fix playbook, a suggested <span class="mono">settings.json</span> allowlist, a work order your own Claude Code applies, and a dashboard showing your CLAUDE.md before and after.</p><div class="offer"><div class="offer-price"><span class="big">${esc(LICENSE_PRICE)}</span> one-time</div><ul class="offer-list"><li>Key emailed in about a minute</li><li>Verified offline on your machine, no license server</li><li>Every project, unlimited runs</li><li>Move it between machines with activate and deactivate</li></ul><a class="buy" href="${CHECKOUT_URL}">Buy the optimize license</a><p class="fine">Then, once the key arrives:</p>` + cmd("npx costclaw activate <key>\ncd <your-project>\nnpx costclaw optimize") + `<p class="fine">Questions or a key that will not activate: <a href="mailto:${SUPPORT_EMAIL}">${SUPPORT_EMAIL}</a>. The audit stays free either way.</p></div>`
|
|
3578
|
+
));
|
|
3579
|
+
}
|
|
3580
|
+
steps.push(step(
|
|
3581
|
+
n++,
|
|
3582
|
+
"Track the movement",
|
|
3583
|
+
`<p>Every audit snapshots the derived record locally. Rerun in a week and compare: new spend, the cache hit rate for just that period, pillar movement, and which fixes resolved.</p>` + cmd("npx costclaw audit\nnpx costclaw diff")
|
|
3584
|
+
));
|
|
3585
|
+
steps.push(step(
|
|
3586
|
+
n++,
|
|
3587
|
+
"Share the score",
|
|
3588
|
+
`<p>A 600x315 score card for a post, and a shields-style badge for a README. Both are static SVGs with only derived numbers.</p>` + cmd("npx costclaw audit --card\nnpx costclaw badge")
|
|
3589
|
+
));
|
|
3590
|
+
const reference = `<table class="ref"><tbody><tr><td class="mono">costclaw audit</td><td>Cost report, setup score, ranked fixes, this HTML report. Free.</td></tr><tr><td class="mono">costclaw audit --plan <p></td><td>Declare api, pro, max5x, or max20x; remembered for later runs.</td></tr><tr><td class="mono">costclaw diff</td><td>Compare the latest two audits, or two --json records. Free.</td></tr><tr><td class="mono">costclaw badge</td><td>Fresh audit plus a README badge SVG. Free.</td></tr><tr><td class="mono">costclaw optimize</td><td>Write the optimized CLAUDE.md, playbook, settings, work order, and dashboard. Licensed.</td></tr><tr><td class="mono">costclaw activate / deactivate</td><td>Install or move the license on this machine. Offline.</td></tr><tr><td class="mono">costclaw --help</td><td>Every flag, per command.</td></tr></tbody></table>`;
|
|
3591
|
+
return `<h2>What to do next</h2>
|
|
3592
|
+
<ol class="steps">${steps.join("")}</ol>
|
|
3593
|
+
<h3 class="ref-head">Command reference</h3>
|
|
3594
|
+
${reference}
|
|
3595
|
+
<p class="sub">Docs and pricing: <a href="${SITE_URL}">${SITE_URL.replace("https://", "")}</a>. A hosted dashboard with history and team views is in progress; the waitlist is on the <a href="${PRICING_URL}">pricing section</a>. It will only ever receive the derived record, never your logs.</p>`;
|
|
3596
|
+
}
|
|
3342
3597
|
var STYLE = `
|
|
3343
3598
|
:root {
|
|
3344
3599
|
color-scheme: light;
|
|
@@ -3447,8 +3702,49 @@ ul.fixes { list-style: none; margin: 0; padding: 0; }
|
|
|
3447
3702
|
.footer .gen { margin: var(--s2) 0 0; }
|
|
3448
3703
|
/* The timestamp is one token; never let it break across lines. */
|
|
3449
3704
|
.footer .gen .mono { white-space: nowrap; }
|
|
3705
|
+
/* Next-steps ramp */
|
|
3706
|
+
ol.steps { list-style: none; margin: 0; padding: 0; counter-reset: none; }
|
|
3707
|
+
.step {
|
|
3708
|
+
display: flex; gap: var(--s4); background: var(--card); border: 1px solid var(--line);
|
|
3709
|
+
border-radius: 10px; padding: var(--s4) var(--s5); margin: 0 0 var(--s3);
|
|
3710
|
+
}
|
|
3711
|
+
.step-n {
|
|
3712
|
+
flex: 0 0 28px; height: 28px; border-radius: 14px; background: var(--umber); color: var(--paper);
|
|
3713
|
+
font-family: var(--mono); font-weight: 700; font-size: 14px; display: flex; align-items: center; justify-content: center;
|
|
3714
|
+
}
|
|
3715
|
+
.step-body { flex: 1; min-width: 0; }
|
|
3716
|
+
.step-body h3 { font-size: 15px; margin: 3px 0 var(--s2); }
|
|
3717
|
+
.step-body p { margin: var(--s2) 0 0; font-size: 14px; max-width: 74ch; }
|
|
3718
|
+
.step-body .ok { color: #1f6b3a; font-weight: 600; }
|
|
3719
|
+
.step-body .fine { font-size: 13px; color: var(--muted); }
|
|
3720
|
+
.cmd {
|
|
3721
|
+
margin: var(--s3) 0 0; padding: var(--s3) var(--s4); background: #2a211d; color: #f4ebe5;
|
|
3722
|
+
border-radius: 8px; font-family: var(--mono); font-size: 13px; line-height: 1.6;
|
|
3723
|
+
overflow-x: auto; white-space: pre;
|
|
3724
|
+
}
|
|
3725
|
+
.cmd code { font-family: inherit; }
|
|
3726
|
+
.offer {
|
|
3727
|
+
margin: var(--s4) 0 0; padding: var(--s4) var(--s5); border: 1px solid var(--line);
|
|
3728
|
+
border-left: 4px solid var(--clay); border-radius: 10px; background: var(--paper);
|
|
3729
|
+
}
|
|
3730
|
+
.offer-price { font-size: 14px; color: var(--muted); }
|
|
3731
|
+
.offer-price .big { font-size: 28px; font-weight: 700; color: var(--umber); font-family: var(--mono); margin-right: var(--s2); }
|
|
3732
|
+
.offer-list { margin: var(--s3) 0 0; padding-left: 18px; font-size: 14px; }
|
|
3733
|
+
.offer-list li { margin: 2px 0; }
|
|
3734
|
+
.buy {
|
|
3735
|
+
display: inline-block; margin: var(--s4) 0 0; padding: 10px 18px; border-radius: 8px;
|
|
3736
|
+
background: linear-gradient(135deg, var(--umber), var(--clay)); color: var(--paper);
|
|
3737
|
+
font-weight: 700; text-decoration: none; font-size: 14px;
|
|
3738
|
+
}
|
|
3739
|
+
.buy:hover { filter: brightness(1.05); }
|
|
3740
|
+
a { color: var(--umber); }
|
|
3741
|
+
.ref-head { font-size: 14px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; margin: var(--s6) 0 var(--s3); }
|
|
3742
|
+
table.ref { width: 100%; border-collapse: collapse; font-size: 14px; }
|
|
3743
|
+
table.ref td { padding: var(--s2) var(--s3); border-top: 1px solid var(--line); vertical-align: top; }
|
|
3744
|
+
table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size: 13px; }
|
|
3450
3745
|
@media (max-width: 560px) {
|
|
3451
3746
|
.wrap { padding: var(--s6) var(--s4) var(--s8); }
|
|
3747
|
+
table.ref td:first-child { white-space: normal; }
|
|
3452
3748
|
h1 { font-size: 24px; }
|
|
3453
3749
|
.banner .amount { font-size: 32px; }
|
|
3454
3750
|
.p-name { flex: 0 0 130px; font-size: 13px; }
|
|
@@ -3536,6 +3832,8 @@ ${dollarSection}
|
|
|
3536
3832
|
${otherSection}
|
|
3537
3833
|
${skippedNote}
|
|
3538
3834
|
|
|
3835
|
+
${nextStepsSection(record, meta)}
|
|
3836
|
+
|
|
3539
3837
|
<div class="footer">
|
|
3540
3838
|
<strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
|
|
3541
3839
|
your prompts, file contents, and paths never left this computer.
|
|
@@ -3670,6 +3968,125 @@ async function saveCliConfig(dir, patch) {
|
|
|
3670
3968
|
await writeFile(configFile(dir), JSON.stringify(merged, null, 2), "utf8");
|
|
3671
3969
|
}
|
|
3672
3970
|
|
|
3971
|
+
// src/license.ts
|
|
3972
|
+
import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2, rm } from "fs/promises";
|
|
3973
|
+
import { join as join4 } from "path";
|
|
3974
|
+
import { homedir as homedir3, hostname } from "os";
|
|
3975
|
+
|
|
3976
|
+
// ../../packages/license/src/keys.ts
|
|
3977
|
+
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
3978
|
+
var KEY_PREFIX = "CC1";
|
|
3979
|
+
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
3980
|
+
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
3981
|
+
-----END PUBLIC KEY-----`;
|
|
3982
|
+
|
|
3983
|
+
// ../../packages/license/src/verify.ts
|
|
3984
|
+
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
3985
|
+
function base64UrlDecode(part) {
|
|
3986
|
+
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
3987
|
+
}
|
|
3988
|
+
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
3989
|
+
const parts = licenseKey.trim().split(".");
|
|
3990
|
+
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
3991
|
+
const [prefix, payloadPart, signaturePart] = parts;
|
|
3992
|
+
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
3993
|
+
try {
|
|
3994
|
+
const publicKey = createPublicKey(publicKeyPem);
|
|
3995
|
+
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
3996
|
+
const signature = base64UrlDecode(signaturePart);
|
|
3997
|
+
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
3998
|
+
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
3999
|
+
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
4000
|
+
return payload;
|
|
4001
|
+
} catch {
|
|
4002
|
+
return null;
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
|
|
4006
|
+
// ../../packages/license/src/mint.ts
|
|
4007
|
+
import { createPrivateKey, sign } from "crypto";
|
|
4008
|
+
|
|
4009
|
+
// ../../packages/license/src/stripe.ts
|
|
4010
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4011
|
+
|
|
4012
|
+
// src/license.ts
|
|
4013
|
+
var NOT_ACTIVATED_MESSAGE = [
|
|
4014
|
+
"costclaw optimize needs a license.",
|
|
4015
|
+
"",
|
|
4016
|
+
"Buy a one-time license at https://costclaw.io, then run:",
|
|
4017
|
+
" costclaw activate <your-license-key>",
|
|
4018
|
+
"",
|
|
4019
|
+
"costclaw audit is free and does not need a license."
|
|
4020
|
+
].join("\n");
|
|
4021
|
+
var INVALID_MESSAGE = [
|
|
4022
|
+
"The saved CostClaw license is not valid for this version.",
|
|
4023
|
+
"",
|
|
4024
|
+
"Re-activate with the key from your purchase email:",
|
|
4025
|
+
" costclaw activate <your-license-key>",
|
|
4026
|
+
"",
|
|
4027
|
+
"Key missing or not working? Email wes@dashclaw.io with your order number.",
|
|
4028
|
+
"costclaw audit stays free."
|
|
4029
|
+
].join("\n");
|
|
4030
|
+
function defaultConfigDir() {
|
|
4031
|
+
return join4(homedir3(), ".costclaw");
|
|
4032
|
+
}
|
|
4033
|
+
function licenseFile(dir) {
|
|
4034
|
+
return join4(dir, "license.json");
|
|
4035
|
+
}
|
|
4036
|
+
async function readStoredLicense(dir) {
|
|
4037
|
+
try {
|
|
4038
|
+
const data = JSON.parse(await readFile3(licenseFile(dir), "utf8"));
|
|
4039
|
+
if (!data || typeof data.licenseKey !== "string") return null;
|
|
4040
|
+
return data;
|
|
4041
|
+
} catch {
|
|
4042
|
+
return null;
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
4045
|
+
async function writeStoredLicense(dir, lic) {
|
|
4046
|
+
await mkdir2(dir, { recursive: true });
|
|
4047
|
+
await writeFile2(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
4048
|
+
}
|
|
4049
|
+
async function clearStoredLicense(dir) {
|
|
4050
|
+
await rm(licenseFile(dir), { force: true });
|
|
4051
|
+
}
|
|
4052
|
+
async function activateLicense(licenseKey, opts = {}) {
|
|
4053
|
+
const key = licenseKey.trim();
|
|
4054
|
+
if (!key) throw new Error("Provide your license key: costclaw activate <key>");
|
|
4055
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
4056
|
+
const payload = verifyLicenseKey(key, opts.publicKeyPem);
|
|
4057
|
+
if (!payload) {
|
|
4058
|
+
throw new Error(
|
|
4059
|
+
"Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
|
|
4060
|
+
);
|
|
4061
|
+
}
|
|
4062
|
+
const stored = {
|
|
4063
|
+
licenseKey: key,
|
|
4064
|
+
instanceId: "local",
|
|
4065
|
+
instanceName: opts.instanceName?.trim() || hostname(),
|
|
4066
|
+
email: payload.e,
|
|
4067
|
+
activatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4068
|
+
};
|
|
4069
|
+
await writeStoredLicense(configDir, stored);
|
|
4070
|
+
return stored;
|
|
4071
|
+
}
|
|
4072
|
+
async function checkLicense(opts = {}) {
|
|
4073
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
4074
|
+
const stored = await readStoredLicense(configDir);
|
|
4075
|
+
if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
|
|
4076
|
+
const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
|
|
4077
|
+
if (payload) {
|
|
4078
|
+
return { ok: true, email: payload.e ?? stored.email };
|
|
4079
|
+
}
|
|
4080
|
+
await clearStoredLicense(configDir);
|
|
4081
|
+
return { ok: false, message: INVALID_MESSAGE };
|
|
4082
|
+
}
|
|
4083
|
+
async function deactivateLicense(opts = {}) {
|
|
4084
|
+
const configDir = opts.configDir ?? defaultConfigDir();
|
|
4085
|
+
const stored = await readStoredLicense(configDir);
|
|
4086
|
+
if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
|
|
4087
|
+
await clearStoredLicense(configDir);
|
|
4088
|
+
}
|
|
4089
|
+
|
|
3673
4090
|
// src/audit-command.ts
|
|
3674
4091
|
async function resolvePlan(configDir, flag) {
|
|
3675
4092
|
if (flag) {
|
|
@@ -3696,12 +4113,12 @@ async function loadAuditInputs(opts) {
|
|
|
3696
4113
|
let claudeMd;
|
|
3697
4114
|
let claudeMdSource = null;
|
|
3698
4115
|
if (opts.claudeMdPath) {
|
|
3699
|
-
claudeMd = await
|
|
4116
|
+
claudeMd = await readFile4(opts.claudeMdPath, "utf8");
|
|
3700
4117
|
claudeMdSource = resolve(opts.claudeMdPath);
|
|
3701
4118
|
} else {
|
|
3702
|
-
const fallback =
|
|
4119
|
+
const fallback = join5(opts.home ?? homedir4(), ".claude", "CLAUDE.md");
|
|
3703
4120
|
try {
|
|
3704
|
-
claudeMd = await
|
|
4121
|
+
claudeMd = await readFile4(fallback, "utf8");
|
|
3705
4122
|
claudeMdSource = fallback;
|
|
3706
4123
|
} catch {
|
|
3707
4124
|
}
|
|
@@ -3715,7 +4132,7 @@ async function runAudit(opts) {
|
|
|
3715
4132
|
home: opts.home
|
|
3716
4133
|
});
|
|
3717
4134
|
const setup = await readSetup();
|
|
3718
|
-
const configDir =
|
|
4135
|
+
const configDir = join5(opts.home ?? homedir4(), ".costclaw");
|
|
3719
4136
|
const { plan, planSource } = await resolvePlan(configDir, opts.plan);
|
|
3720
4137
|
const record = buildAudit({
|
|
3721
4138
|
logs,
|
|
@@ -3727,15 +4144,17 @@ async function runAudit(opts) {
|
|
|
3727
4144
|
});
|
|
3728
4145
|
const baseline = (await readCliConfig(configDir)).lastOptimize;
|
|
3729
4146
|
const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
|
|
4147
|
+
const gate = await checkLicense({ configDir });
|
|
4148
|
+
const license = gate.ok ? { active: true, ...gate.email ? { email: gate.email } : {} } : { active: false };
|
|
3730
4149
|
let snapshotNotice = null;
|
|
3731
4150
|
try {
|
|
3732
|
-
const historyDir =
|
|
3733
|
-
await
|
|
4151
|
+
const historyDir = join5(opts.home ?? homedir4(), ".costclaw", "history");
|
|
4152
|
+
await mkdir3(historyDir, { recursive: true });
|
|
3734
4153
|
const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
|
|
3735
|
-
await
|
|
4154
|
+
await writeFile3(join5(historyDir, name), JSON.stringify(record, null, 2), "utf8");
|
|
3736
4155
|
const snapshots = (await readdir2(historyDir)).filter((f) => f.endsWith(".json")).sort();
|
|
3737
4156
|
for (const stale of snapshots.slice(0, Math.max(0, snapshots.length - SNAPSHOT_KEEP))) {
|
|
3738
|
-
await
|
|
4157
|
+
await rm2(join5(historyDir, stale), { force: true });
|
|
3739
4158
|
}
|
|
3740
4159
|
snapshotNotice = "Snapshot saved for costclaw diff.";
|
|
3741
4160
|
} catch (err) {
|
|
@@ -3748,15 +4167,15 @@ async function runAudit(opts) {
|
|
|
3748
4167
|
if (snapshotNotice) notices.push(snapshotNotice);
|
|
3749
4168
|
if (opts.html) {
|
|
3750
4169
|
const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
|
|
3751
|
-
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize });
|
|
3752
|
-
await
|
|
4170
|
+
const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license });
|
|
4171
|
+
await writeFile3(target, doc, "utf8");
|
|
3753
4172
|
openInBrowser(target);
|
|
3754
4173
|
notices.push(`HTML report written to ${target}`);
|
|
3755
4174
|
}
|
|
3756
4175
|
if (opts.card) {
|
|
3757
4176
|
const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
|
|
3758
4177
|
const svg = renderCard(record);
|
|
3759
|
-
await
|
|
4178
|
+
await writeFile3(target, svg, "utf8");
|
|
3760
4179
|
notices.push(`Score card written to ${target}`);
|
|
3761
4180
|
}
|
|
3762
4181
|
if (opts.json) {
|
|
@@ -3768,9 +4187,9 @@ async function runAudit(opts) {
|
|
|
3768
4187
|
}
|
|
3769
4188
|
|
|
3770
4189
|
// src/optimize-command.ts
|
|
3771
|
-
import { mkdir as
|
|
3772
|
-
import { join as
|
|
3773
|
-
import { homedir as
|
|
4190
|
+
import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, stat as stat2 } from "fs/promises";
|
|
4191
|
+
import { join as join7, dirname } from "path";
|
|
4192
|
+
import { homedir as homedir5 } from "os";
|
|
3774
4193
|
|
|
3775
4194
|
// src/optimize-dashboard.ts
|
|
3776
4195
|
function usd5(n) {
|
|
@@ -4184,8 +4603,8 @@ No network calls, no telemetry, no model calls.</footer>
|
|
|
4184
4603
|
}
|
|
4185
4604
|
|
|
4186
4605
|
// src/project-scan.ts
|
|
4187
|
-
import { readdir as readdir3, readFile as
|
|
4188
|
-
import { join as
|
|
4606
|
+
import { readdir as readdir3, readFile as readFile5, stat } from "fs/promises";
|
|
4607
|
+
import { join as join6, basename } from "path";
|
|
4189
4608
|
var NOISE_DIRS = /* @__PURE__ */ new Set([
|
|
4190
4609
|
"node_modules",
|
|
4191
4610
|
".git",
|
|
@@ -4214,7 +4633,7 @@ var DIR_NOTES = {
|
|
|
4214
4633
|
};
|
|
4215
4634
|
async function readText(p) {
|
|
4216
4635
|
try {
|
|
4217
|
-
return await
|
|
4636
|
+
return await readFile5(p, "utf8");
|
|
4218
4637
|
} catch {
|
|
4219
4638
|
return null;
|
|
4220
4639
|
}
|
|
@@ -4324,7 +4743,7 @@ async function containsTestFiles(dir) {
|
|
|
4324
4743
|
const top = await listEntries(dir);
|
|
4325
4744
|
if (top.files.some((f) => TEST_FILE.test(f))) return true;
|
|
4326
4745
|
for (const sub of top.dirs) {
|
|
4327
|
-
const inner = await listEntries(
|
|
4746
|
+
const inner = await listEntries(join6(dir, sub));
|
|
4328
4747
|
if (inner.files.some((f) => TEST_FILE.test(f))) return true;
|
|
4329
4748
|
}
|
|
4330
4749
|
return false;
|
|
@@ -4334,14 +4753,14 @@ async function detectTestsLocation(dir, files, dirs) {
|
|
|
4334
4753
|
if (candidates.length > 0) {
|
|
4335
4754
|
const withTests = [];
|
|
4336
4755
|
for (const c of candidates) {
|
|
4337
|
-
if (await containsTestFiles(
|
|
4756
|
+
if (await containsTestFiles(join6(dir, c))) withTests.push(c);
|
|
4338
4757
|
}
|
|
4339
4758
|
const chosen = withTests.length > 0 ? withTests : candidates;
|
|
4340
4759
|
return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
|
|
4341
4760
|
}
|
|
4342
4761
|
if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
|
|
4343
4762
|
if (dirs.includes("src")) {
|
|
4344
|
-
const sub = await listEntries(
|
|
4763
|
+
const sub = await listEntries(join6(dir, "src"));
|
|
4345
4764
|
if (sub.files.some((f) => TEST_FILE.test(f))) {
|
|
4346
4765
|
return "tests alongside source (*.test.* / *.spec.*)";
|
|
4347
4766
|
}
|
|
@@ -4424,7 +4843,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
|
|
|
4424
4843
|
if (oneFileCmd !== null && "test" in scripts) {
|
|
4425
4844
|
profile.commands.push({ label: "test one file", command: oneFileCmd });
|
|
4426
4845
|
}
|
|
4427
|
-
const tsconfig = parseJson(await readText(
|
|
4846
|
+
const tsconfig = parseJson(await readText(join6(dir, "tsconfig.json")));
|
|
4428
4847
|
if (tsconfig) {
|
|
4429
4848
|
const co = tsconfig.compilerOptions;
|
|
4430
4849
|
if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
|
|
@@ -4527,7 +4946,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4527
4946
|
const deps = [];
|
|
4528
4947
|
const tables = /* @__PURE__ */ new Set();
|
|
4529
4948
|
let hasPoetry = false;
|
|
4530
|
-
const pyprojectText = await readText(
|
|
4949
|
+
const pyprojectText = await readText(join6(dir, "pyproject.toml"));
|
|
4531
4950
|
if (pyprojectText !== null) {
|
|
4532
4951
|
const parsed = parsePyproject(pyprojectText);
|
|
4533
4952
|
name = parsed.name;
|
|
@@ -4537,7 +4956,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4537
4956
|
hasPoetry = parsed.hasPoetry;
|
|
4538
4957
|
}
|
|
4539
4958
|
if (files.includes("requirements.txt")) {
|
|
4540
|
-
const reqText = await readText(
|
|
4959
|
+
const reqText = await readText(join6(dir, "requirements.txt"));
|
|
4541
4960
|
if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
|
|
4542
4961
|
}
|
|
4543
4962
|
if (name !== null && name.trim() !== "") profile.name = name;
|
|
@@ -4571,7 +4990,7 @@ async function scanPython(dir, files, profile) {
|
|
|
4571
4990
|
}
|
|
4572
4991
|
}
|
|
4573
4992
|
async function scanRust(dir, profile) {
|
|
4574
|
-
const text2 = await readText(
|
|
4993
|
+
const text2 = await readText(join6(dir, "Cargo.toml"));
|
|
4575
4994
|
pushUnique(profile.stack, "Rust");
|
|
4576
4995
|
profile.packageManager = "cargo";
|
|
4577
4996
|
if (text2 !== null) {
|
|
@@ -4597,7 +5016,7 @@ async function scanRust(dir, profile) {
|
|
|
4597
5016
|
profile.commands.push({ label: "lint", command: "cargo clippy" });
|
|
4598
5017
|
}
|
|
4599
5018
|
async function scanGo(dir, profile) {
|
|
4600
|
-
const text2 = await readText(
|
|
5019
|
+
const text2 = await readText(join6(dir, "go.mod"));
|
|
4601
5020
|
pushUnique(profile.stack, "Go");
|
|
4602
5021
|
profile.packageManager = "go";
|
|
4603
5022
|
if (text2 !== null) {
|
|
@@ -4662,7 +5081,7 @@ async function scanProject(dir) {
|
|
|
4662
5081
|
const profile = emptyProfile(basename(dir));
|
|
4663
5082
|
const { files, dirs } = await listEntries(dir);
|
|
4664
5083
|
if (files.includes("package.json")) {
|
|
4665
|
-
const pkg = parseJson(await readText(
|
|
5084
|
+
const pkg = parseJson(await readText(join6(dir, "package.json")));
|
|
4666
5085
|
if (pkg) await scanNode(dir, files, dirs, pkg, profile);
|
|
4667
5086
|
}
|
|
4668
5087
|
if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
|
|
@@ -4675,7 +5094,7 @@ async function scanProject(dir) {
|
|
|
4675
5094
|
await scanGo(dir, profile);
|
|
4676
5095
|
}
|
|
4677
5096
|
if (files.includes("Makefile") && profile.commands.length === 0) {
|
|
4678
|
-
const text2 = await readText(
|
|
5097
|
+
const text2 = await readText(join6(dir, "Makefile"));
|
|
4679
5098
|
if (text2 !== null) {
|
|
4680
5099
|
for (const t of parseMakefile(text2)) {
|
|
4681
5100
|
profile.commands.push({ label: t, command: `make ${t}` });
|
|
@@ -4685,7 +5104,7 @@ async function scanProject(dir) {
|
|
|
4685
5104
|
if (profile.description === null || profile.name === basename(dir)) {
|
|
4686
5105
|
const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
|
|
4687
5106
|
if (readmeName) {
|
|
4688
|
-
const text2 = await readText(
|
|
5107
|
+
const text2 = await readText(join6(dir, readmeName));
|
|
4689
5108
|
if (text2 !== null) {
|
|
4690
5109
|
const parsed = parseReadme(text2);
|
|
4691
5110
|
if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
|
|
@@ -4698,7 +5117,7 @@ async function scanProject(dir) {
|
|
|
4698
5117
|
profile.structure = await detectStructure(dir, dirs);
|
|
4699
5118
|
const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
|
|
4700
5119
|
if (envFile) {
|
|
4701
|
-
const text2 = await readText(
|
|
5120
|
+
const text2 = await readText(join6(dir, envFile));
|
|
4702
5121
|
if (text2 !== null) profile.envVars = parseEnvNames(text2);
|
|
4703
5122
|
}
|
|
4704
5123
|
return profile;
|
|
@@ -4786,7 +5205,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
4786
5205
|
let existingText = "";
|
|
4787
5206
|
let existing = {};
|
|
4788
5207
|
if (await pathExists(target)) {
|
|
4789
|
-
existingText = await
|
|
5208
|
+
existingText = await readFile6(target, "utf8");
|
|
4790
5209
|
if (existingText.trim() !== "") {
|
|
4791
5210
|
let parsed;
|
|
4792
5211
|
try {
|
|
@@ -4813,9 +5232,9 @@ async function applyDerivedSettings(target, suggestedJson, force) {
|
|
|
4813
5232
|
mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
|
|
4814
5233
|
const merged = { ...existing, permissions: mergedPerms };
|
|
4815
5234
|
const mergedText = JSON.stringify(merged, null, 2) + "\n";
|
|
4816
|
-
await
|
|
4817
|
-
await
|
|
4818
|
-
await
|
|
5235
|
+
await mkdir4(dirname(target), { recursive: true });
|
|
5236
|
+
await writeFile4(backup, existingText, "utf8");
|
|
5237
|
+
await writeFile4(target, mergedText, "utf8");
|
|
4819
5238
|
return [
|
|
4820
5239
|
`Merged the derived permission allowlist into ${target}`,
|
|
4821
5240
|
`Backed up the previous file to ${backup}`,
|
|
@@ -4829,16 +5248,16 @@ async function runOptimize(opts) {
|
|
|
4829
5248
|
const projectDir = opts.projectDir || process.cwd();
|
|
4830
5249
|
let claudeMdPath = opts.claudeMdPath;
|
|
4831
5250
|
if (!claudeMdPath) {
|
|
4832
|
-
const projectClaudeMd =
|
|
5251
|
+
const projectClaudeMd = join7(projectDir, "CLAUDE.md");
|
|
4833
5252
|
if (await pathExists(projectClaudeMd)) claudeMdPath = projectClaudeMd;
|
|
4834
5253
|
}
|
|
4835
5254
|
const { logs, claudeMd, claudeMdSource } = await loadAuditInputs({ path: opts.path, claudeMdPath });
|
|
4836
5255
|
const report = analyzeUploads(logs);
|
|
4837
|
-
const
|
|
4838
|
-
const { pillars } = scorePillars(report,
|
|
4839
|
-
const configDir =
|
|
5256
|
+
const cmd2 = analyzeClaudeMd(claudeMd);
|
|
5257
|
+
const { pillars } = scorePillars(report, cmd2, {});
|
|
5258
|
+
const configDir = join7(opts.home ?? homedir5(), ".costclaw");
|
|
4840
5259
|
const { plan } = await resolvePlan(configDir, opts.plan);
|
|
4841
|
-
const { fixes } = synthesize(report, pillars,
|
|
5260
|
+
const { fixes } = synthesize(report, pillars, cmd2, plan);
|
|
4842
5261
|
const project = await scanProject(projectDir);
|
|
4843
5262
|
const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
|
|
4844
5263
|
const recoverable = cacheMissExposureUsd(report);
|
|
@@ -4852,14 +5271,14 @@ async function runOptimize(opts) {
|
|
|
4852
5271
|
spendUsd: baselineSpend
|
|
4853
5272
|
}
|
|
4854
5273
|
});
|
|
4855
|
-
const outDir = opts.out ||
|
|
4856
|
-
await
|
|
4857
|
-
const playbookPath =
|
|
4858
|
-
await
|
|
4859
|
-
const settingsPath =
|
|
4860
|
-
await
|
|
4861
|
-
const harnessPath =
|
|
4862
|
-
await
|
|
5274
|
+
const outDir = opts.out || join7(process.cwd(), "costclaw-out");
|
|
5275
|
+
await mkdir4(outDir, { recursive: true });
|
|
5276
|
+
const playbookPath = join7(outDir, PLAYBOOK_NAME2);
|
|
5277
|
+
await writeFile4(playbookPath, result.playbook, "utf8");
|
|
5278
|
+
const settingsPath = join7(outDir, SETTINGS_NAME2);
|
|
5279
|
+
await writeFile4(settingsPath, result.settingsJson, "utf8");
|
|
5280
|
+
const harnessPath = join7(outDir, HARNESS_NAME2);
|
|
5281
|
+
await writeFile4(harnessPath, result.harnessPrompt, "utf8");
|
|
4863
5282
|
const wantDashboard = opts.dashboard !== false;
|
|
4864
5283
|
let dashboardPath = null;
|
|
4865
5284
|
if (wantDashboard) {
|
|
@@ -4881,8 +5300,8 @@ async function runOptimize(opts) {
|
|
|
4881
5300
|
headlineWasteShare: spend > 0 ? recoverable / spend : 0,
|
|
4882
5301
|
headlineWasteUsd: recoverable
|
|
4883
5302
|
});
|
|
4884
|
-
dashboardPath =
|
|
4885
|
-
await
|
|
5303
|
+
dashboardPath = join7(outDir, DASHBOARD_NAME);
|
|
5304
|
+
await writeFile4(dashboardPath, html, "utf8");
|
|
4886
5305
|
}
|
|
4887
5306
|
const lines = [];
|
|
4888
5307
|
lines.push("CostClaw optimize");
|
|
@@ -4901,10 +5320,10 @@ async function runOptimize(opts) {
|
|
|
4901
5320
|
}
|
|
4902
5321
|
let original = "";
|
|
4903
5322
|
if (await pathExists(target)) {
|
|
4904
|
-
original = await
|
|
5323
|
+
original = await readFile6(target, "utf8");
|
|
4905
5324
|
}
|
|
4906
|
-
await
|
|
4907
|
-
await
|
|
5325
|
+
await writeFile4(backup, original, "utf8");
|
|
5326
|
+
await writeFile4(target, result.optimizedClaudeMd, "utf8");
|
|
4908
5327
|
lines.push(`Backed up the original to ${backup}`);
|
|
4909
5328
|
lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
|
|
4910
5329
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -4919,8 +5338,8 @@ async function runOptimize(opts) {
|
|
|
4919
5338
|
}
|
|
4920
5339
|
lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
|
|
4921
5340
|
} else {
|
|
4922
|
-
const optimizedPath =
|
|
4923
|
-
await
|
|
5341
|
+
const optimizedPath = join7(outDir, OPTIMIZED_NAME2);
|
|
5342
|
+
await writeFile4(optimizedPath, result.optimizedClaudeMd, "utf8");
|
|
4924
5343
|
lines.push("Dry run (no files of yours were changed).");
|
|
4925
5344
|
lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
|
|
4926
5345
|
lines.push(`Wrote the playbook to ${playbookPath}`);
|
|
@@ -4972,7 +5391,7 @@ async function runOptimize(opts) {
|
|
|
4972
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.");
|
|
4973
5392
|
}
|
|
4974
5393
|
if (opts.applySettings) {
|
|
4975
|
-
const target = opts.applySettingsPath ||
|
|
5394
|
+
const target = opts.applySettingsPath || join7(projectDir, ".claude", "settings.json");
|
|
4976
5395
|
const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
|
|
4977
5396
|
lines.push("");
|
|
4978
5397
|
lines.push(...applyLines);
|
|
@@ -4995,7 +5414,7 @@ async function runOptimize(opts) {
|
|
|
4995
5414
|
}
|
|
4996
5415
|
|
|
4997
5416
|
// src/badge-command.ts
|
|
4998
|
-
import { writeFile as
|
|
5417
|
+
import { writeFile as writeFile5 } from "fs/promises";
|
|
4999
5418
|
import { resolve as resolve2 } from "path";
|
|
5000
5419
|
|
|
5001
5420
|
// src/badge.ts
|
|
@@ -5021,14 +5440,14 @@ async function runBadge(opts) {
|
|
|
5021
5440
|
const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
|
|
5022
5441
|
const svg = renderBadge(record);
|
|
5023
5442
|
const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
|
|
5024
|
-
await
|
|
5443
|
+
await writeFile5(target, svg, "utf8");
|
|
5025
5444
|
return { output: `Badge written to ${target}`, record, target };
|
|
5026
5445
|
}
|
|
5027
5446
|
|
|
5028
5447
|
// src/diff-command.ts
|
|
5029
|
-
import { readdir as readdir4, readFile as
|
|
5030
|
-
import { join as
|
|
5031
|
-
import { homedir as
|
|
5448
|
+
import { readdir as readdir4, readFile as readFile7 } from "fs/promises";
|
|
5449
|
+
import { join as join8 } from "path";
|
|
5450
|
+
import { homedir as homedir6 } from "os";
|
|
5032
5451
|
|
|
5033
5452
|
// src/format-diff.ts
|
|
5034
5453
|
function usd7(n) {
|
|
@@ -5116,7 +5535,7 @@ function formatDiff(d) {
|
|
|
5116
5535
|
async function readRecord(path) {
|
|
5117
5536
|
let text2;
|
|
5118
5537
|
try {
|
|
5119
|
-
text2 = await
|
|
5538
|
+
text2 = await readFile7(path, "utf8");
|
|
5120
5539
|
} catch {
|
|
5121
5540
|
throw new Error(`Could not read ${path}.`);
|
|
5122
5541
|
}
|
|
@@ -5132,7 +5551,7 @@ async function runDiff(opts) {
|
|
|
5132
5551
|
let pathA = opts.fileA;
|
|
5133
5552
|
let pathB = opts.fileB;
|
|
5134
5553
|
if (!pathA || !pathB) {
|
|
5135
|
-
const dir =
|
|
5554
|
+
const dir = join8(opts.home ?? homedir6(), ".costclaw", "history");
|
|
5136
5555
|
let files = [];
|
|
5137
5556
|
try {
|
|
5138
5557
|
files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
|
|
@@ -5143,133 +5562,14 @@ async function runDiff(opts) {
|
|
|
5143
5562
|
"Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
|
|
5144
5563
|
);
|
|
5145
5564
|
}
|
|
5146
|
-
pathA =
|
|
5147
|
-
pathB =
|
|
5565
|
+
pathA = join8(dir, files[files.length - 2]);
|
|
5566
|
+
pathB = join8(dir, files[files.length - 1]);
|
|
5148
5567
|
}
|
|
5149
5568
|
const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
|
|
5150
5569
|
const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
|
|
5151
5570
|
return { output, diff };
|
|
5152
5571
|
}
|
|
5153
5572
|
|
|
5154
|
-
// src/license.ts
|
|
5155
|
-
import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
|
|
5156
|
-
import { join as join8 } from "path";
|
|
5157
|
-
import { homedir as homedir6, hostname } from "os";
|
|
5158
|
-
|
|
5159
|
-
// ../../packages/license/src/keys.ts
|
|
5160
|
-
var LICENSE_PRODUCT = "costclaw-optimize";
|
|
5161
|
-
var KEY_PREFIX = "CC1";
|
|
5162
|
-
var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
5163
|
-
MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
|
|
5164
|
-
-----END PUBLIC KEY-----`;
|
|
5165
|
-
|
|
5166
|
-
// ../../packages/license/src/verify.ts
|
|
5167
|
-
import { createPublicKey, verify as cryptoVerify } from "crypto";
|
|
5168
|
-
function base64UrlDecode(part) {
|
|
5169
|
-
return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
5170
|
-
}
|
|
5171
|
-
function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
|
|
5172
|
-
const parts = licenseKey.trim().split(".");
|
|
5173
|
-
if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
|
|
5174
|
-
const [prefix, payloadPart, signaturePart] = parts;
|
|
5175
|
-
if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
|
|
5176
|
-
try {
|
|
5177
|
-
const publicKey = createPublicKey(publicKeyPem);
|
|
5178
|
-
const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
|
|
5179
|
-
const signature = base64UrlDecode(signaturePart);
|
|
5180
|
-
if (!cryptoVerify(null, signed, publicKey, signature)) return null;
|
|
5181
|
-
const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
|
|
5182
|
-
if (payload.p !== LICENSE_PRODUCT) return null;
|
|
5183
|
-
return payload;
|
|
5184
|
-
} catch {
|
|
5185
|
-
return null;
|
|
5186
|
-
}
|
|
5187
|
-
}
|
|
5188
|
-
|
|
5189
|
-
// ../../packages/license/src/mint.ts
|
|
5190
|
-
import { createPrivateKey, sign } from "crypto";
|
|
5191
|
-
|
|
5192
|
-
// ../../packages/license/src/stripe.ts
|
|
5193
|
-
import { createHmac, timingSafeEqual } from "crypto";
|
|
5194
|
-
|
|
5195
|
-
// src/license.ts
|
|
5196
|
-
var NOT_ACTIVATED_MESSAGE = [
|
|
5197
|
-
"costclaw optimize needs a license.",
|
|
5198
|
-
"",
|
|
5199
|
-
"Buy a one-time license at https://costclaw.io, then run:",
|
|
5200
|
-
" costclaw activate <your-license-key>",
|
|
5201
|
-
"",
|
|
5202
|
-
"costclaw audit is free and does not need a license."
|
|
5203
|
-
].join("\n");
|
|
5204
|
-
var INVALID_MESSAGE = [
|
|
5205
|
-
"The saved CostClaw license is not valid for this version.",
|
|
5206
|
-
"",
|
|
5207
|
-
"Re-activate with the key from your purchase email:",
|
|
5208
|
-
" costclaw activate <your-license-key>",
|
|
5209
|
-
"",
|
|
5210
|
-
"Key missing or not working? Email wes@dashclaw.io with your order number.",
|
|
5211
|
-
"costclaw audit stays free."
|
|
5212
|
-
].join("\n");
|
|
5213
|
-
function defaultConfigDir() {
|
|
5214
|
-
return join8(homedir6(), ".costclaw");
|
|
5215
|
-
}
|
|
5216
|
-
function licenseFile(dir) {
|
|
5217
|
-
return join8(dir, "license.json");
|
|
5218
|
-
}
|
|
5219
|
-
async function readStoredLicense(dir) {
|
|
5220
|
-
try {
|
|
5221
|
-
const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
|
|
5222
|
-
if (!data || typeof data.licenseKey !== "string") return null;
|
|
5223
|
-
return data;
|
|
5224
|
-
} catch {
|
|
5225
|
-
return null;
|
|
5226
|
-
}
|
|
5227
|
-
}
|
|
5228
|
-
async function writeStoredLicense(dir, lic) {
|
|
5229
|
-
await mkdir4(dir, { recursive: true });
|
|
5230
|
-
await writeFile5(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
|
|
5231
|
-
}
|
|
5232
|
-
async function clearStoredLicense(dir) {
|
|
5233
|
-
await rm2(licenseFile(dir), { force: true });
|
|
5234
|
-
}
|
|
5235
|
-
async function activateLicense(licenseKey, opts = {}) {
|
|
5236
|
-
const key = licenseKey.trim();
|
|
5237
|
-
if (!key) throw new Error("Provide your license key: costclaw activate <key>");
|
|
5238
|
-
const configDir = opts.configDir ?? defaultConfigDir();
|
|
5239
|
-
const payload = verifyLicenseKey(key, opts.publicKeyPem);
|
|
5240
|
-
if (!payload) {
|
|
5241
|
-
throw new Error(
|
|
5242
|
-
"Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
|
|
5243
|
-
);
|
|
5244
|
-
}
|
|
5245
|
-
const stored = {
|
|
5246
|
-
licenseKey: key,
|
|
5247
|
-
instanceId: "local",
|
|
5248
|
-
instanceName: opts.instanceName?.trim() || hostname(),
|
|
5249
|
-
email: payload.e,
|
|
5250
|
-
activatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5251
|
-
};
|
|
5252
|
-
await writeStoredLicense(configDir, stored);
|
|
5253
|
-
return stored;
|
|
5254
|
-
}
|
|
5255
|
-
async function checkLicense(opts = {}) {
|
|
5256
|
-
const configDir = opts.configDir ?? defaultConfigDir();
|
|
5257
|
-
const stored = await readStoredLicense(configDir);
|
|
5258
|
-
if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
|
|
5259
|
-
const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
|
|
5260
|
-
if (payload) {
|
|
5261
|
-
return { ok: true, email: payload.e ?? stored.email };
|
|
5262
|
-
}
|
|
5263
|
-
await clearStoredLicense(configDir);
|
|
5264
|
-
return { ok: false, message: INVALID_MESSAGE };
|
|
5265
|
-
}
|
|
5266
|
-
async function deactivateLicense(opts = {}) {
|
|
5267
|
-
const configDir = opts.configDir ?? defaultConfigDir();
|
|
5268
|
-
const stored = await readStoredLicense(configDir);
|
|
5269
|
-
if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
|
|
5270
|
-
await clearStoredLicense(configDir);
|
|
5271
|
-
}
|
|
5272
|
-
|
|
5273
5573
|
// src/index.ts
|
|
5274
5574
|
process.on("unhandledRejection", (reason) => {
|
|
5275
5575
|
console.error("Unhandled rejection:", reason);
|
|
@@ -5317,7 +5617,7 @@ function parseBadgeFlags(args) {
|
|
|
5317
5617
|
};
|
|
5318
5618
|
}
|
|
5319
5619
|
function cliVersion() {
|
|
5320
|
-
return true ? "0.
|
|
5620
|
+
return true ? "0.9.1" : "0.0.0-dev";
|
|
5321
5621
|
}
|
|
5322
5622
|
function isHelpRequest(command, args) {
|
|
5323
5623
|
if (command === void 0) return false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "costclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|