costclaw 0.13.0 → 0.13.2

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 +160 -94
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2816,37 +2816,8 @@ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy)
2816
2816
  function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
2817
2817
  const { currentClaudeMd, project } = input;
2818
2818
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
2819
- 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.";
2820
2819
  const parts = [];
2821
- parts.push(
2822
- [
2823
- "<!--",
2824
- " CLAUDE.md scaffold generated by CostClaw (https://costclaw.io).",
2825
- "",
2826
- " How to use this file:",
2827
- " - Replace every placeholder comment with your project's real details, then",
2828
- " delete any line that does not earn its place.",
2829
- ' - Keep it lean, but do not cut to a line count. For each line ask "would',
2830
- ' removing this make the agent make a mistake?" If not, cut it.',
2831
- " - Only include what the agent cannot infer from the code: commands it cannot",
2832
- " guess, conventions that differ from the language defaults, and non-obvious",
2833
- " gotchas. Skip anything self-evident.",
2834
- "",
2835
- " Why this matters for cost:",
2836
- " - Claude Code reads CLAUDE.md once at the start of a session and re-reads it",
2837
- " from the prompt cache on every later turn at roughly a tenth of the input",
2838
- " price. A small, stable file is cheap to cache and reuse; a bloated, churny",
2839
- " one inflates every turn.",
2840
- " - Keep volatile content (dates, TODOs, status notes, version numbers) out of",
2841
- " this file. Put churn in a scratch note the agent opens on demand, or a",
2842
- " path-scoped rule under .claude/rules/.",
2843
- recoverableLine,
2844
- " - Things that must happen every time (lint before commit, blocking a path)",
2845
- " belong in a hook, not here: CLAUDE.md is context the agent usually follows,",
2846
- " not an enforced rule.",
2847
- "-->"
2848
- ].join("\n")
2849
- );
2820
+ parts.push("<!-- Generated by CostClaw. Why each section is here: .claude/costclaw/PLAYBOOK.md -->");
2850
2821
  const filled = [];
2851
2822
  const projectName = project?.name?.trim() || null;
2852
2823
  const titleText = projectName ?? title ?? "Project name";
@@ -3313,6 +3284,15 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
3313
3284
  );
3314
3285
  const receipt = claudeMdReceiptLine(claudeMdTokens);
3315
3286
  if (receipt) parts.push(receipt);
3287
+ parts.push([
3288
+ "## How to keep this file lean",
3289
+ "",
3290
+ '- Cut by question, not by line count. For each line ask "would removing this make the agent make a mistake?" If not, cut it.',
3291
+ "- Only keep what the agent cannot infer from the code: commands it could not guess, conventions that differ from the language defaults, and non-obvious gotchas.",
3292
+ "- Keep volatile content out. Dates, TODOs, status notes and version numbers change between sessions and reset the cached prefix, so the next session re-pays for the whole file.",
3293
+ "- Things that must happen every time (lint before commit, blocking a path) belong in a hook. CLAUDE.md is context the agent usually follows, not an enforced rule.",
3294
+ recoverable >= 1 ? `- Your audit put ${usd(recoverable)} of recoverable waste in reach. A small, stable file is part of that; the ranked fixes below are the rest.` : "- A small, stable file keeps the cached prefix cheap to reuse on every later turn."
3295
+ ].join("\n"));
3316
3296
  dollarFixes.forEach((fix, i) => {
3317
3297
  parts.push(renderDollarFix(fix, i + 1));
3318
3298
  if (fix.id === "cache_recovery") {
@@ -4454,6 +4434,11 @@ function repoRootFor(startDir) {
4454
4434
  } catch {
4455
4435
  return null;
4456
4436
  }
4437
+ try {
4438
+ if (!statSync(dir).isDirectory()) return null;
4439
+ } catch {
4440
+ return null;
4441
+ }
4457
4442
  for (let depth = 0; depth < 64; depth += 1) {
4458
4443
  const dotGit = join(dir, ".git");
4459
4444
  let stat4;
@@ -6234,6 +6219,14 @@ function renderSideBySideTab(before, after, tokens) {
6234
6219
  function renderComparisonTabs(input) {
6235
6220
  return `<div class="tabs"><input type="radio" name="cmp" id="t-sections" checked><label for="t-sections">By section</label><input type="radio" name="cmp" id="t-diff"><label for="t-diff">Line changes</label><input type="radio" name="cmp" id="t-side"><label for="t-side">Side by side</label><div class="tabpane" data-for="t-sections">${renderSectionsTable(input.sectionDispositions)}</div><div class="tabpane" data-for="t-diff">${renderDiffTab(input.currentClaudeMd, input.optimizedClaudeMd)}</div><div class="tabpane" data-for="t-side">${renderSideBySideTab(input.currentClaudeMd, input.optimizedClaudeMd, input.claudeMdTokens)}</div></div>`;
6236
6221
  }
6222
+ function renderComparisonSection(input) {
6223
+ const tabs = renderComparisonTabs(input);
6224
+ if (!input.review) return `<div class="panel">${tabs}</div>`;
6225
+ const after = countLines(input.optimizedClaudeMd);
6226
+ const before = input.currentClaudeMd === null ? null : countLines(input.currentClaudeMd);
6227
+ const size = before === null ? `${num5(after)} ${plural2(after, "line")}` : `${num5(before)} ${plural2(before, "line")} to ${num5(after)}`;
6228
+ return `<div class="panel"><details class="filedrop"><summary>Show the full before and after (${size})</summary>${tabs}</details></div>`;
6229
+ }
6237
6230
  function countLines(s) {
6238
6231
  return s.length === 0 ? 0 : s.split("\n").length;
6239
6232
  }
@@ -6404,11 +6397,12 @@ ${renderHeader(input)}
6404
6397
  <h2>What this run changed<span class="n">the receipt</span></h2>
6405
6398
  ${renderReceipt(input)}
6406
6399
 
6407
- <h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
6408
- <div class="panel">${renderComparisonTabs(input)}</div>
6409
6400
  ${input.review ? `
6410
6401
  <h2>What to change in your CLAUDE.md<span class="n">${num5(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
6411
- <div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
6402
+ <div class="panel">${renderAnnotatedFile(input.review)}</div>
6403
+ ` : ""}
6404
+ <h2>Your CLAUDE.md, before and after<span class="n">${input.review ? "the evidence behind that list" : "what actually changed"}</span></h2>
6405
+ ${renderComparisonSection(input)}
6412
6406
 
6413
6407
  <h2>Fixes, ranked by what they recover</h2>
6414
6408
  ${renderFixes(input.fixes, input.report)}
@@ -6448,6 +6442,23 @@ pre.review .skip{color:var(--ink2);font-style:italic}
6448
6442
  .legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
6449
6443
  .taglegend{list-style:none;padding:0;margin:0 0 12px;display:flex;flex-wrap:wrap;gap:6px 16px;font-size:.78rem;color:var(--ink2)}
6450
6444
  .taglegend li{display:flex;align-items:center;gap:6px}
6445
+ .paths{display:grid;gap:14px;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));margin:0 0 10px}
6446
+ .path{position:relative;border:1px solid var(--line);border-radius:12px;padding:18px 18px 16px;background:var(--panel)}
6447
+ .path.best{border-color:var(--accent);border-width:2px}
6448
+ .path h3{margin:0 0 6px;font-size:1rem}
6449
+ .path p{margin:0 0 10px;font-size:.88rem;line-height:1.5}
6450
+ .path .badge{position:absolute;top:-10px;left:16px;background:var(--accent);color:#fff;font-size:.68rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;padding:2px 9px;border-radius:99px}
6451
+ .path .cmd{display:block;margin-top:8px}
6452
+ .path textarea.prompt{margin-top:10px}
6453
+ .oneclick{margin:0 0 18px}
6454
+ .acts button.big{font-size:1rem;font-weight:650;padding:11px 22px}
6455
+ .path .opt{display:flex;align-items:flex-start;gap:8px;margin-top:12px;font-size:.84rem;color:var(--ink2);line-height:1.4}
6456
+ .path .opt input{margin-top:2px}
6457
+ th.pick,td.pick{width:1%;text-align:center;padding-right:0}
6458
+ .changed .chg{padding:10px 0;border-bottom:1px solid var(--line)}
6459
+ .changed .chg:last-of-type{border-bottom:0}
6460
+ .changed .chg b{font-size:.92rem}
6461
+ .changed .chg ul{margin:6px 0 0;padding-left:20px;font-size:.84rem;color:var(--ink2);line-height:1.5}
6451
6462
  .changes{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:10px}
6452
6463
  .changes li{line-height:1.45}
6453
6464
  .ch-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px}
@@ -6571,43 +6582,24 @@ function indexTokens(tokens) {
6571
6582
  if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
6572
6583
  return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
6573
6584
  }
6574
- function indexStatus(appliedAt) {
6585
+ function indexStatus(appliedAt, mode) {
6575
6586
  if (!appliedAt) return `<span class="state off">not applied</span>`;
6576
- return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
6587
+ const what = mode === "settings" ? " + permissions" : mode === "include" ? ", no permissions" : "";
6588
+ return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}${esc(what)}</span>`;
6577
6589
  }
6578
- function actionForm(token, slug, action, label, primary, hint = "") {
6579
- return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}${hint ? ` title="${esc(hint)}"` : ""}>${esc(label)}</button></form>`;
6590
+ function applyButtons(slug) {
6591
+ return `<div class="acts"><button type="submit" name="action" value="include:${esc(slug)}" class="go" title="Writes .claude/costclaw.md, adds one import line to this project's CLAUDE.md, and copies the playbook and work order into .claude/costclaw/.">Apply</button><button type="submit" name="action" value="settings:${esc(slug)}" title="Everything Apply does, and also merges the suggested permission allowlist into this project's settings, backing up the original first.">Apply + permissions</button><button type="submit" name="action" value="remove:${esc(slug)}" title="Removes the costclaw include and the import line.">Undo</button></div>`;
6580
6592
  }
6581
6593
  function indexActions(row, serve) {
6582
6594
  const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
6583
6595
  if (!serve) {
6584
6596
  return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
6585
6597
  }
6586
- return `<div class="acts">` + actionForm(
6587
- serve.token,
6588
- row.slug,
6589
- "include",
6590
- "Apply CLAUDE.md",
6591
- true,
6592
- "Writes .claude/costclaw.md and adds one import line to this project's CLAUDE.md. Every line you wrote stays."
6593
- ) + actionForm(
6594
- serve.token,
6595
- row.slug,
6596
- "settings",
6597
- "Apply permissions",
6598
- false,
6599
- "Merges the suggested permission allowlist into this project's settings file. Nothing is removed."
6600
- ) + actionForm(
6601
- serve.token,
6602
- row.slug,
6603
- "remove",
6604
- "Undo",
6605
- false,
6606
- "Removes the costclaw include and the import line this page added."
6607
- ) + `</div><p class="note" style="margin-top:6px"><strong>Apply CLAUDE.md</strong> writes <span class="mono">.claude/costclaw.md</span> and one import line. <strong>Apply permissions</strong> merges the allowlist into your settings file. They are independent, both are additive, and <strong>Undo</strong> reverses the first. ${details}</p>`;
6608
- }
6609
- function renderPromptPanel(review) {
6610
- return `<div class="panel"><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="14" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run the line below. It covers your global CLAUDE.md and every project on this page, so there is one prompt, not one per project.</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code><p class="note">costclaw never calls a model: this work order is deterministic text built from your own audit. Your agent does the editing, with your approval.</p></div>`;
6598
+ return applyButtons(row.slug) + `<p class="note" style="margin-top:6px"><b>Apply</b> writes <span class="mono">.claude/costclaw.md</span>, adds one <span class="mono">@.claude/costclaw.md</span> line to this project's CLAUDE.md, and copies the playbook and work order into <span class="mono">.claude/costclaw/</span>. Every line you wrote stays. <b>Apply + permissions</b> does all of that <em>and</em> merges the suggested allowlist into this project's settings, so it is the same button plus one step. ${details}</p>`;
6599
+ }
6600
+ function renderStartHere(review, projectCount) {
6601
+ const covers = projectCount === 1 ? "your global CLAUDE.md and this project" : `your global CLAUDE.md and all ${num5(projectCount)} projects`;
6602
+ return `<div class="paths"><div class="path best"><span class="badge">Recommended</span><h3>Hand it to your own Claude</h3><p>It knows your project and costclaw does not. It opens each file, makes the changes, and asks you before writing anything. One paste covers ${esc(covers)}.</p><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="8" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run:</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code></div><div class="path"><h3>Or let costclaw write the files</h3><p>No model involved, so it only does the part that needs no judgement: a generated include file plus one import line per project. It never edits a line you wrote.</p><p class="note">Use the Apply buttons on the project rows below. Start with the top row: that is where the money is.</p></div></div><p class="note">costclaw never calls a model. The prompt above is deterministic text built from your own audit, so nothing here has been through an LLM.</p>`;
6611
6603
  }
6612
6604
  function renderGlobalPanel(review) {
6613
6605
  const t = review.tokens;
@@ -6631,9 +6623,19 @@ function renderOptimizeIndex(input) {
6631
6623
  const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
6632
6624
  const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
6633
6625
  const rows = input.rows.map(
6634
- (r) => `<tr><td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt)}</td><td>${indexActions(r, input.serve)}</td></tr>`
6626
+ (r) => `<tr>` + (input.serve ? `<td class="pick"><input type="checkbox" name="slug" value="${esc(r.slug)}" checked aria-label="Include ${esc(r.slug)}"></td>` : "") + `<td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt, r.appliedMode)}</td><td>${indexActions(r, input.serve)}</td></tr>`
6635
6627
  ).join("");
6636
- const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">Valuation estimate</th><th class="num">Cache-miss exposure estimate</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
6628
+ const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr>` + (input.serve ? `<th class="pick" title="Uncheck a project to leave it out of Apply everything">Include</th>` : "") + `<th>Project</th><th class="num">Valuation estimate</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
6629
+ const serve = input.serve;
6630
+ const applied = input.rows.filter((r) => r.appliedAt).length;
6631
+ const priorRun = serve?.lastRun;
6632
+ const oneButton = serve ? `<div class="path best oneclick"><span class="badge">One click</span><h3>Apply everything</h3><p>Writes the generated include and one import line into ${num5(input.rows.length)} ${plural2(input.rows.length, "project")}. It never edits a line you wrote, and the Revert button puts it all back.</p><div class="acts"><button type="submit" name="action" value="apply-all" class="go big">Apply everything</button>` + // Only one Revert on the page: the What changed panel owns it right after
6633
+ // a run, and this card carries it when a previous session left files behind.
6634
+ (applied > 0 && !priorRun ? `<button type="submit" name="action" value="revert-all">Revert everything</button>` : "") + `</div><label class="opt"><input type="checkbox" name="settings" value="1" checked> also merge the suggested permission allowlist (backs up your settings first)</label><p class="note">Uncheck any project in the table below to leave it out.</p></div>` : "";
6635
+ const run = priorRun;
6636
+ const changed = run ? `<h2>What changed<span class="n">${run.reverted ? "reverted" : "written just now"}</span></h2><div class="panel changed">` + run.changes.map(
6637
+ (c) => `<div class="chg"><b>${esc(c.slug)}</b><ul>` + c.lines.map((l) => `<li>${esc(l)}</li>`).join("") + `</ul></div>`
6638
+ ).join("") + (run.reverted ? `<p class="note">Everything costclaw added has been removed.</p>` : `<div class="acts" style="margin-top:12px"><button type="submit" name="action" value="revert-all" class="go">Revert everything</button></div><p class="note">Reverts every project checked in the table below.</p>`) + `</div>` : "";
6637
6639
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
6638
6640
  const done = input.serve ? `<div class="acts" style="margin:0 0 22px"><form method="post" action="/done"><input type="hidden" name="token" value="${esc(input.serve.token)}"><button type="submit">Done</button></form></div>` : "";
6639
6641
  const how = input.serve ? `<p class="note">Apply writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md. Every line you wrote stays where it is. Remove undoes both.</p>` : `<p class="note">Run the line on a project's row to apply it. It writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md; every line you wrote stays where it is. Undo with <code>--remove</code>.</p>`;
@@ -6650,20 +6652,25 @@ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
6650
6652
  <div class="wrap">
6651
6653
  <header><p class="kicker">CostClaw optimize &middot; generated locally &middot; nothing left your machine</p>
6652
6654
  <h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
6653
- <p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation &middot; ${esc(usd5(recoverable))} cache-miss exposure estimate &middot;
6655
+ <p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation &middot; ${esc(usd5(recoverable))} recoverable &middot;
6654
6656
  artifacts in ${esc(input.root)}/</p></header>
6655
6657
 
6656
6658
  ${banner}${done}
6657
- ${input.review ? `<h2>Your upgrade prompt<span class="n">one paste applies all of it</span></h2>
6658
- ${renderPromptPanel(input.review)}
6659
-
6660
- <h2>Global CLAUDE.md<span class="n">loaded on every turn of every project</span></h2>
6661
- ${renderGlobalPanel(input.review.global)}` : ""}
6659
+ ${serve ? `<form method="post" action="/apply">
6660
+ <input type="hidden" name="token" value="${esc(serve.token)}">` : ""}
6661
+ ${changed}
6662
+ ${oneButton}
6663
+ ${input.review ? `<h2>${serve ? "Or hand it to your own Claude" : "Start here"}<span class="n">${serve ? "it knows your project" : "two ways to do this, pick one"}</span></h2>
6664
+ ${renderStartHere(input.review, input.rows.length)}` : ""}
6662
6665
 
6663
6666
  <h2>Your projects<span class="n">ranked by spend</span></h2>
6664
6667
  ${body}
6665
6668
  ${how}
6666
- ${input.review ? renderProjectPanels(input, input.review) : ""}
6669
+ ${serve ? `</form>` : ""}
6670
+ ${input.review ? `<h2>What the prompt will change<span class="n">the evidence behind it</span></h2>
6671
+ <h3>Global CLAUDE.md<span class="n">loaded on every turn of every project</span></h3>
6672
+ ${renderGlobalPanel(input.review.global)}
6673
+ ${renderProjectPanels(input, input.review)}` : ""}
6667
6674
 
6668
6675
  <footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
6669
6676
  Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
@@ -7229,6 +7236,19 @@ function safeArtifactPath(root, urlPath) {
7229
7236
  if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
7230
7237
  return full;
7231
7238
  }
7239
+ function parseFormMulti(body) {
7240
+ const out = {};
7241
+ for (const pair of body.split("&")) {
7242
+ if (pair === "") continue;
7243
+ const eq = pair.indexOf("=");
7244
+ const rawKey = eq < 0 ? pair : pair.slice(0, eq);
7245
+ const rawValue = eq < 0 ? "" : pair.slice(eq + 1);
7246
+ const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
7247
+ const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
7248
+ (out[key] ??= []).push(value);
7249
+ }
7250
+ return out;
7251
+ }
7232
7252
  function rowsFromManifest(manifest) {
7233
7253
  return manifest.projects.map((e) => ({
7234
7254
  slug: e.slug,
@@ -7238,6 +7258,7 @@ function rowsFromManifest(manifest) {
7238
7258
  recoverableUsd: e.recoverableUsd,
7239
7259
  tokens: e.tokens,
7240
7260
  ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
7261
+ ...e.appliedMode ? { appliedMode: e.appliedMode } : {},
7241
7262
  applyCommand: `costclaw apply ${e.projectDir}`
7242
7263
  }));
7243
7264
  }
@@ -7276,6 +7297,7 @@ async function startApplyServer(opts) {
7276
7297
  const token = randomBytes(16).toString("hex");
7277
7298
  const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
7278
7299
  const manifest = opts.manifest;
7300
+ let lastRun = null;
7279
7301
  let closedAlready = false;
7280
7302
  let resolveClosed;
7281
7303
  const closedPromise = new Promise((res) => {
@@ -7303,7 +7325,11 @@ async function startApplyServer(opts) {
7303
7325
  generatedAt: manifest.generatedAt,
7304
7326
  root: opts.root,
7305
7327
  rows: rowsFromManifest(manifest),
7306
- serve: { token, ...msg ? { message: msg } : {} }
7328
+ serve: {
7329
+ token,
7330
+ ...msg ? { message: msg } : {},
7331
+ ...lastRun ? { lastRun } : {}
7332
+ }
7307
7333
  });
7308
7334
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
7309
7335
  res.end(html);
@@ -7316,31 +7342,69 @@ async function startApplyServer(opts) {
7316
7342
  sendText(res, 400, "Payload too large");
7317
7343
  return;
7318
7344
  }
7319
- const form = parseForm(body);
7320
- if (form["token"] !== token) {
7345
+ const form = parseFormMulti(body);
7346
+ if (form["token"]?.[0] !== token) {
7321
7347
  sendText(res, 403, "Forbidden");
7322
7348
  return;
7323
7349
  }
7324
- const action = form["action"];
7325
- if (!isApplyAction(action)) {
7326
- sendText(res, 400, "Unknown action");
7327
- return;
7328
- }
7329
- const entry = manifest.projects.find((p) => p.slug === form["slug"]);
7330
- if (!entry) {
7331
- sendText(res, 400, "Unknown project");
7332
- return;
7350
+ const raw = form["action"]?.[0] ?? "";
7351
+ const bulk = raw === "apply-all" || raw === "revert-all";
7352
+ const withSettings = (form["settings"]?.[0] ?? "") !== "";
7353
+ const targets = [];
7354
+ if (bulk) {
7355
+ const picked = new Set(form["slug"] ?? []);
7356
+ for (const entry of manifest.projects) {
7357
+ if (!picked.has(entry.slug)) continue;
7358
+ if (raw === "revert-all") {
7359
+ if (entry.appliedAt) targets.push({ entry, action: "remove" });
7360
+ } else {
7361
+ targets.push({ entry, action: withSettings ? "settings" : "include" });
7362
+ }
7363
+ }
7364
+ if (targets.length === 0) {
7365
+ res.writeHead(303, { Location: `/?msg=${encodeURIComponent("Nothing selected.")}` });
7366
+ res.end();
7367
+ return;
7368
+ }
7369
+ } else {
7370
+ const sep3 = raw.indexOf(":");
7371
+ const verb2 = sep3 < 0 ? raw : raw.slice(0, sep3);
7372
+ const slug = sep3 < 0 ? form["slug"]?.[0] ?? "" : raw.slice(sep3 + 1);
7373
+ if (!isApplyAction(verb2)) {
7374
+ sendText(res, 400, "Unknown action");
7375
+ return;
7376
+ }
7377
+ const entry = manifest.projects.find((p) => p.slug === slug);
7378
+ if (!entry) {
7379
+ sendText(res, 400, "Unknown project");
7380
+ return;
7381
+ }
7382
+ targets.push({ entry, action: verb2 });
7333
7383
  }
7334
- let msg;
7335
- try {
7336
- const lines = await opts.apply(entry, action);
7337
- if (action === "remove") delete entry.appliedAt;
7338
- else entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7339
- if (opts.onManifestChange) await opts.onManifestChange(manifest);
7340
- msg = lines[0] ?? "Done.";
7341
- } catch (err) {
7342
- msg = `Error: ${err instanceof Error ? err.message : String(err)}`;
7384
+ const changes = [];
7385
+ const errors = [];
7386
+ for (const { entry, action } of targets) {
7387
+ try {
7388
+ const lines = await opts.apply(entry, action);
7389
+ if (action === "remove") {
7390
+ delete entry.appliedAt;
7391
+ delete entry.appliedMode;
7392
+ } else {
7393
+ entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7394
+ entry.appliedMode = action;
7395
+ }
7396
+ changes.push({ slug: entry.slug, lines });
7397
+ } catch (err) {
7398
+ const text2 = `Error: ${err instanceof Error ? err.message : String(err)}`;
7399
+ errors.push(text2);
7400
+ changes.push({ slug: entry.slug, lines: [text2] });
7401
+ }
7343
7402
  }
7403
+ if (opts.onManifestChange) await opts.onManifestChange(manifest);
7404
+ lastRun = { reverted: targets[0]?.action === "remove", changes };
7405
+ const ok = targets.length - errors.length;
7406
+ const verb = lastRun.reverted ? "Reverted" : "Applied";
7407
+ const msg = errors.length === targets.length ? errors[0] : errors.length > 0 ? `${verb} ${ok} of ${targets.length}. ${errors[0]}` : `${verb} ${ok} ${ok === 1 ? "project" : "projects"}.`;
7344
7408
  res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg)}` });
7345
7409
  res.end();
7346
7410
  }
@@ -7753,7 +7817,8 @@ async function runOptimize(opts) {
7753
7817
  const previous = await readManifest(manifestRoot);
7754
7818
  const merged = entries.map((e) => {
7755
7819
  const old = previous ? findEntry(previous, e.projectDir) : void 0;
7756
- return old?.appliedAt ? { ...e, appliedAt: old.appliedAt } : e;
7820
+ if (!old?.appliedAt) return e;
7821
+ return { ...e, appliedAt: old.appliedAt, ...old.appliedMode ? { appliedMode: old.appliedMode } : {} };
7757
7822
  });
7758
7823
  if (single && previous) {
7759
7824
  const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
@@ -7801,6 +7866,7 @@ async function runOptimize(opts) {
7801
7866
  recoverableUsd: e.recoverableUsd,
7802
7867
  tokens: e.tokens,
7803
7868
  ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
7869
+ ...e.appliedMode ? { appliedMode: e.appliedMode } : {},
7804
7870
  applyCommand: `costclaw apply ${e.projectDir}`
7805
7871
  }));
7806
7872
  const html = renderOptimizeIndex({
@@ -8110,7 +8176,7 @@ function parseApplyFlags(args) {
8110
8176
  };
8111
8177
  }
8112
8178
  function cliVersion() {
8113
- return true ? "0.13.0" : "0.0.0-dev";
8179
+ return true ? "0.13.2" : "0.0.0-dev";
8114
8180
  }
8115
8181
  function isHelpRequest(command, args) {
8116
8182
  if (command === void 0) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "description": "Local Claude Code usage estimates, cache analysis, and rule-based setup checks. Your prompts stay on your machine.",
5
5
  "type": "module",
6
6
  "bin": {