costclaw 0.5.6 → 0.5.8

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 +184 -14
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1666,10 +1666,9 @@ function stackOneLiner(stack) {
1666
1666
  }
1667
1667
  return `A ${joined} project.`;
1668
1668
  }
1669
- function buildClaudeMd(input, recoverable, notes, stats) {
1669
+ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1670
1670
  const { currentClaudeMd, project } = input;
1671
1671
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
1672
- const carried = carriedSections(currentClaudeMd);
1673
1672
  const recoverableLine = recoverable >= 1 ? ` - Your audit valued cache-miss exposure at ${usd(recoverable)}. Keeping this file small and stable is part of recovering it; the matching PLAYBOOK.md has the rest.` : " - Keeping this file small and stable keeps the cached prefix cheap to reuse each turn.";
1674
1673
  const parts = [];
1675
1674
  parts.push(
@@ -1744,7 +1743,7 @@ function buildClaudeMd(input, recoverable, notes, stats) {
1744
1743
  if (droppedCommands > 0) {
1745
1744
  lines.push("");
1746
1745
  lines.push(
1747
- `The remaining ${droppedCommands} scripts stay in \`package.json\`; add one here only when the agent keeps needing it.`
1746
+ "The remaining scripts stay in `package.json`; add one here only when the agent keeps needing it."
1748
1747
  );
1749
1748
  notes.push(
1750
1749
  `Kept the ${commands.length} canonical commands of ${allCommands.length} detected; the rest stay in the manifest so this file stays lean.`
@@ -2091,9 +2090,12 @@ var BASE_DENY = [
2091
2090
  "Bash(rm *)",
2092
2091
  "Bash(rm -rf:*)",
2093
2092
  "Bash(sudo:*)",
2094
- "Bash(git push:*)",
2093
+ "Bash(git push --force:*)",
2094
+ "Bash(git push -f:*)",
2095
2095
  "Read(.env)",
2096
- "Read(.env.*)",
2096
+ "Read(.env.local)",
2097
+ "Read(.env.production)",
2098
+ "Read(.env.*.local)",
2097
2099
  "Read(**/*.pem)",
2098
2100
  "Read(**/*.key)",
2099
2101
  "Read(~/.ssh/**)"
@@ -2110,24 +2112,167 @@ function buildSettings(project) {
2110
2112
  const settings = { permissions: { allow, deny: [...BASE_DENY] } };
2111
2113
  return clean(JSON.stringify(settings, null, 2) + "\n");
2112
2114
  }
2115
+ function buildHarnessPrompt(input, carried) {
2116
+ const project = input.project;
2117
+ const name = project?.name?.trim() || "this project";
2118
+ const findings = input.report.findings;
2119
+ const has = (id) => findings.some((f) => f.ruleId === id);
2120
+ const heavyTools = [
2121
+ ...new Set(
2122
+ findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS").map((f) => String(f.evidence?.["tool"] ?? "")).filter((t) => t.length > 0)
2123
+ )
2124
+ ];
2125
+ const parts = [];
2126
+ parts.push(`# CostClaw harness upgrade for ${name}`);
2127
+ parts.push(
2128
+ [
2129
+ "You are Claude Code, working in this repository. costclaw generated this",
2130
+ "work order from a local audit of real usage logs plus a scan of this",
2131
+ "project; every task is grounded in that evidence. Execute the tasks in",
2132
+ "order and report what changed at the end."
2133
+ ].join("\n")
2134
+ );
2135
+ parts.push(
2136
+ [
2137
+ "## Ground rules",
2138
+ "",
2139
+ "- Never invent project facts. When a merge choice is unclear, ask.",
2140
+ "- Show a diff before replacing any human-written file, and back the",
2141
+ " file up first (CLAUDE.md -> CLAUDE.md.bak).",
2142
+ "- Keep the final CLAUDE.md lean: under about 200 lines, and every line",
2143
+ ' must pass "would removing this make the agent make a mistake?"',
2144
+ "- Commit per this repo's conventions when a task completes cleanly."
2145
+ ].join("\n")
2146
+ );
2147
+ parts.push(
2148
+ [
2149
+ "## Task 1: Merge the optimized CLAUDE.md",
2150
+ "",
2151
+ "Merge `costclaw-out/CLAUDE.optimized.md` into `./CLAUDE.md`:",
2152
+ "",
2153
+ "- Conflicting facts: the existing CLAUDE.md wins (it is the human's).",
2154
+ "- Structure and curation: the optimized file wins (section set, command",
2155
+ " curation, dropped filler).",
2156
+ "- Commands: start from the optimized curated list with its annotations;",
2157
+ " re-add a dropped script only when the workflow genuinely needs it",
2158
+ " pinned in an always-loaded file.",
2159
+ "- Strip the generator's HTML comment blocks from the final file.",
2160
+ "- Back up, show the diff, then write."
2161
+ ].join("\n")
2162
+ );
2163
+ parts.push(
2164
+ [
2165
+ "## Task 2: Permission allowlist",
2166
+ "",
2167
+ "Review `costclaw-out/settings.suggested.json` (read-only tools plus",
2168
+ "this project's safe commands; denies secret reads and destructive",
2169
+ "ops). Merge the rules you agree with additively into",
2170
+ "`.claude/settings.json`, keeping every existing entry.",
2171
+ "`npx costclaw optimize --apply-settings` performs the mechanical merge",
2172
+ "with a backup and a diff if you prefer."
2173
+ ].join("\n")
2174
+ );
2175
+ let n = 3;
2176
+ if (carried.droppedVolatile.length > 0) {
2177
+ parts.push(
2178
+ [
2179
+ `## Task ${n++}: Rehome volatile content`,
2180
+ "",
2181
+ `The optimized file left out ${joinAnd(carried.droppedVolatile)}:`,
2182
+ "status-style sections churn on every update and bust the prompt",
2183
+ "cache. Move that content from the old CLAUDE.md into docs/ (or a",
2184
+ "scratch note the agent opens on demand) so nothing is lost when the",
2185
+ "merge lands."
2186
+ ].join("\n")
2187
+ );
2188
+ }
2189
+ if (project?.preCommit) {
2190
+ parts.push(
2191
+ [
2192
+ `## Task ${n++}: Enforce the pre-commit gate`,
2193
+ "",
2194
+ `The project's gate is: ${project.preCommit}.`,
2195
+ "Prose in CLAUDE.md is advisory; make the gate real. If no pre-commit",
2196
+ "hook runs it, add one in the repo's existing style (husky, a plain",
2197
+ ".git/hooks script, or the project's hook framework), and verify it",
2198
+ "fires on a throwaway commit."
2199
+ ].join("\n")
2200
+ );
2201
+ }
2202
+ if (heavyTools.length > 0) {
2203
+ parts.push(
2204
+ [
2205
+ `## Task ${n++}: Stop-condition guardrails`,
2206
+ "",
2207
+ `The audit found sessions where ${joinAnd(heavyTools)} fired far past`,
2208
+ "a sane loop bound. Add one line to CLAUDE.md's workflow section",
2209
+ "telling the agent to state a stop condition before search or edit",
2210
+ "loops, and consider a PreToolUse hook that warns on a high",
2211
+ "per-session count for those tools."
2212
+ ].join("\n")
2213
+ );
2214
+ }
2215
+ if (has("MODEL_MISROUTE")) {
2216
+ parts.push(
2217
+ [
2218
+ `## Task ${n++}: Model routing defaults`,
2219
+ "",
2220
+ "The audit found short, trivial sessions running on premium models",
2221
+ "(Opus, Fable). Add a routing line to CLAUDE.md (cheap model for",
2222
+ "short, simple tasks; premium for hard reasoning), and if the user",
2223
+ "agrees, set shell defaults (ANTHROPIC_MODEL,",
2224
+ "CLAUDE_CODE_EFFORT_LEVEL) so sessions start right without a",
2225
+ "per-session step."
2226
+ ].join("\n")
2227
+ );
2228
+ }
2229
+ if (has("MARATHON_SESSION")) {
2230
+ parts.push(
2231
+ [
2232
+ `## Task ${n++}: Marathon-session hygiene`,
2233
+ "",
2234
+ "The audit found long sessions whose cache decayed turn over turn.",
2235
+ "Add a compact-between-tasks line to CLAUDE.md: run /compact before",
2236
+ "the context outgrows the cache, and /clear between unrelated tasks."
2237
+ ].join("\n")
2238
+ );
2239
+ }
2240
+ const verify = ["## Verify", ""];
2241
+ const testCmd = project?.commands.find((c) => c.label === "test")?.command;
2242
+ const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
2243
+ if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
2244
+ if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
2245
+ verify.push(
2246
+ "- Confirm CLAUDE.md is under about 200 lines with no generator comments",
2247
+ " left in it.",
2248
+ "- After about a week of normal usage, run `npx costclaw audit`: the",
2249
+ ' "Since optimize" line measures the cache-hit movement these changes',
2250
+ " are meant to produce."
2251
+ );
2252
+ parts.push(verify.join("\n"));
2253
+ return clean(parts.join("\n\n").trimEnd() + "\n");
2254
+ }
2113
2255
  function optimize(input) {
2114
2256
  const recoverable = cacheMissExposureUsd(input.report);
2115
2257
  const notes = [];
2116
2258
  const stats = { placeholders: 0 };
2117
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats);
2259
+ const carried = carriedSections(input.currentClaudeMd);
2260
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried);
2118
2261
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, input.project);
2119
2262
  const settingsJson = buildSettings(input.project);
2263
+ const harnessPrompt = buildHarnessPrompt(input, carried);
2120
2264
  const cleanNotes = notes.map((n) => clean(n));
2121
- if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || cleanNotes.some(hasEmDash)) {
2265
+ if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash)) {
2122
2266
  return {
2123
2267
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2124
2268
  playbook: sanitizeText(playbook),
2125
2269
  settingsJson: sanitizeText(settingsJson),
2270
+ harnessPrompt: sanitizeText(harnessPrompt),
2126
2271
  notes: cleanNotes.map(sanitizeText),
2127
2272
  placeholdersRemaining: stats.placeholders
2128
2273
  };
2129
2274
  }
2130
- return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
2275
+ return { optimizedClaudeMd, playbook, settingsJson, harnessPrompt, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
2131
2276
  }
2132
2277
 
2133
2278
  // ../../packages/engine/src/audit.ts
@@ -3359,14 +3504,30 @@ async function detectStructure(dir, dirs) {
3359
3504
  }
3360
3505
  return structure;
3361
3506
  }
3507
+ var TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
3508
+ async function containsTestFiles(dir) {
3509
+ const top = await listEntries(dir);
3510
+ if (top.files.some((f) => TEST_FILE.test(f))) return true;
3511
+ for (const sub of top.dirs) {
3512
+ const inner = await listEntries(join5(dir, sub));
3513
+ if (inner.files.some((f) => TEST_FILE.test(f))) return true;
3514
+ }
3515
+ return false;
3516
+ }
3362
3517
  async function detectTestsLocation(dir, files, dirs) {
3363
- if (dirs.includes("tests")) return "tests in tests/";
3364
- if (dirs.includes("test")) return "tests in test/";
3365
- if (dirs.includes("__tests__")) return "tests in __tests__/";
3366
- if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
3518
+ const candidates = ["tests", "test", "__tests__"].filter((d) => dirs.includes(d));
3519
+ if (candidates.length > 0) {
3520
+ const withTests = [];
3521
+ for (const c of candidates) {
3522
+ if (await containsTestFiles(join5(dir, c))) withTests.push(c);
3523
+ }
3524
+ const chosen = withTests.length > 0 ? withTests : candidates;
3525
+ return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
3526
+ }
3527
+ if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
3367
3528
  if (dirs.includes("src")) {
3368
3529
  const sub = await listEntries(join5(dir, "src"));
3369
- if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
3530
+ if (sub.files.some((f) => TEST_FILE.test(f))) {
3370
3531
  return "tests alongside source (*.test.* / *.spec.*)";
3371
3532
  }
3372
3533
  }
@@ -3732,6 +3893,7 @@ async function scanProject(dir) {
3732
3893
  var OPTIMIZED_NAME = "CLAUDE.optimized.md";
3733
3894
  var PLAYBOOK_NAME = "PLAYBOOK.md";
3734
3895
  var SETTINGS_NAME = "settings.suggested.json";
3896
+ var HARNESS_NAME = "HARNESS-UPGRADE.md";
3735
3897
  function usd5(n) {
3736
3898
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
3737
3899
  }
@@ -3870,6 +4032,8 @@ async function runOptimize(opts) {
3870
4032
  await writeFile3(playbookPath, result.playbook, "utf8");
3871
4033
  const settingsPath = join6(outDir, SETTINGS_NAME);
3872
4034
  await writeFile3(settingsPath, result.settingsJson, "utf8");
4035
+ const harnessPath = join6(outDir, HARNESS_NAME);
4036
+ await writeFile3(harnessPath, result.harnessPrompt, "utf8");
3873
4037
  const lines = [];
3874
4038
  lines.push("CostClaw optimize");
3875
4039
  lines.push("");
@@ -3891,6 +4055,7 @@ async function runOptimize(opts) {
3891
4055
  lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
3892
4056
  lines.push(`Wrote the playbook to ${playbookPath}`);
3893
4057
  lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
4058
+ lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
3894
4059
  lines.push("");
3895
4060
  lines.push("Diff (old vs new):");
3896
4061
  lines.push(lineDiff(original, result.optimizedClaudeMd));
@@ -3906,6 +4071,7 @@ async function runOptimize(opts) {
3906
4071
  lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
3907
4072
  lines.push(`Wrote the playbook to ${playbookPath}`);
3908
4073
  lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
4074
+ lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
3909
4075
  lines.push("");
3910
4076
  lines.push(describeDetection(project));
3911
4077
  if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
@@ -3930,6 +4096,10 @@ async function runOptimize(opts) {
3930
4096
  lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
3931
4097
  lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied unless you ask.");
3932
4098
  lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
4099
+ lines.push("");
4100
+ lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
4101
+ lines.push(' claude "Follow costclaw-out/HARNESS-UPGRADE.md"');
4102
+ 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.");
3933
4103
  }
3934
4104
  if (opts.applySettings) {
3935
4105
  const target = opts.applySettingsPath || join6(projectDir, ".claude", "settings.json");
@@ -4271,7 +4441,7 @@ function parseBadgeFlags(args) {
4271
4441
  };
4272
4442
  }
4273
4443
  function cliVersion() {
4274
- return true ? "0.5.6" : "0.0.0-dev";
4444
+ return true ? "0.5.8" : "0.0.0-dev";
4275
4445
  }
4276
4446
  function helpText() {
4277
4447
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
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": {