bugzero 0.0.60 → 0.0.61

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 (3) hide show
  1. package/README.md +7 -2
  2. package/dist/index.js +185 -29
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -230,6 +230,8 @@ The whole proposed fix is shown at once, because a fix that spans several files
230
230
 
231
231
  **Failing tests are re-run on their own first.** While tests are what is failing, BugZero re-runs only the test files that failed after each attempt, which is much quicker than the whole pipeline on a big project. Once those files pass it runs the full build, lint and tests, so a fix is never called done on a partial check. This works for projects whose `test` script runs Jest or Vitest as one plain command (for example `vitest run` or `jest --ci`); for any other script, or when no failing test file can be found in the output, the full pipeline runs as before. Turn it off with `--no-focus-tests` or `"focusTests": false` in `.bugzerorc`.
232
232
 
233
+ **Token budget.** `--max-tokens <n>` (or `"maxTokens"` in `.bugzerorc`) limits the AI tokens one `rescue` run may use, fix attempts and the report together; there is no limit unless you set one. Before each request BugZero estimates the prompt (about 4 characters per token) and caps the reply to what is left, up to 8192 tokens. If less than 500 tokens would remain for a reply, the request is not made: the run stops and says so, and the report is written from the raw results without the AI. Because the prompt is only estimated, a run can finish somewhat above the number you give, so treat it as a guard against runaway cost rather than an exact cap. A model that does not report its token usage is counted by the same estimate, and BugZero says when the total includes estimates. `0` means no limit. `hunt` is not covered; use `--no-ai-report` there.
234
+
233
235
  <details>
234
236
  <summary><strong>Options for <code>rescue</code></strong></summary>
235
237
 
@@ -239,6 +241,7 @@ The whole proposed fix is shown at once, because a fix that spans several files
239
241
  | `--max-attempts <n>` | `-n` | `3` | Maximum AI fix iterations before giving up |
240
242
  | `--timeout <seconds>` | `-t` | none | Stop any build, lint, or test command that runs longer than this many seconds |
241
243
  | `--patience <n>` | | `2` | Stop early after this many attempts in a row make no progress. `0` turns it off |
244
+ | `--max-tokens <n>` | | none | Limit the AI tokens the run may use, the report included. `0` means no limit |
242
245
  | `--no-focus-tests` | | off | Always run the full build, lint and tests, instead of re-running only the failing test files between attempts |
243
246
  | `--dry-run` | | `false` | Analyze only — no files will be written |
244
247
  | `--approve` | | `false` | Show each proposed fix as a diff and ask before writing it. Needs an interactive terminal |
@@ -291,7 +294,7 @@ bugzero hunt --json | jq '.steps'
291
294
  bugzero rescue --json --dry-run | jq -r '.outcome'
292
295
  ```
293
296
 
294
- `hunt` reports each step (`build`, `lint`, `test`) as `passed`, `failed`, or `skipped`; failed steps include the command's output and whether it timed out. `rescue` reports an `outcome` of `already-passing`, `fixed`, `failed`, or `dry-run`, along with the model, token usage, and the files and root cause of any fix. Both include the path to the generated report. If a run can't start at all (for example, because of an invalid option), stdout is `{ "success": false, "error": "..." }`.
297
+ `hunt` reports each step (`build`, `lint`, `test`) as `passed`, `failed`, or `skipped`; failed steps include the command's output and whether it timed out. `rescue` reports an `outcome` of `already-passing`, `fixed`, `failed`, or `dry-run`, along with the model, token usage, and the files and root cause of any fix. `tokenBudget` (`limit`, `used`, `estimated`) is set when a budget was given, and `stoppedEarly` is `no-progress` or `token-budget` when a run stopped before using all its attempts; both are `null` otherwise. Both include the path to the generated report. If a run can't start at all (for example, because of an invalid option), stdout is `{ "success": false, "error": "..." }`.
295
298
 
296
299
  ---
297
300
 
@@ -319,7 +322,8 @@ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick
319
322
  "protect": ["config/prod.json", "migrations/**"],
320
323
  "allow": [".env.example"],
321
324
  "patience": 2,
322
- "focusTests": true
325
+ "focusTests": true,
326
+ "maxTokens": 100000
323
327
  }
324
328
  ```
325
329
 
@@ -330,6 +334,7 @@ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick
330
334
  | `allow` | Files from the built-in list that BugZero may edit and read after all, such as `.env.example`. A `protect` pattern still wins. |
331
335
  | `patience` | How many attempts in a row may make no progress before `rescue` stops early. Default 2, `0` turns it off. `--patience` overrides it. |
332
336
  | `focusTests` | Set to `false` to always run the full pipeline, instead of re-running only the failing test files between attempts. Default `true`. `--no-focus-tests` overrides it. |
337
+ | `maxTokens` | The most AI tokens a `rescue` run may use, the report included. Not set or `0` means no limit. `--max-tokens` overrides it. |
333
338
 
334
339
  Patterns are relative to the project and ignore case. `*` matches within a folder, `**` matches across folders, `?` matches one character, and a trailing `/` means a folder and everything in it. A pattern with no `/` matches that name at any depth, so `.env.*` also covers `apps/web/.env.local`; a pattern with a `/` is anchored to the project root. All keys are optional.
335
340
 
package/dist/index.js CHANGED
@@ -499,7 +499,12 @@ var require_dist2 = __commonJS({
499
499
  __export(index_exports, {
500
500
  DEFAULT_PROTECTED_PATTERNS: () => DEFAULT_PROTECTED_PATTERNS,
501
501
  DEFAULT_SECRET_PATTERNS: () => DEFAULT_SECRET_PATTERNS,
502
+ MAX_REPLY_TOKENS: () => MAX_REPLY_TOKENS,
503
+ MIN_REPLY_TOKENS: () => MIN_REPLY_TOKENS,
504
+ checkBudget: () => checkBudget,
505
+ countCallTokens: () => countCallTokens,
502
506
  createProtectedPathRules: () => createProtectedPathRules2,
507
+ estimateTokens: () => estimateTokens,
503
508
  isInsideDirectory: () => isInsideDirectory,
504
509
  isLexicallyInside: () => isLexicallyInside,
505
510
  projectRelativePaths: () => projectRelativePaths,
@@ -658,6 +663,39 @@ var require_dist2 = __commonJS({
658
663
  }
659
664
  return paths;
660
665
  }
666
+ var CHARS_PER_TOKEN = 4;
667
+ var MIN_REPLY_TOKENS = 500;
668
+ var MAX_REPLY_TOKENS = 8192;
669
+ function estimateTokens(text) {
670
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
671
+ }
672
+ function checkBudget(limit, used, prompt) {
673
+ if (limit === void 0) return { allowed: true, maxReplyTokens: void 0 };
674
+ const promptTokens = estimateTokens(prompt);
675
+ const left = limit - used - promptTokens;
676
+ if (left < MIN_REPLY_TOKENS) {
677
+ return {
678
+ allowed: false,
679
+ reason: `The token budget of ${limit} does not leave enough for the next AI request (${used} already used, the prompt is about ${promptTokens} tokens, and a reply needs at least ${MIN_REPLY_TOKENS}).`
680
+ };
681
+ }
682
+ return { allowed: true, maxReplyTokens: Math.min(left, MAX_REPLY_TOKENS) };
683
+ }
684
+ function reported(value) {
685
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
686
+ }
687
+ function countCallTokens(limit, prompt, reply) {
688
+ const promptTokens = reply.usage?.prompt_tokens;
689
+ const completionTokens = reply.usage?.completion_tokens;
690
+ if (limit === void 0) {
691
+ return { promptTokens: promptTokens ?? 0, completionTokens: completionTokens ?? 0, estimated: false };
692
+ }
693
+ return {
694
+ promptTokens: reported(promptTokens) ? promptTokens : estimateTokens(prompt),
695
+ completionTokens: reported(completionTokens) ? completionTokens : estimateTokens(reply.content),
696
+ estimated: !reported(promptTokens) || !reported(completionTokens)
697
+ };
698
+ }
661
699
  }
662
700
  });
663
701
 
@@ -1682,7 +1720,8 @@ var require_dist5 = __commonJS({
1682
1720
  role: "user",
1683
1721
  content: prompt
1684
1722
  }
1685
- ]
1723
+ ],
1724
+ ...options?.maxTokens !== void 0 ? { max_tokens: options.maxTokens } : {}
1686
1725
  },
1687
1726
  {
1688
1727
  headers: {
@@ -1694,10 +1733,12 @@ var require_dist5 = __commonJS({
1694
1733
  if (response.data?.error) {
1695
1734
  throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1696
1735
  }
1736
+ const choice = response.data.choices[0];
1697
1737
  return {
1698
- content: response.data.choices[0].message.content,
1738
+ content: choice.message.content ?? "",
1699
1739
  model,
1700
- usage: response.data.usage
1740
+ usage: response.data.usage,
1741
+ ...choice.finish_reason === "length" ? { truncated: true } : {}
1701
1742
  };
1702
1743
  } catch (error) {
1703
1744
  let msg = error.message;
@@ -2111,6 +2152,21 @@ var require_dist7 = __commonJS({
2111
2152
  reducer: (_, value) => value,
2112
2153
  default: () => false
2113
2154
  }),
2155
+ /** The most AI tokens the run may use (undefined = no limit) */
2156
+ maxTokens: (0, import_langgraph.Annotation)({
2157
+ reducer: (_, value) => value,
2158
+ default: () => void 0
2159
+ }),
2160
+ /** True once any token count is an estimate because the model did not report it */
2161
+ tokensEstimated: (0, import_langgraph.Annotation)({
2162
+ reducer: (previous, estimated) => previous || estimated,
2163
+ default: () => false
2164
+ }),
2165
+ /** Why the run stopped for lack of token budget, or null when it did not */
2166
+ budgetStop: (0, import_langgraph.Annotation)({
2167
+ reducer: (_, value) => value,
2168
+ default: () => null
2169
+ }),
2114
2170
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
2115
2171
  timeoutMs: (0, import_langgraph.Annotation)({
2116
2172
  reducer: (_, value) => value,
@@ -2166,13 +2222,27 @@ var require_dist7 = __commonJS({
2166
2222
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
2167
2223
  }
2168
2224
  async function analyzeNode(state) {
2225
+ const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2226
+ const used = state.promptTokens + state.completionTokens;
2227
+ const budget = (0, import_shared4.checkBudget)(state.maxTokens, used, prompt);
2228
+ if (!budget.allowed) {
2229
+ console.log(`
2230
+ [BugZero] ${budget.reason} Stopping before attempt ${state.attempts + 1}.`);
2231
+ return { budgetStop: budget.reason };
2232
+ }
2169
2233
  console.log(
2170
2234
  `
2171
2235
  [BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
2172
2236
  );
2173
- const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2174
- const result = await provider.invoke(prompt, { cwd: state.cwd });
2237
+ const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
2175
2238
  const response = result.content;
2239
+ const tokens = (0, import_shared4.countCallTokens)(state.maxTokens, prompt, result);
2240
+ if (state.maxTokens !== void 0) {
2241
+ const total = used + tokens.promptTokens + tokens.completionTokens;
2242
+ const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
2243
+ console.log(`[BugZero] Token budget: ${total} of ${state.maxTokens} used${note}.`);
2244
+ if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
2245
+ }
2176
2246
  let fixSuggestion = null;
2177
2247
  try {
2178
2248
  const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
@@ -2195,8 +2265,9 @@ var require_dist7 = __commonJS({
2195
2265
  fixSuggestion,
2196
2266
  attempts: state.attempts + 1,
2197
2267
  modelUsed: result.model,
2198
- promptTokens: result.usage?.prompt_tokens ?? 0,
2199
- completionTokens: result.usage?.completion_tokens ?? 0
2268
+ promptTokens: tokens.promptTokens,
2269
+ completionTokens: tokens.completionTokens,
2270
+ tokensEstimated: tokens.estimated
2200
2271
  };
2201
2272
  }
2202
2273
  function patchFailure(state, error) {
@@ -2315,7 +2386,10 @@ Any other files from that same suggestion were rolled back to keep the change at
2315
2386
  }
2316
2387
  return "analyze";
2317
2388
  }
2318
- var workflow = new import_langgraph2.StateGraph(GraphState).addNode("analyze", analyzeNode).addNode("apply_fix", applyFixNode).addNode("verify", verifyNode).addEdge(import_langgraph2.START, "analyze").addEdge("analyze", "apply_fix").addEdge("apply_fix", "verify").addConditionalEdges("verify", shouldRetry).compile();
2389
+ function afterAnalyze(state) {
2390
+ return state.budgetStop ? import_langgraph2.END : "apply_fix";
2391
+ }
2392
+ var workflow = new import_langgraph2.StateGraph(GraphState).addNode("analyze", analyzeNode).addNode("apply_fix", applyFixNode).addNode("verify", verifyNode).addEdge(import_langgraph2.START, "analyze").addConditionalEdges("analyze", afterAnalyze).addEdge("apply_fix", "verify").addConditionalEdges("verify", shouldRetry).compile();
2319
2393
  function runRepairWorkflow(input) {
2320
2394
  const { initialStep, ...rest } = input;
2321
2395
  return workflow.invoke(
@@ -2373,6 +2447,7 @@ var require_dist8 = __commonJS({
2373
2447
  orchestrateAndFix: () => orchestrateAndFix2,
2374
2448
  resolveFocusTests: () => resolveFocusTests,
2375
2449
  resolveMaxAttempts: () => resolveMaxAttempts2,
2450
+ resolveMaxTokens: () => resolveMaxTokens2,
2376
2451
  resolvePatience: () => resolvePatience2,
2377
2452
  resolveTimeoutMs: () => resolveTimeoutMs2
2378
2453
  });
@@ -2545,6 +2620,15 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2545
2620
  }
2546
2621
  return configured;
2547
2622
  }
2623
+ function resolveMaxTokens2(flag, configured) {
2624
+ const source = flag !== void 0 ? "--max-tokens" : "maxTokens in .bugzerorc";
2625
+ const value = flag !== void 0 ? flag : configured;
2626
+ if (value === void 0) return void 0;
2627
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
2628
+ throw new Error(`${source} must be a whole number of 0 or more, where 0 means no limit (received ${JSON.stringify(value) ?? String(value)}).`);
2629
+ }
2630
+ return value === 0 ? void 0 : value;
2631
+ }
2548
2632
  var DEFAULT_PATIENCE = 2;
2549
2633
  function resolvePatience2(flag, configured) {
2550
2634
  const source = flag !== void 0 ? "--patience" : "patience in .bugzerorc";
@@ -2564,8 +2648,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2564
2648
  }
2565
2649
  var import_ai_provider = require_dist5();
2566
2650
  var REPORT_FILENAME2 = "bugzero-report.md";
2567
- function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter) {
2651
+ function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter, budgetStop) {
2568
2652
  const plural = declined === 1 ? "fix" : "fixes";
2653
+ if (budgetStop !== void 0) {
2654
+ const base2 = `Stopped: ${budgetStop} Raise it with --max-tokens.`;
2655
+ return declined > 0 ? `${base2} You declined ${declined} proposed ${plural}.` : base2;
2656
+ }
2569
2657
  if (declined > 0 && !appliedAnything) {
2570
2658
  return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2571
2659
  }
@@ -2602,6 +2690,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2602
2690
  const config = (0, import_config2.getLocalConfig)(cwd);
2603
2691
  const patience = resolvePatience2(options.patience, config.patience);
2604
2692
  const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
2693
+ const maxTokens = resolveMaxTokens2(options.maxTokens, config.maxTokens);
2605
2694
  console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
2606
2695
  const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
2607
2696
  if (pipelineResult.success) {
@@ -2632,19 +2721,21 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2632
2721
  }
2633
2722
  if (options.dryRun) {
2634
2723
  console.log("[BugZero] Dry-run mode \u2014 skipping AI fix.");
2635
- await writeReport(cwd, "rescue", {
2724
+ const spend2 = await writeReport(cwd, "rescue", {
2636
2725
  success: false,
2637
2726
  attempts: 0,
2638
2727
  maxAttempts,
2639
2728
  error: "Dry-run: analysis complete, no files modified.",
2640
2729
  rawOutput: pipelineResult.output,
2641
- dryRun: true
2730
+ dryRun: true,
2731
+ maxTokens
2642
2732
  });
2643
2733
  return {
2644
2734
  success: false,
2645
2735
  attempts: 0,
2646
2736
  finalOutput: pipelineResult.output,
2647
- error: "Dry-run: analysis complete, no files modified."
2737
+ error: "Dry-run: analysis complete, no files modified.",
2738
+ ...tokenBudgetUse(maxTokens, spend2)
2648
2739
  };
2649
2740
  }
2650
2741
  const finalState = await (0, import_agents.runRepairWorkflow)({
@@ -2655,6 +2746,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2655
2746
  approve: options.approve,
2656
2747
  patience,
2657
2748
  focusTests,
2749
+ maxTokens,
2658
2750
  initialStep: pipelineResult.step
2659
2751
  });
2660
2752
  const result = {
@@ -2666,15 +2758,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2666
2758
  maxAttempts,
2667
2759
  finalState.declinedFixes ?? 0,
2668
2760
  Boolean(finalState.appliedFix),
2669
- finalState.stoppedForNoProgress ? patience : void 0
2761
+ finalState.stoppedForNoProgress ? patience : void 0,
2762
+ finalState.budgetStop ?? void 0
2670
2763
  ),
2671
- stoppedEarly: finalState.stoppedForNoProgress ? "no-progress" : void 0,
2764
+ stoppedEarly: finalState.budgetStop ? "token-budget" : finalState.stoppedForNoProgress ? "no-progress" : void 0,
2672
2765
  declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2673
2766
  modelUsed: finalState.modelUsed,
2674
2767
  promptTokens: finalState.promptTokens,
2675
2768
  completionTokens: finalState.completionTokens
2676
2769
  };
2677
- await writeReport(cwd, "rescue", {
2770
+ const spend = await writeReport(cwd, "rescue", {
2678
2771
  success: result.success,
2679
2772
  attempts: result.attempts,
2680
2773
  maxAttempts,
@@ -2683,9 +2776,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2683
2776
  rawOutput: result.finalOutput,
2684
2777
  modelUsed: result.modelUsed,
2685
2778
  promptTokens: result.promptTokens,
2686
- completionTokens: result.completionTokens
2779
+ completionTokens: result.completionTokens,
2780
+ maxTokens,
2781
+ tokensUsed: (result.promptTokens ?? 0) + (result.completionTokens ?? 0),
2782
+ tokensEstimated: finalState.tokensEstimated
2687
2783
  });
2688
- return result;
2784
+ return { ...result, ...tokenBudgetUse(maxTokens, spend) };
2785
+ }
2786
+ function tokenBudgetUse(maxTokens, spend) {
2787
+ if (maxTokens === void 0) return {};
2788
+ return { tokenBudget: { limit: maxTokens, used: spend.tokensUsed, estimated: spend.tokensEstimated } };
2689
2789
  }
2690
2790
  function formatPatchesMarkdown(appliedFix) {
2691
2791
  return appliedFix.patches.map(
@@ -2705,6 +2805,30 @@ ${p.replace}
2705
2805
  async function writeReport(cwd, type, data) {
2706
2806
  let content = "";
2707
2807
  const provider = new import_ai_provider.OpenRouterProvider();
2808
+ const spend = { tokensUsed: data.tokensUsed ?? 0, tokensEstimated: data.tokensEstimated ?? false };
2809
+ const askForReport = async (prompt, announcement) => {
2810
+ const budget = (0, import_shared22.checkBudget)(data.maxTokens, spend.tokensUsed, prompt);
2811
+ if (!budget.allowed) {
2812
+ console.log(`[BugZero] ${budget.reason} Writing the report without the AI.`);
2813
+ throw new Error(budget.reason);
2814
+ }
2815
+ console.log(announcement);
2816
+ const result = await provider.invoke(prompt, { cwd, maxTokens: budget.maxReplyTokens });
2817
+ if (data.maxTokens === void 0) return result;
2818
+ const cost = (0, import_shared22.countCallTokens)(data.maxTokens, prompt, result);
2819
+ spend.tokensUsed += cost.promptTokens + cost.completionTokens;
2820
+ spend.tokensEstimated ||= cost.estimated;
2821
+ if (result.content.trim() === "") {
2822
+ throw new Error("The AI returned an empty reply within the token budget.");
2823
+ }
2824
+ if (!result.truncated) return result;
2825
+ return { ...result, content: `${result.content}
2826
+
2827
+ > \u26A0\uFE0F This AI-written text was cut off by its length limit (see --max-tokens).` };
2828
+ };
2829
+ const aiNote = (reason) => data.maxTokens === void 0 ? "" : `
2830
+ *The AI did not write this report: ${reason}*
2831
+ `;
2708
2832
  if (type === "hunt") {
2709
2833
  const { build, lint, test } = data;
2710
2834
  if (!build.success || !lint.success || !test.success) {
@@ -2788,9 +2912,11 @@ ${logs}
2788
2912
 
2789
2913
  Your project already passes its build, lint, and tests, so BugZero made no changes and did not call an AI model.`;
2790
2914
  } else if (data.dryRun) {
2791
- console.log("[BugZero] Calling AI to diagnose the detected errors and write report...");
2792
2915
  try {
2793
- const result = await provider.invoke(buildDryRunPrompt(cwd, rawOutput ?? ""), { cwd });
2916
+ const result = await askForReport(
2917
+ buildDryRunPrompt(cwd, rawOutput ?? ""),
2918
+ "[BugZero] Calling AI to diagnose the detected errors and write report..."
2919
+ );
2794
2920
  content = result.content + buildDryRunMetadata(result);
2795
2921
  } catch (e) {
2796
2922
  content = buildDryRunFallbackReport({
@@ -2801,10 +2927,9 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2801
2927
  });
2802
2928
  }
2803
2929
  } else if (success && appliedFix) {
2804
- console.log("[BugZero] Calling AI to write solution summary report...");
2805
2930
  const prompt = buildRescueSuccessPrompt({ cwd, attempts, appliedFix });
2806
2931
  try {
2807
- const result = await provider.invoke(prompt, { cwd });
2932
+ const result = await askForReport(prompt, "[BugZero] Calling AI to write solution summary report...");
2808
2933
  content = result.content;
2809
2934
  content += `
2810
2935
 
@@ -2823,7 +2948,7 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2823
2948
 
2824
2949
  ## \u{1F4CA} Repair Summary
2825
2950
  - **Status:** \u2705 Fixed successfully!
2826
- - **Attempts:** ${attempts} / ${maxAttempts}
2951
+ ${aiNote(e.message)}- **Attempts:** ${attempts} / ${maxAttempts}
2827
2952
  - **AI Brain (Model):** \`${modelUsed || "unknown"}\`
2828
2953
  - **Token Usage:** ${promptTokens !== void 0 && completionTokens !== void 0 ? `Prompt: **${promptTokens}** | Completion: **${completionTokens}** | Total: **${promptTokens + completionTokens}**` : "*N/A*"}
2829
2954
 
@@ -2837,10 +2962,9 @@ ${formatPatchesMarkdown(appliedFix)}
2837
2962
  `;
2838
2963
  }
2839
2964
  } else {
2840
- console.log("[BugZero] Calling AI to analyze unresolved errors and write report...");
2841
2965
  const prompt = buildRescueFailurePrompt({ cwd, attempts, rawOutput });
2842
2966
  try {
2843
- const result = await provider.invoke(prompt, { cwd });
2967
+ const result = await askForReport(prompt, "[BugZero] Calling AI to analyze unresolved errors and write report...");
2844
2968
  content = result.content;
2845
2969
  content += `
2846
2970
 
@@ -2865,7 +2989,7 @@ ${formatPatchesMarkdown(appliedFix)}
2865
2989
 
2866
2990
  ## \u274C Failed to Repair
2867
2991
  **Reason:** ${error || "Max attempts reached without finding a solution."}
2868
-
2992
+ ${aiNote(e.message)}
2869
2993
  ### \u{1F7E5} Unresolved Errors & Logs
2870
2994
  \`\`\`text
2871
2995
  ${rawOutput}
@@ -2874,6 +2998,13 @@ ${rawOutput}
2874
2998
  }
2875
2999
  }
2876
3000
  }
3001
+ if (data.maxTokens !== void 0) {
3002
+ const estimates = spend.tokensEstimated ? " (includes estimates)" : "";
3003
+ content += `
3004
+
3005
+ ---
3006
+ **Token budget:** ${spend.tokensUsed} of ${data.maxTokens} tokens used${estimates}`;
3007
+ }
2877
3008
  content += `
2878
3009
 
2879
3010
  ---
@@ -2895,6 +3026,7 @@ ${rawOutput}
2895
3026
  console.log(content);
2896
3027
  console.log("\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
2897
3028
  }
3029
+ return spend;
2898
3030
  }
2899
3031
  var import_analyzers2 = require_dist4();
2900
3032
  }
@@ -2955,6 +3087,8 @@ function buildRescueJson(result, info) {
2955
3087
  attempts: result.attempts,
2956
3088
  model: result.modelUsed || null,
2957
3089
  tokens,
3090
+ tokenBudget: result.tokenBudget ?? null,
3091
+ stoppedEarly: result.stoppedEarly ?? null,
2958
3092
  fix: result.appliedFix ? {
2959
3093
  rootCause: result.appliedFix.rootCause,
2960
3094
  explanation: result.appliedFix.explanation,
@@ -3025,10 +3159,18 @@ function createApprovalHandler(io) {
3025
3159
  var import_patcher = __toESM(require_dist3());
3026
3160
  var import_path = __toESM(require("path"));
3027
3161
  var import_shared2 = __toESM(require_dist2());
3162
+ function budgetLines(result) {
3163
+ if (!result.tokenBudget) return [];
3164
+ const { used, limit, estimated } = result.tokenBudget;
3165
+ return [` Token budget: ${used} of ${limit} used${estimated ? " (includes estimates)" : ""}`];
3166
+ }
3028
3167
  function tokenLines(result) {
3029
- if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
3168
+ if (result.promptTokens === void 0 || result.completionTokens === void 0) return budgetLines(result);
3030
3169
  const total = result.promptTokens + result.completionTokens;
3031
- return [` Tokens: Prompt: ${result.promptTokens} | Completion: ${result.completionTokens} | Total: ${total}`];
3170
+ return [
3171
+ ` Tokens: Prompt: ${result.promptTokens} | Completion: ${result.completionTokens} | Total: ${total}`,
3172
+ ...budgetLines(result)
3173
+ ];
3032
3174
  }
3033
3175
  function buildRescueSummary(result, options) {
3034
3176
  if (result.success && result.attempts === 0) {
@@ -3060,6 +3202,7 @@ function buildRescueSummary(result, options) {
3060
3202
  lines: [
3061
3203
  "\u{1F50D} Dry run complete \u2014 failures were detected, but no fixes were attempted and no files were modified.",
3062
3204
  " Re-run without --dry-run to let BugZero attempt a fix.",
3205
+ ...budgetLines(result),
3063
3206
  "",
3064
3207
  "\u{1F449} Full error logs have been listed in the generated report."
3065
3208
  ]
@@ -3170,7 +3313,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
3170
3313
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
3171
3314
  }
3172
3315
  });
3173
- program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--patience <n>", "Stop early after this many attempts in a row make no progress (default 2, 0 turns it off)").option("--no-focus-tests", "Always run the full build, lint and tests, instead of re-running only the failing test files between attempts").option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
3316
+ program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--patience <n>", "Stop early after this many attempts in a row make no progress (default 2, 0 turns it off)").option("--max-tokens <n>", "Limit the AI tokens the run may use, the report included (default no limit, 0 for none)").option("--no-focus-tests", "Always run the full build, lint and tests, instead of re-running only the failing test files between attempts").option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
3174
3317
  const json = opts.json === true;
3175
3318
  const printPrompt = opts.printPrompt === true;
3176
3319
  if (json || printPrompt) routeLogsToStderr();
@@ -3181,6 +3324,8 @@ program.command("rescue").description("Detect build failures and automatically a
3181
3324
  const timeoutSeconds = parseTimeout(opts.timeout);
3182
3325
  const patience = opts.patience === void 0 ? void 0 : Number(opts.patience);
3183
3326
  (0, import_core.resolvePatience)(patience, void 0);
3327
+ const maxTokens = opts.maxTokens === void 0 ? void 0 : Number(opts.maxTokens);
3328
+ (0, import_core.resolveMaxTokens)(maxTokens, void 0);
3184
3329
  const focusTests = opts.focusTests === false ? false : void 0;
3185
3330
  const dryRun = opts.dryRun;
3186
3331
  let approve;
@@ -3202,10 +3347,21 @@ program.command("rescue").description("Detect build failures and automatically a
3202
3347
  console.log(` Max attempts: ${maxAttempts}`);
3203
3348
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
3204
3349
  if (patience !== void 0) console.log(` Patience: ${patience === 0 ? "off" : `${patience} attempt(s) without progress`}`);
3350
+ if (maxTokens !== void 0) console.log(` Token budget: ${maxTokens === 0 ? "no limit" : maxTokens}`);
3205
3351
  if (focusTests === false) console.log(` Focus tests: off (the full pipeline runs every time)`);
3206
3352
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
3207
3353
  console.log();
3208
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve, patience, focusTests });
3354
+ const result = await (0, import_core.orchestrateAndFix)({
3355
+ cwd,
3356
+ maxAttempts,
3357
+ dryRun,
3358
+ timeoutSeconds,
3359
+ printPrompt,
3360
+ approve,
3361
+ patience,
3362
+ focusTests,
3363
+ maxTokens
3364
+ });
3209
3365
  if (result.promptPreview !== void 0) {
3210
3366
  if (json) {
3211
3367
  finish(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.60",
3
+ "version": "0.0.61",
4
4
  "description": "Autonomous AI-powered CLI and GitHub Action that detects build, lint, and test failures, generates multi-file patches, applies them atomically with fuzzy matching, and re-verifies until your project is green.",
5
5
  "license": "MIT",
6
6
  "author": "Saksham Agarwal (https://github.com/Saksham1800t)",