costclaw 0.5.2 → 0.5.4

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 +194 -46
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1546,6 +1546,78 @@ function carriedIntro(currentClaudeMd) {
1546
1546
  }
1547
1547
  return { title, intro, introDropped };
1548
1548
  }
1549
+ function parseSections(md) {
1550
+ const lines = md.split(/\r?\n/);
1551
+ const sections = [];
1552
+ let current = null;
1553
+ for (const line of lines) {
1554
+ const m = line.match(/^##\s+(.+?)\s*$/);
1555
+ if (m) {
1556
+ if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1557
+ current = { heading: m[1], body: [] };
1558
+ } else if (current) {
1559
+ current.body.push(line);
1560
+ }
1561
+ }
1562
+ if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1563
+ return sections.filter((s) => s.body.length > 0);
1564
+ }
1565
+ var REGENERATED_HEADING = [
1566
+ /^(commands?|scripts?)\b/i,
1567
+ /^(project structure|structure|layout|directory)/i,
1568
+ /^(code style|style|formatting)\b/i,
1569
+ /^test(s|ing)?\b/i,
1570
+ /^env(ironment)?\b/i
1571
+ ];
1572
+ var VOLATILE_HEADING = /^(status|changelog|progress|history|roadmap|todos?|next steps)\b/i;
1573
+ var WORKFLOW_HEADING = /workflow|etiquette|contributing|branch|commit/i;
1574
+ var ARCH_HEADING = /architecture|gotcha|footgun|how it works|data flow|overview/i;
1575
+ function carriedSections(currentClaudeMd) {
1576
+ const out = { workflow: null, architecture: null, other: [], droppedVolatile: [], replaced: [] };
1577
+ if (!currentClaudeMd) return out;
1578
+ for (const section of parseSections(currentClaudeMd)) {
1579
+ if (VOLATILE_HEADING.test(section.heading)) {
1580
+ out.droppedVolatile.push(section.heading);
1581
+ } else if (REGENERATED_HEADING.some((re) => re.test(section.heading))) {
1582
+ out.replaced.push(section.heading);
1583
+ } else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
1584
+ out.workflow = section.body;
1585
+ } else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
1586
+ out.architecture = section.body;
1587
+ } else {
1588
+ out.other.push(section);
1589
+ }
1590
+ }
1591
+ return out;
1592
+ }
1593
+ var CANONICAL_LABELS = /* @__PURE__ */ new Set([
1594
+ "install",
1595
+ "dev",
1596
+ "start",
1597
+ "serve",
1598
+ "demo",
1599
+ "build",
1600
+ "test",
1601
+ "test one file",
1602
+ "lint",
1603
+ "typecheck",
1604
+ "format",
1605
+ "e2e",
1606
+ "migrate",
1607
+ "db:migrate"
1608
+ ]);
1609
+ var MAX_COMMANDS = 12;
1610
+ function curateCommands(commands) {
1611
+ if (commands.length <= MAX_COMMANDS) return { kept: commands, dropped: 0 };
1612
+ const kept = commands.filter((c) => CANONICAL_LABELS.has(c.label.toLowerCase()));
1613
+ const chosen = (kept.length >= 4 ? kept : commands).slice(0, MAX_COMMANDS);
1614
+ return { kept: chosen, dropped: commands.length - chosen.length };
1615
+ }
1616
+ function commandLine(c) {
1617
+ const tokens = c.command.toLowerCase().split(/[^a-z0-9:_-]+/);
1618
+ const redundant = tokens.includes(c.label.toLowerCase());
1619
+ return redundant ? `- \`${c.command}\`` : `- \`${c.command}\` ${c.label}`;
1620
+ }
1549
1621
  function stackOneLiner(stack) {
1550
1622
  const items = stack.map((s) => s.trim()).filter((s) => s.length > 0);
1551
1623
  if (items.length === 0) return null;
@@ -1559,9 +1631,10 @@ function stackOneLiner(stack) {
1559
1631
  }
1560
1632
  return `A ${joined} project.`;
1561
1633
  }
1562
- function buildClaudeMd(input, recoverable, notes) {
1634
+ function buildClaudeMd(input, recoverable, notes, stats) {
1563
1635
  const { currentClaudeMd, project } = input;
1564
1636
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
1637
+ const carried = carriedSections(currentClaudeMd);
1565
1638
  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.";
1566
1639
  const parts = [];
1567
1640
  parts.push(
@@ -1605,7 +1678,13 @@ function buildClaudeMd(input, recoverable, notes) {
1605
1678
  }
1606
1679
  const projectDesc = project?.description?.trim() || null;
1607
1680
  const synthesized = project ? stackOneLiner(project.stack) : null;
1608
- const descLine = projectDesc ?? synthesized ?? intro ?? "<!-- one line: the stack and what this project does, e.g. Node and Postgres API on Render -->";
1681
+ let descLine;
1682
+ if (projectDesc ?? synthesized ?? intro) {
1683
+ descLine = projectDesc ?? synthesized ?? intro;
1684
+ } else {
1685
+ descLine = "<!-- one line: the stack and what this project does, e.g. Node and Postgres API on Render -->";
1686
+ stats.placeholders += 1;
1687
+ }
1609
1688
  if (projectDesc) {
1610
1689
  filled.push("Description");
1611
1690
  } else if (synthesized) {
@@ -1618,14 +1697,25 @@ function buildClaudeMd(input, recoverable, notes) {
1618
1697
  );
1619
1698
  }
1620
1699
  parts.push([`# ${titleText}`, "", descLine].join("\n"));
1621
- const commands = project?.commands ?? [];
1700
+ const allCommands = project?.commands ?? [];
1701
+ const { kept: commands, dropped: droppedCommands } = curateCommands(allCommands);
1622
1702
  if (commands.length > 0) {
1623
1703
  const lines = ["## Commands", ""];
1624
- for (const c of commands) lines.push(`- \`${c.command}\` ${c.label}`);
1704
+ for (const c of commands) lines.push(commandLine(c));
1625
1705
  if (project?.preCommit) lines.push(`- IMPORTANT: ${project.preCommit}.`);
1706
+ if (droppedCommands > 0) {
1707
+ lines.push("");
1708
+ lines.push(
1709
+ `The remaining ${droppedCommands} scripts stay in \`package.json\`; add one here only when the agent keeps needing it.`
1710
+ );
1711
+ notes.push(
1712
+ `Kept the ${commands.length} canonical commands of ${allCommands.length} detected; the rest stay in the manifest so this file stays lean.`
1713
+ );
1714
+ }
1626
1715
  parts.push(lines.join("\n"));
1627
1716
  filled.push("Commands");
1628
1717
  } else {
1718
+ stats.placeholders += 1;
1629
1719
  parts.push(
1630
1720
  [
1631
1721
  "## Commands",
@@ -1646,7 +1736,7 @@ function buildClaudeMd(input, recoverable, notes) {
1646
1736
  ].join("\n")
1647
1737
  );
1648
1738
  }
1649
- const structure = project?.structure ?? [];
1739
+ const structure = (project?.structure ?? []).filter((d) => d.note.trim().length > 0).slice(0, 10);
1650
1740
  if (structure.length > 0) {
1651
1741
  const lines = ["## Project structure", ""];
1652
1742
  for (const d of structure) {
@@ -1656,6 +1746,7 @@ function buildClaudeMd(input, recoverable, notes) {
1656
1746
  parts.push(lines.join("\n"));
1657
1747
  filled.push("Project structure");
1658
1748
  } else {
1749
+ stats.placeholders += 1;
1659
1750
  parts.push(
1660
1751
  [
1661
1752
  "## Project structure",
@@ -1671,13 +1762,14 @@ function buildClaudeMd(input, recoverable, notes) {
1671
1762
  ].join("\n")
1672
1763
  );
1673
1764
  }
1674
- const codeStyle = project?.codeStyle ?? [];
1765
+ const codeStyle = (project?.codeStyle ?? []).filter((s) => !/\bconfigured\s*$/i.test(s.trim()));
1675
1766
  if (codeStyle.length > 0) {
1676
1767
  const lines = ["## Code style", ""];
1677
1768
  for (const s of codeStyle) lines.push(`- ${s}`);
1678
1769
  parts.push(lines.join("\n"));
1679
1770
  filled.push("Code style");
1680
1771
  } else {
1772
+ stats.placeholders += 1;
1681
1773
  parts.push(
1682
1774
  [
1683
1775
  "## Code style",
@@ -1700,6 +1792,7 @@ function buildClaudeMd(input, recoverable, notes) {
1700
1792
  parts.push(lines.join("\n"));
1701
1793
  filled.push("Testing");
1702
1794
  } else {
1795
+ stats.placeholders += 1;
1703
1796
  parts.push(
1704
1797
  [
1705
1798
  "## Testing",
@@ -1713,32 +1806,47 @@ function buildClaudeMd(input, recoverable, notes) {
1713
1806
  ].join("\n")
1714
1807
  );
1715
1808
  }
1716
- parts.push(
1717
- [
1718
- "## Workflow",
1719
- "",
1720
- "<!--",
1721
- " Repository etiquette: branch naming, commit message rules, which branch PRs",
1722
- " target, merge vs rebase.",
1723
- "-->",
1724
- "- <!-- branch naming and commit conventions -->",
1725
- "- Typecheck and run the tests after a set of changes, before calling it done."
1726
- ].join("\n")
1727
- );
1728
- parts.push(
1729
- [
1730
- "## Architecture and gotchas",
1731
- "",
1732
- "<!--",
1733
- " The highest-leverage prose: non-obvious, project-specific facts and footguns.",
1734
- " Grow this over time. Whenever the agent makes the same mistake twice, add a",
1735
- " line here. Example:",
1736
- " - Migrations are not auto-run: run `npm run migrate` after pulling.",
1737
- " - Auth tokens refresh in `src/auth/refresh.ts`, not per-request.",
1738
- "-->",
1739
- "- <!-- a non-obvious fact or footgun the agent should know -->"
1740
- ].join("\n")
1741
- );
1809
+ if (carried.workflow) {
1810
+ parts.push(["## Workflow", "", carried.workflow].join("\n"));
1811
+ filled.push("Workflow");
1812
+ } else {
1813
+ stats.placeholders += 1;
1814
+ parts.push(
1815
+ [
1816
+ "## Workflow",
1817
+ "",
1818
+ "<!--",
1819
+ " Repository etiquette: branch naming, commit message rules, which branch PRs",
1820
+ " target, merge vs rebase.",
1821
+ "-->",
1822
+ "- <!-- branch naming and commit conventions -->",
1823
+ "- Typecheck and run the tests after a set of changes, before calling it done."
1824
+ ].join("\n")
1825
+ );
1826
+ }
1827
+ if (carried.architecture) {
1828
+ parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
1829
+ filled.push("Architecture and gotchas");
1830
+ } else {
1831
+ stats.placeholders += 1;
1832
+ parts.push(
1833
+ [
1834
+ "## Architecture and gotchas",
1835
+ "",
1836
+ "<!--",
1837
+ " The highest-leverage prose: non-obvious, project-specific facts and footguns.",
1838
+ " Grow this over time. Whenever the agent makes the same mistake twice, add a",
1839
+ " line here. Example:",
1840
+ " - Migrations are not auto-run: run `npm run migrate` after pulling.",
1841
+ " - Auth tokens refresh in `src/auth/refresh.ts`, not per-request.",
1842
+ "-->",
1843
+ "- <!-- a non-obvious fact or footgun the agent should know -->"
1844
+ ].join("\n")
1845
+ );
1846
+ }
1847
+ for (const section of carried.other) {
1848
+ parts.push([`## ${section.heading}`, "", section.body].join("\n"));
1849
+ }
1742
1850
  const envVars = (project?.envVars ?? []).map((v) => v.trim()).filter((v) => v.length > 0);
1743
1851
  if (envVars.length > 0) {
1744
1852
  const names = envVars.map((v) => `\`${v}\``).join(", ");
@@ -1751,6 +1859,7 @@ function buildClaudeMd(input, recoverable, notes) {
1751
1859
  );
1752
1860
  filled.push("Environment");
1753
1861
  } else {
1862
+ stats.placeholders += 1;
1754
1863
  parts.push(
1755
1864
  [
1756
1865
  "## Environment",
@@ -1778,11 +1887,30 @@ function buildClaudeMd(input, recoverable, notes) {
1778
1887
  "-->"
1779
1888
  ].join("\n")
1780
1889
  );
1890
+ const carriedNames = [
1891
+ ...carried.workflow ? ["Workflow"] : [],
1892
+ ...carried.architecture ? ["Architecture and gotchas"] : [],
1893
+ ...carried.other.map((s) => s.heading)
1894
+ ];
1895
+ if (carriedNames.length > 0) {
1896
+ notes.push(
1897
+ `Carried ${joinAnd(carriedNames)} across from your existing CLAUDE.md; hold each line to the "earns its place" bar.`
1898
+ );
1899
+ }
1900
+ if (carried.replaced.length > 0) {
1901
+ notes.push(
1902
+ `Replaced your ${joinAnd(carried.replaced)} section${carried.replaced.length === 1 ? "" : "s"} with the version derived from the project scan; compare before applying.`
1903
+ );
1904
+ }
1905
+ if (carried.droppedVolatile.length > 0) {
1906
+ notes.push(
1907
+ `Left out ${joinAnd(carried.droppedVolatile)}: status-style sections churn on every update and bust the prompt cache. Keep that content in docs or a scratch note the agent opens on demand.`
1908
+ );
1909
+ }
1781
1910
  if (project) {
1782
1911
  if (filled.length > 0) {
1783
- notes.push(
1784
- `Filled ${joinAnd(filled)} from your project; Architecture and gotchas is left as a placeholder for you to grow.`
1785
- );
1912
+ const growNote = carried.architecture ? "" : "; Architecture and gotchas is left as a placeholder for you to grow";
1913
+ notes.push(`Filled ${joinAnd(filled)} from your project${growNote}.`);
1786
1914
  } else {
1787
1915
  notes.push(
1788
1916
  "Your project had no detectable facts, so every section is a placeholder and nothing was invented."
@@ -1884,13 +2012,17 @@ function tokenDiscipline(report) {
1884
2012
  "- Set `ANTHROPIC_MODEL` and `CLAUDE_CODE_EFFORT_LEVEL` in your shell profile so every session starts on the right model and effort without a per-session step."
1885
2013
  ].join("\n");
1886
2014
  }
1887
- function buildPlaybook(report, fixes, scores, recoverable) {
2015
+ function buildPlaybook(report, fixes, scores, recoverable, project) {
1888
2016
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
1889
2017
  const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
1890
2018
  const parts = [];
1891
2019
  parts.push("# CostClaw fix playbook");
2020
+ const projectName = project?.name?.trim();
2021
+ const stack = (project?.stack ?? []).filter((s) => s.trim().length > 0);
2022
+ const projectLine = projectName ? `Project: ${projectName}${stack.length > 0 ? ` (${stack.join(", ")})` : ""}.` : null;
1892
2023
  parts.push(
1893
2024
  [
2025
+ ...projectLine ? [projectLine, ""] : [],
1894
2026
  `Total recoverable spend: ${usd(recoverable)} (cache-miss exposure).`,
1895
2027
  "",
1896
2028
  "This is the ranked plan from your audit. The priority fixes are ordered by the dollars they recover; the setup warnings follow. CostClaw generates the plan; working through it is what recovers the spend."
@@ -1940,8 +2072,9 @@ function buildSettings(project) {
1940
2072
  function optimize(input) {
1941
2073
  const recoverable = cacheMissExposureUsd(input.report);
1942
2074
  const notes = [];
1943
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes);
1944
- const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable);
2075
+ const stats = { placeholders: 0 };
2076
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats);
2077
+ const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, input.project);
1945
2078
  const settingsJson = buildSettings(input.project);
1946
2079
  const cleanNotes = notes.map((n) => clean(n));
1947
2080
  if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || cleanNotes.some(hasEmDash)) {
@@ -1949,10 +2082,11 @@ function optimize(input) {
1949
2082
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
1950
2083
  playbook: sanitizeText(playbook),
1951
2084
  settingsJson: sanitizeText(settingsJson),
1952
- notes: cleanNotes.map(sanitizeText)
2085
+ notes: cleanNotes.map(sanitizeText),
2086
+ placeholdersRemaining: stats.placeholders
1953
2087
  };
1954
2088
  }
1955
- return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes };
2089
+ return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
1956
2090
  }
1957
2091
 
1958
2092
  // ../../packages/engine/src/audit.ts
@@ -3606,13 +3740,18 @@ async function applyDerivedSettings(target, suggestedJson, force) {
3606
3740
  ];
3607
3741
  }
3608
3742
  async function runOptimize(opts) {
3609
- const { logs, claudeMd } = await loadAuditInputs({ path: opts.path, claudeMdPath: opts.claudeMdPath });
3743
+ const projectDir = opts.projectDir || process.cwd();
3744
+ let claudeMdPath = opts.claudeMdPath;
3745
+ if (!claudeMdPath) {
3746
+ const projectClaudeMd = join6(projectDir, "CLAUDE.md");
3747
+ if (await pathExists(projectClaudeMd)) claudeMdPath = projectClaudeMd;
3748
+ }
3749
+ const { logs, claudeMd, claudeMdSource } = await loadAuditInputs({ path: opts.path, claudeMdPath });
3610
3750
  const report = analyzeUploads(logs);
3611
3751
  const cmd = analyzeClaudeMd(claudeMd);
3612
3752
  const { pillars } = scorePillars(report, cmd, {});
3613
3753
  const { plan } = await resolvePlan(join6(opts.home ?? homedir4(), ".costclaw"), opts.plan);
3614
3754
  const { fixes } = synthesize(report, pillars, cmd, plan);
3615
- const projectDir = opts.projectDir || process.cwd();
3616
3755
  const project = await scanProject(projectDir);
3617
3756
  const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
3618
3757
  const recoverable = cacheMissExposureUsd(report);
@@ -3647,7 +3786,9 @@ async function runOptimize(opts) {
3647
3786
  lines.push("Diff (old vs new):");
3648
3787
  lines.push(lineDiff(original, result.optimizedClaudeMd));
3649
3788
  lines.push("");
3650
- lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
3789
+ if (result.placeholdersRemaining > 0) {
3790
+ lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
3791
+ }
3651
3792
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
3652
3793
  } else {
3653
3794
  const optimizedPath = join6(outDir, OPTIMIZED_NAME);
@@ -3658,6 +3799,7 @@ async function runOptimize(opts) {
3658
3799
  lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
3659
3800
  lines.push("");
3660
3801
  lines.push(describeDetection(project));
3802
+ if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
3661
3803
  if (plan === "api") {
3662
3804
  lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
3663
3805
  } else {
@@ -3668,8 +3810,14 @@ async function runOptimize(opts) {
3668
3810
  );
3669
3811
  }
3670
3812
  lines.push("");
3671
- lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
3672
- lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
3813
+ if (result.placeholdersRemaining > 0) {
3814
+ const n = result.placeholdersRemaining;
3815
+ lines.push(`The optimized CLAUDE.md has ${n} section${n === 1 ? "" : "s"} left as placeholders (no evidence to fill them).`);
3816
+ lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
3817
+ } else {
3818
+ lines.push("Every section was filled from your project and your existing CLAUDE.md; nothing is left as a placeholder.");
3819
+ lines.push("Review it (the notes below say what changed), then apply it.");
3820
+ }
3673
3821
  lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
3674
3822
  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.");
3675
3823
  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.");
@@ -4001,7 +4149,7 @@ function parseBadgeFlags(args) {
4001
4149
  };
4002
4150
  }
4003
4151
  function cliVersion() {
4004
- return true ? "0.5.2" : "0.0.0-dev";
4152
+ return true ? "0.5.4" : "0.0.0-dev";
4005
4153
  }
4006
4154
  function helpText() {
4007
4155
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
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": {