costclaw 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +63 -61
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -390,22 +390,31 @@ function ruleHotProject(ctx) {
390
390
  function ruleHeavyToolLoops(ctx) {
391
391
  const out = [];
392
392
  for (const proj of ctx.projects) {
393
+ const byTool = /* @__PURE__ */ new Map();
393
394
  for (const s of proj.sessions) {
394
395
  if (s.kind !== "main") continue;
395
396
  for (const [tool, fires] of Object.entries(s.toolUsage)) {
396
397
  if (fires < HEAVY_TOOL_FIRES) continue;
397
- out.push({
398
- ruleId: "HEAVY_TOOL_LOOPS",
399
- severity: "warn",
400
- project: proj.slug,
401
- title: `Heavy ${tool} usage in one session`,
402
- description: `${tool} fired ${fires} times in a single session, a sign of a stuck loop or unscoped search.`,
403
- suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
404
- estimatedMonthlySavingsUsd: 0,
405
- evidence: { tool, fires, sessionUuid: s.sessionUuid }
406
- });
398
+ const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
399
+ entry.sessionsAffected += 1;
400
+ entry.maxFires = Math.max(entry.maxFires, fires);
401
+ if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
402
+ byTool.set(tool, entry);
407
403
  }
408
404
  }
405
+ for (const [tool, e] of byTool) {
406
+ const n = e.sessionsAffected;
407
+ out.push({
408
+ ruleId: "HEAVY_TOOL_LOOPS",
409
+ severity: "warn",
410
+ project: proj.slug,
411
+ title: `Heavy ${tool} usage in ${n} session${n === 1 ? "" : "s"}`,
412
+ description: `${tool} fired up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of a stuck loop or unscoped search.`,
413
+ suggestedAction: `Add a guard or narrow the task so ${tool} is not called in a loop.`,
414
+ estimatedMonthlySavingsUsd: 0,
415
+ evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
416
+ });
417
+ }
409
418
  }
410
419
  return out;
411
420
  }
@@ -928,7 +937,10 @@ function buildChecks(report, cmd, answers, setup) {
928
937
  checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
929
938
  const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
930
939
  const thrashSessions = new Set(
931
- heavyLoops.map((f) => f.evidence?.["sessionUuid"]).filter((v) => typeof v === "string")
940
+ heavyLoops.flatMap((f) => {
941
+ const uuids = f.evidence?.["sessionUuids"];
942
+ return Array.isArray(uuids) ? uuids.filter((v) => typeof v === "string") : [];
943
+ })
932
944
  ).size;
933
945
  const thrashShare = s.sessionsCount > 0 ? thrashSessions / s.sessionsCount : 0;
934
946
  const thrashPct = Math.round(thrashShare * 100);
@@ -1198,9 +1210,8 @@ function synthesize(report, pillars, cmd) {
1198
1210
  for (const f of report.findings) {
1199
1211
  if (f.ruleId === "HEAVY_TOOL_LOOPS" && f.evidence) {
1200
1212
  const tool = String(f.evidence["tool"] ?? "a tool");
1201
- const entry = heavyByTool.get(tool) ?? { sessions: /* @__PURE__ */ new Set(), maxFires: 0 };
1202
- const sid = f.evidence["sessionUuid"];
1203
- if (typeof sid === "string") entry.sessions.add(sid);
1213
+ const entry = heavyByTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0 };
1214
+ entry.sessionsAffected += Number(f.evidence["sessionsAffected"]) || 0;
1204
1215
  entry.maxFires = Math.max(entry.maxFires, Number(f.evidence["fires"]) || 0);
1205
1216
  heavyByTool.set(tool, entry);
1206
1217
  covered.add("tool_thrash");
@@ -1224,7 +1235,7 @@ function synthesize(report, pillars, cmd) {
1224
1235
  }
1225
1236
  }
1226
1237
  for (const [tool, e] of heavyByTool) {
1227
- const n = Math.max(e.sessions.size, 1);
1238
+ const n = Math.max(e.sessionsAffected, 1);
1228
1239
  fixes.push({
1229
1240
  id: `heavy_tool_${tool}`,
1230
1241
  title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
@@ -2675,10 +2686,12 @@ async function runOptimize(opts) {
2675
2686
  import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile2, rm } from "fs/promises";
2676
2687
  import { join as join5 } from "path";
2677
2688
  import { homedir as homedir3, hostname } from "os";
2678
- var STORE_ID = 373222;
2679
- var PRODUCT_ID = 1107820;
2680
- var API_BASE = "https://api.lemonsqueezy.com/v1/licenses";
2681
- var defaultFetch = (url, init) => fetch(url, init);
2689
+ import { createPublicKey, verify as cryptoVerify } from "crypto";
2690
+ var LICENSE_PRODUCT = "costclaw-optimize";
2691
+ var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
2692
+ MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
2693
+ -----END PUBLIC KEY-----`;
2694
+ var KEY_PREFIX = "CC1";
2682
2695
  var NOT_ACTIVATED_MESSAGE = [
2683
2696
  "costclaw optimize needs a license.",
2684
2697
  "",
@@ -2688,11 +2701,12 @@ var NOT_ACTIVATED_MESSAGE = [
2688
2701
  "costclaw audit is free and does not need a license."
2689
2702
  ].join("\n");
2690
2703
  var INVALID_MESSAGE = [
2691
- "Your CostClaw license is no longer valid. It may have been refunded or deactivated.",
2704
+ "The saved CostClaw license is not valid for this version.",
2692
2705
  "",
2693
- "Buy again at https://costclaw.io, then run:",
2706
+ "Re-activate with the key from your purchase email:",
2694
2707
  " costclaw activate <your-license-key>",
2695
2708
  "",
2709
+ "Key missing or not working? Email wes@dashclaw.io with your order number.",
2696
2710
  "costclaw audit stays free."
2697
2711
  ].join("\n");
2698
2712
  function defaultConfigDir() {
@@ -2701,13 +2715,29 @@ function defaultConfigDir() {
2701
2715
  function licenseFile(dir) {
2702
2716
  return join5(dir, "license.json");
2703
2717
  }
2704
- function metaMatches(meta) {
2705
- return !!meta && meta.store_id === STORE_ID && meta.product_id === PRODUCT_ID;
2718
+ function base64UrlDecode(part) {
2719
+ return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
2720
+ }
2721
+ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
2722
+ const parts = licenseKey.trim().split(".");
2723
+ if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
2724
+ const [prefix, payloadPart, signaturePart] = parts;
2725
+ try {
2726
+ const publicKey = createPublicKey(publicKeyPem);
2727
+ const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
2728
+ const signature = base64UrlDecode(signaturePart);
2729
+ if (!cryptoVerify(null, signed, publicKey, signature)) return null;
2730
+ const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
2731
+ if (payload.p !== LICENSE_PRODUCT) return null;
2732
+ return payload;
2733
+ } catch {
2734
+ return null;
2735
+ }
2706
2736
  }
2707
2737
  async function readStoredLicense(dir) {
2708
2738
  try {
2709
2739
  const data = JSON.parse(await readFile6(licenseFile(dir), "utf8"));
2710
- if (!data || typeof data.licenseKey !== "string" || typeof data.instanceId !== "string") return null;
2740
+ if (!data || typeof data.licenseKey !== "string") return null;
2711
2741
  return data;
2712
2742
  } catch {
2713
2743
  return null;
@@ -2720,38 +2750,21 @@ async function writeStoredLicense(dir, lic) {
2720
2750
  async function clearStoredLicense(dir) {
2721
2751
  await rm(licenseFile(dir), { force: true });
2722
2752
  }
2723
- async function post(endpoint, fields, fetchImpl) {
2724
- const res = await fetchImpl(`${API_BASE}/${endpoint}`, {
2725
- method: "POST",
2726
- headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
2727
- body: new URLSearchParams(fields).toString()
2728
- });
2729
- return res.json();
2730
- }
2731
2753
  async function activateLicense(licenseKey, opts = {}) {
2732
2754
  const key = licenseKey.trim();
2733
2755
  if (!key) throw new Error("Provide your license key: costclaw activate <key>");
2734
- const fetchImpl = opts.fetchImpl ?? defaultFetch;
2735
2756
  const configDir = opts.configDir ?? defaultConfigDir();
2736
- const instanceName = opts.instanceName?.trim() || hostname();
2737
- const json = await post("activate", { license_key: key, instance_name: instanceName }, fetchImpl);
2738
- if (json.activated !== true) {
2739
- const detail = typeof json.error === "string" && json.error ? json.error : "the key could not be activated";
2757
+ const payload = verifyLicenseKey(key, opts.publicKeyPem);
2758
+ if (!payload) {
2740
2759
  throw new Error(
2741
- `Could not activate this license key: ${detail}.
2742
- Check the key from your CostClaw purchase email, or buy one at https://costclaw.io.`
2760
+ "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."
2743
2761
  );
2744
2762
  }
2745
- if (!metaMatches(json.meta)) {
2746
- throw new Error("That key is valid but it is not a CostClaw optimize license. Use the key from your CostClaw purchase.");
2747
- }
2748
- const instanceId = json.instance?.id;
2749
- if (!instanceId) throw new Error("Lemon Squeezy did not return an activation id. Try again in a moment.");
2750
2763
  const stored = {
2751
2764
  licenseKey: key,
2752
- instanceId,
2753
- instanceName,
2754
- email: json.meta?.customer_email,
2765
+ instanceId: "local",
2766
+ instanceName: opts.instanceName?.trim() || hostname(),
2767
+ email: payload.e,
2755
2768
  activatedAt: (/* @__PURE__ */ new Date()).toISOString()
2756
2769
  };
2757
2770
  await writeStoredLicense(configDir, stored);
@@ -2761,15 +2774,9 @@ async function checkLicense(opts = {}) {
2761
2774
  const configDir = opts.configDir ?? defaultConfigDir();
2762
2775
  const stored = await readStoredLicense(configDir);
2763
2776
  if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
2764
- const fetchImpl = opts.fetchImpl ?? defaultFetch;
2765
- let json;
2766
- try {
2767
- json = await post("validate", { license_key: stored.licenseKey }, fetchImpl);
2768
- } catch {
2769
- return { ok: true, email: stored.email, offline: true };
2770
- }
2771
- if (json.valid === true && metaMatches(json.meta)) {
2772
- return { ok: true, email: json.meta?.customer_email ?? stored.email };
2777
+ const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
2778
+ if (payload) {
2779
+ return { ok: true, email: payload.e ?? stored.email };
2773
2780
  }
2774
2781
  await clearStoredLicense(configDir);
2775
2782
  return { ok: false, message: INVALID_MESSAGE };
@@ -2778,11 +2785,6 @@ async function deactivateLicense(opts = {}) {
2778
2785
  const configDir = opts.configDir ?? defaultConfigDir();
2779
2786
  const stored = await readStoredLicense(configDir);
2780
2787
  if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
2781
- const fetchImpl = opts.fetchImpl ?? defaultFetch;
2782
- try {
2783
- await post("deactivate", { license_key: stored.licenseKey, instance_id: stored.instanceId }, fetchImpl);
2784
- } catch {
2785
- }
2786
2788
  await clearStoredLicense(configDir);
2787
2789
  }
2788
2790
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
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": {