bugzero 0.0.59 → 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 +12 -2
  2. package/dist/index.js +298 -32
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -228,6 +228,10 @@ The whole proposed fix is shown at once, because a fix that spans several files
228
228
 
229
229
  **Stuck runs stop early.** After each attempt BugZero compares what is still failing with the best result so far. It counts as progress when there are fewer errors, or when a later step is now the one failing (the build passes and lint fails, or lint passes and the tests fail), even if that step shows more errors. If 2 attempts in a row make no progress, it stops and says why, instead of paying for the remaining attempts. Output BugZero cannot count only stops a run when it is exactly the same as before. Attempts whose patch could not be applied, or that you declined, do not count. Change the limit with `--patience <n>` or `patience` in `.bugzerorc`; `0` turns it off.
230
230
 
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
+
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
+
231
235
  <details>
232
236
  <summary><strong>Options for <code>rescue</code></strong></summary>
233
237
 
@@ -237,6 +241,8 @@ The whole proposed fix is shown at once, because a fix that spans several files
237
241
  | `--max-attempts <n>` | `-n` | `3` | Maximum AI fix iterations before giving up |
238
242
  | `--timeout <seconds>` | `-t` | none | Stop any build, lint, or test command that runs longer than this many seconds |
239
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 |
245
+ | `--no-focus-tests` | | off | Always run the full build, lint and tests, instead of re-running only the failing test files between attempts |
240
246
  | `--dry-run` | | `false` | Analyze only — no files will be written |
241
247
  | `--approve` | | `false` | Show each proposed fix as a diff and ask before writing it. Needs an interactive terminal |
242
248
  | `--print-prompt` | | `false` | Print the exact prompt that would be sent to the AI model, then stop. Nothing is sent and no files are written |
@@ -288,7 +294,7 @@ bugzero hunt --json | jq '.steps'
288
294
  bugzero rescue --json --dry-run | jq -r '.outcome'
289
295
  ```
290
296
 
291
- `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": "..." }`.
292
298
 
293
299
  ---
294
300
 
@@ -315,7 +321,9 @@ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick
315
321
  "model": "deepseek/deepseek-chat",
316
322
  "protect": ["config/prod.json", "migrations/**"],
317
323
  "allow": [".env.example"],
318
- "patience": 2
324
+ "patience": 2,
325
+ "focusTests": true,
326
+ "maxTokens": 100000
319
327
  }
320
328
  ```
321
329
 
@@ -325,6 +333,8 @@ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick
325
333
  | `protect` | Extra files BugZero must never edit, added to the built-in list (see Protected files above). |
326
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. |
327
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. |
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. |
328
338
 
329
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.
330
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
 
@@ -1295,15 +1333,21 @@ var require_dist4 = __commonJS({
1295
1333
  var index_exports = {};
1296
1334
  __export(index_exports, {
1297
1335
  detectPackageManager: () => detectPackageManager3,
1336
+ detectTestRunner: () => detectTestRunner,
1337
+ findFailingTestFiles: () => findFailingTestFiles,
1298
1338
  getRunScriptCommand: () => getRunScriptCommand,
1299
1339
  parseErrors: () => parseErrors,
1340
+ planFocusedTests: () => planFocusedTests,
1341
+ readScriptText: () => readScriptText,
1300
1342
  readScripts: () => readScripts,
1301
1343
  runBuild: () => runBuild,
1302
1344
  runCommand: () => runCommand,
1345
+ runFocusedTests: () => runFocusedTests,
1303
1346
  runLint: () => runLint,
1304
1347
  runScript: () => runScript,
1305
1348
  runTests: () => runTests,
1306
- runValidationPipeline: () => runValidationPipeline
1349
+ runValidationPipeline: () => runValidationPipeline,
1350
+ usableFocusedResult: () => usableFocusedResult
1307
1351
  });
1308
1352
  module2.exports = __toCommonJS(index_exports);
1309
1353
  var import_fs2 = __toESM2(require("fs"));
@@ -1412,6 +1456,17 @@ var require_dist4 = __commonJS({
1412
1456
  return [];
1413
1457
  }
1414
1458
  }
1459
+ function readScriptText(cwd, name) {
1460
+ try {
1461
+ const pkgPath = import_path3.default.join(cwd, "package.json");
1462
+ if (!import_fs2.default.existsSync(pkgPath)) return void 0;
1463
+ const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
1464
+ const text = pkg?.scripts?.[name];
1465
+ return typeof text === "string" ? text : void 0;
1466
+ } catch {
1467
+ return void 0;
1468
+ }
1469
+ }
1415
1470
  async function runScript(script, cwd, options) {
1416
1471
  if (!readScripts(cwd).includes(script)) {
1417
1472
  return { success: true, output: "", skipped: true };
@@ -1497,6 +1552,61 @@ var require_dist4 = __commonJS({
1497
1552
  }
1498
1553
  return { success: true, step: "none", output: "" };
1499
1554
  }
1555
+ var import_fs32 = __toESM2(require("fs"));
1556
+ var import_shared4 = require_dist2();
1557
+ var MAX_FOCUSED_FILES = 10;
1558
+ var ANSI_RE = /\u001b\[[0-9;]*[A-Za-z]/g;
1559
+ var FAIL_LINE_RE = /^[ \t]*FAIL[ \t]+(?:\|[^|\n]*\|[ \t]+)?(\S+)/gm;
1560
+ var TEST_FILE_RE = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)__tests__\//;
1561
+ var SAFE_PATH_RE = /^[A-Za-z0-9_@.+/-]+$/;
1562
+ function detectTestRunner(script) {
1563
+ if (typeof script !== "string" || script.trim() === "") return null;
1564
+ if (/[&|;<>`$()]/.test(script)) return null;
1565
+ const names = /* @__PURE__ */ new Set();
1566
+ for (const token of script.trim().split(/\s+/)) {
1567
+ const name = token.split(/[\\/]/).pop();
1568
+ if (name === "vitest" || name === "jest") names.add(name);
1569
+ }
1570
+ return names.size === 1 ? [...names][0] : null;
1571
+ }
1572
+ function findFailingTestFiles(cwd, output) {
1573
+ const text = output.replace(ANSI_RE, "").replace(/\r\n/g, "\n");
1574
+ const files = [];
1575
+ for (const match of text.matchAll(FAIL_LINE_RE)) {
1576
+ const candidate = match[1].replace(/\\/g, "/").replace(/^\.\//, "");
1577
+ if (files.includes(candidate)) continue;
1578
+ if (!SAFE_PATH_RE.test(candidate) || candidate.startsWith("-") || candidate.split("/").includes("..")) continue;
1579
+ if (!TEST_FILE_RE.test(candidate)) continue;
1580
+ const resolved = (0, import_shared4.resolveInsideProject)(cwd, candidate);
1581
+ if (!resolved.ok) continue;
1582
+ try {
1583
+ if (!import_fs32.default.statSync(resolved.absolutePath).isFile()) continue;
1584
+ } catch {
1585
+ continue;
1586
+ }
1587
+ files.push(candidate);
1588
+ }
1589
+ return files.length > MAX_FOCUSED_FILES ? [] : files;
1590
+ }
1591
+ function focusedCommand(manager, files) {
1592
+ const args = files.map((file) => `"${file}"`).join(" ");
1593
+ return manager === "npm" ? `npm run test -- ${args}` : `${manager} run test ${args}`;
1594
+ }
1595
+ function planFocusedTests(cwd, output) {
1596
+ const runner = detectTestRunner(readScriptText(cwd, "test"));
1597
+ if (runner === null) return null;
1598
+ const files = findFailingTestFiles(cwd, output);
1599
+ if (files.length === 0) return null;
1600
+ return { runner, files, command: focusedCommand(detectPackageManager3(cwd), files) };
1601
+ }
1602
+ function runFocusedTests(plan, cwd, options) {
1603
+ return runCommand(plan.command, cwd, options);
1604
+ }
1605
+ function usableFocusedResult(cwd, result) {
1606
+ if (result.success) return false;
1607
+ if (result.timedOut) return true;
1608
+ return findFailingTestFiles(cwd, result.output).length > 0;
1609
+ }
1500
1610
  }
1501
1611
  });
1502
1612
 
@@ -1610,7 +1720,8 @@ var require_dist5 = __commonJS({
1610
1720
  role: "user",
1611
1721
  content: prompt
1612
1722
  }
1613
- ]
1723
+ ],
1724
+ ...options?.maxTokens !== void 0 ? { max_tokens: options.maxTokens } : {}
1614
1725
  },
1615
1726
  {
1616
1727
  headers: {
@@ -1622,10 +1733,12 @@ var require_dist5 = __commonJS({
1622
1733
  if (response.data?.error) {
1623
1734
  throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1624
1735
  }
1736
+ const choice = response.data.choices[0];
1625
1737
  return {
1626
- content: response.data.choices[0].message.content,
1738
+ content: choice.message.content ?? "",
1627
1739
  model,
1628
- usage: response.data.usage
1740
+ usage: response.data.usage,
1741
+ ...choice.finish_reason === "length" ? { truncated: true } : {}
1629
1742
  };
1630
1743
  } catch (error) {
1631
1744
  let msg = error.message;
@@ -2029,11 +2142,31 @@ var require_dist7 = __commonJS({
2029
2142
  reducer: (_, value) => value,
2030
2143
  default: () => null
2031
2144
  }),
2145
+ /** Whether, while tests are what is failing, verification may re-run only the failing test files first */
2146
+ focusTests: (0, import_langgraph.Annotation)({
2147
+ reducer: (_, value) => value,
2148
+ default: () => true
2149
+ }),
2032
2150
  /** True when the run stopped before max attempts because attempts were not making progress */
2033
2151
  stoppedForNoProgress: (0, import_langgraph.Annotation)({
2034
2152
  reducer: (_, value) => value,
2035
2153
  default: () => false
2036
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
+ }),
2037
2170
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
2038
2171
  timeoutMs: (0, import_langgraph.Annotation)({
2039
2172
  reducer: (_, value) => value,
@@ -2089,13 +2222,27 @@ var require_dist7 = __commonJS({
2089
2222
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
2090
2223
  }
2091
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
+ }
2092
2233
  console.log(
2093
2234
  `
2094
2235
  [BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
2095
2236
  );
2096
- const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2097
- const result = await provider.invoke(prompt, { cwd: state.cwd });
2237
+ const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
2098
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
+ }
2099
2246
  let fixSuggestion = null;
2100
2247
  try {
2101
2248
  const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
@@ -2118,8 +2265,9 @@ var require_dist7 = __commonJS({
2118
2265
  fixSuggestion,
2119
2266
  attempts: state.attempts + 1,
2120
2267
  modelUsed: result.model,
2121
- promptTokens: result.usage?.prompt_tokens ?? 0,
2122
- completionTokens: result.usage?.completion_tokens ?? 0
2268
+ promptTokens: tokens.promptTokens,
2269
+ completionTokens: tokens.completionTokens,
2270
+ tokensEstimated: tokens.estimated
2123
2271
  };
2124
2272
  }
2125
2273
  function patchFailure(state, error) {
@@ -2183,6 +2331,25 @@ Any other files from that same suggestion were rolled back to keep the change at
2183
2331
  patchFailed: false
2184
2332
  };
2185
2333
  }
2334
+ async function validate(state) {
2335
+ const options = { timeoutMs: state.timeoutMs };
2336
+ if (state.focusTests !== false && state.progress?.last.step === "test") {
2337
+ const plan = (0, import_analyzers2.planFocusedTests)(state.cwd, state.logs);
2338
+ if (plan) {
2339
+ console.log(
2340
+ `[BugZero] Re-running only the failing test file${plan.files.length === 1 ? "" : "s"}: ${plan.files.join(", ")} (the full pipeline runs once they pass)\u2026`
2341
+ );
2342
+ const focused = await (0, import_analyzers2.runFocusedTests)(plan, state.cwd, options);
2343
+ if ((0, import_analyzers2.usableFocusedResult)(state.cwd, focused)) {
2344
+ return { success: false, step: "test", output: focused.output };
2345
+ }
2346
+ console.log(
2347
+ focused.success ? "[BugZero] Those tests pass now \u2014 running the full pipeline to confirm\u2026" : "[BugZero] The focused run did not report any failing test file, so it is not trusted \u2014 running the full pipeline instead\u2026"
2348
+ );
2349
+ }
2350
+ }
2351
+ return (0, import_analyzers2.runValidationPipeline)(state.cwd, options);
2352
+ }
2186
2353
  async function verifyNode(state) {
2187
2354
  if (state.patchFailed) {
2188
2355
  console.log("[BugZero] Skipping validation pipeline because the patch failed to apply.");
@@ -2192,7 +2359,7 @@ Any other files from that same suggestion were rolled back to keep the change at
2192
2359
  };
2193
2360
  }
2194
2361
  console.log("[BugZero] Re-running validation pipeline to verify fix\u2026");
2195
- const result = await (0, import_analyzers2.runValidationPipeline)(state.cwd, { timeoutMs: state.timeoutMs });
2362
+ const result = await validate(state);
2196
2363
  if (result.success) {
2197
2364
  console.log("[BugZero] \u2705 Validation succeeded!");
2198
2365
  } else {
@@ -2219,7 +2386,10 @@ Any other files from that same suggestion were rolled back to keep the change at
2219
2386
  }
2220
2387
  return "analyze";
2221
2388
  }
2222
- 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();
2223
2393
  function runRepairWorkflow(input) {
2224
2394
  const { initialStep, ...rest } = input;
2225
2395
  return workflow.invoke(
@@ -2275,7 +2445,9 @@ var require_dist8 = __commonJS({
2275
2445
  detectPackageManager: () => import_analyzers2.detectPackageManager,
2276
2446
  orchestrate: () => orchestrate2,
2277
2447
  orchestrateAndFix: () => orchestrateAndFix2,
2448
+ resolveFocusTests: () => resolveFocusTests,
2278
2449
  resolveMaxAttempts: () => resolveMaxAttempts2,
2450
+ resolveMaxTokens: () => resolveMaxTokens2,
2279
2451
  resolvePatience: () => resolvePatience2,
2280
2452
  resolveTimeoutMs: () => resolveTimeoutMs2
2281
2453
  });
@@ -2440,6 +2612,23 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2440
2612
  }
2441
2613
  return attempts;
2442
2614
  }
2615
+ function resolveFocusTests(flag, configured) {
2616
+ if (flag !== void 0) return flag;
2617
+ if (configured === void 0) return true;
2618
+ if (typeof configured !== "boolean") {
2619
+ throw new Error(`focusTests in .bugzerorc must be true or false (received ${JSON.stringify(configured)}).`);
2620
+ }
2621
+ return configured;
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
+ }
2443
2632
  var DEFAULT_PATIENCE = 2;
2444
2633
  function resolvePatience2(flag, configured) {
2445
2634
  const source = flag !== void 0 ? "--patience" : "patience in .bugzerorc";
@@ -2459,8 +2648,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2459
2648
  }
2460
2649
  var import_ai_provider = require_dist5();
2461
2650
  var REPORT_FILENAME2 = "bugzero-report.md";
2462
- function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter) {
2651
+ function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter, budgetStop) {
2463
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
+ }
2464
2657
  if (declined > 0 && !appliedAnything) {
2465
2658
  return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2466
2659
  }
@@ -2494,7 +2687,10 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2494
2687
  assertNodeProject(cwd);
2495
2688
  const maxAttempts = resolveMaxAttempts2(options.maxAttempts);
2496
2689
  const timeoutMs = resolveTimeoutMs2(options.timeoutSeconds);
2497
- const patience = resolvePatience2(options.patience, (0, import_config2.getLocalConfig)(cwd).patience);
2690
+ const config = (0, import_config2.getLocalConfig)(cwd);
2691
+ const patience = resolvePatience2(options.patience, config.patience);
2692
+ const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
2693
+ const maxTokens = resolveMaxTokens2(options.maxTokens, config.maxTokens);
2498
2694
  console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
2499
2695
  const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
2500
2696
  if (pipelineResult.success) {
@@ -2525,19 +2721,21 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2525
2721
  }
2526
2722
  if (options.dryRun) {
2527
2723
  console.log("[BugZero] Dry-run mode \u2014 skipping AI fix.");
2528
- await writeReport(cwd, "rescue", {
2724
+ const spend2 = await writeReport(cwd, "rescue", {
2529
2725
  success: false,
2530
2726
  attempts: 0,
2531
2727
  maxAttempts,
2532
2728
  error: "Dry-run: analysis complete, no files modified.",
2533
2729
  rawOutput: pipelineResult.output,
2534
- dryRun: true
2730
+ dryRun: true,
2731
+ maxTokens
2535
2732
  });
2536
2733
  return {
2537
2734
  success: false,
2538
2735
  attempts: 0,
2539
2736
  finalOutput: pipelineResult.output,
2540
- error: "Dry-run: analysis complete, no files modified."
2737
+ error: "Dry-run: analysis complete, no files modified.",
2738
+ ...tokenBudgetUse(maxTokens, spend2)
2541
2739
  };
2542
2740
  }
2543
2741
  const finalState = await (0, import_agents.runRepairWorkflow)({
@@ -2547,6 +2745,8 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2547
2745
  timeoutMs,
2548
2746
  approve: options.approve,
2549
2747
  patience,
2748
+ focusTests,
2749
+ maxTokens,
2550
2750
  initialStep: pipelineResult.step
2551
2751
  });
2552
2752
  const result = {
@@ -2558,15 +2758,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2558
2758
  maxAttempts,
2559
2759
  finalState.declinedFixes ?? 0,
2560
2760
  Boolean(finalState.appliedFix),
2561
- finalState.stoppedForNoProgress ? patience : void 0
2761
+ finalState.stoppedForNoProgress ? patience : void 0,
2762
+ finalState.budgetStop ?? void 0
2562
2763
  ),
2563
- stoppedEarly: finalState.stoppedForNoProgress ? "no-progress" : void 0,
2764
+ stoppedEarly: finalState.budgetStop ? "token-budget" : finalState.stoppedForNoProgress ? "no-progress" : void 0,
2564
2765
  declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2565
2766
  modelUsed: finalState.modelUsed,
2566
2767
  promptTokens: finalState.promptTokens,
2567
2768
  completionTokens: finalState.completionTokens
2568
2769
  };
2569
- await writeReport(cwd, "rescue", {
2770
+ const spend = await writeReport(cwd, "rescue", {
2570
2771
  success: result.success,
2571
2772
  attempts: result.attempts,
2572
2773
  maxAttempts,
@@ -2575,9 +2776,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2575
2776
  rawOutput: result.finalOutput,
2576
2777
  modelUsed: result.modelUsed,
2577
2778
  promptTokens: result.promptTokens,
2578
- completionTokens: result.completionTokens
2779
+ completionTokens: result.completionTokens,
2780
+ maxTokens,
2781
+ tokensUsed: (result.promptTokens ?? 0) + (result.completionTokens ?? 0),
2782
+ tokensEstimated: finalState.tokensEstimated
2579
2783
  });
2580
- 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 } };
2581
2789
  }
2582
2790
  function formatPatchesMarkdown(appliedFix) {
2583
2791
  return appliedFix.patches.map(
@@ -2597,6 +2805,30 @@ ${p.replace}
2597
2805
  async function writeReport(cwd, type, data) {
2598
2806
  let content = "";
2599
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
+ `;
2600
2832
  if (type === "hunt") {
2601
2833
  const { build, lint, test } = data;
2602
2834
  if (!build.success || !lint.success || !test.success) {
@@ -2680,9 +2912,11 @@ ${logs}
2680
2912
 
2681
2913
  Your project already passes its build, lint, and tests, so BugZero made no changes and did not call an AI model.`;
2682
2914
  } else if (data.dryRun) {
2683
- console.log("[BugZero] Calling AI to diagnose the detected errors and write report...");
2684
2915
  try {
2685
- 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
+ );
2686
2920
  content = result.content + buildDryRunMetadata(result);
2687
2921
  } catch (e) {
2688
2922
  content = buildDryRunFallbackReport({
@@ -2693,10 +2927,9 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2693
2927
  });
2694
2928
  }
2695
2929
  } else if (success && appliedFix) {
2696
- console.log("[BugZero] Calling AI to write solution summary report...");
2697
2930
  const prompt = buildRescueSuccessPrompt({ cwd, attempts, appliedFix });
2698
2931
  try {
2699
- const result = await provider.invoke(prompt, { cwd });
2932
+ const result = await askForReport(prompt, "[BugZero] Calling AI to write solution summary report...");
2700
2933
  content = result.content;
2701
2934
  content += `
2702
2935
 
@@ -2715,7 +2948,7 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2715
2948
 
2716
2949
  ## \u{1F4CA} Repair Summary
2717
2950
  - **Status:** \u2705 Fixed successfully!
2718
- - **Attempts:** ${attempts} / ${maxAttempts}
2951
+ ${aiNote(e.message)}- **Attempts:** ${attempts} / ${maxAttempts}
2719
2952
  - **AI Brain (Model):** \`${modelUsed || "unknown"}\`
2720
2953
  - **Token Usage:** ${promptTokens !== void 0 && completionTokens !== void 0 ? `Prompt: **${promptTokens}** | Completion: **${completionTokens}** | Total: **${promptTokens + completionTokens}**` : "*N/A*"}
2721
2954
 
@@ -2729,10 +2962,9 @@ ${formatPatchesMarkdown(appliedFix)}
2729
2962
  `;
2730
2963
  }
2731
2964
  } else {
2732
- console.log("[BugZero] Calling AI to analyze unresolved errors and write report...");
2733
2965
  const prompt = buildRescueFailurePrompt({ cwd, attempts, rawOutput });
2734
2966
  try {
2735
- const result = await provider.invoke(prompt, { cwd });
2967
+ const result = await askForReport(prompt, "[BugZero] Calling AI to analyze unresolved errors and write report...");
2736
2968
  content = result.content;
2737
2969
  content += `
2738
2970
 
@@ -2757,7 +2989,7 @@ ${formatPatchesMarkdown(appliedFix)}
2757
2989
 
2758
2990
  ## \u274C Failed to Repair
2759
2991
  **Reason:** ${error || "Max attempts reached without finding a solution."}
2760
-
2992
+ ${aiNote(e.message)}
2761
2993
  ### \u{1F7E5} Unresolved Errors & Logs
2762
2994
  \`\`\`text
2763
2995
  ${rawOutput}
@@ -2766,6 +2998,13 @@ ${rawOutput}
2766
2998
  }
2767
2999
  }
2768
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
+ }
2769
3008
  content += `
2770
3009
 
2771
3010
  ---
@@ -2787,6 +3026,7 @@ ${rawOutput}
2787
3026
  console.log(content);
2788
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");
2789
3028
  }
3029
+ return spend;
2790
3030
  }
2791
3031
  var import_analyzers2 = require_dist4();
2792
3032
  }
@@ -2847,6 +3087,8 @@ function buildRescueJson(result, info) {
2847
3087
  attempts: result.attempts,
2848
3088
  model: result.modelUsed || null,
2849
3089
  tokens,
3090
+ tokenBudget: result.tokenBudget ?? null,
3091
+ stoppedEarly: result.stoppedEarly ?? null,
2850
3092
  fix: result.appliedFix ? {
2851
3093
  rootCause: result.appliedFix.rootCause,
2852
3094
  explanation: result.appliedFix.explanation,
@@ -2917,10 +3159,18 @@ function createApprovalHandler(io) {
2917
3159
  var import_patcher = __toESM(require_dist3());
2918
3160
  var import_path = __toESM(require("path"));
2919
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
+ }
2920
3167
  function tokenLines(result) {
2921
- if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
3168
+ if (result.promptTokens === void 0 || result.completionTokens === void 0) return budgetLines(result);
2922
3169
  const total = result.promptTokens + result.completionTokens;
2923
- 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
+ ];
2924
3174
  }
2925
3175
  function buildRescueSummary(result, options) {
2926
3176
  if (result.success && result.attempts === 0) {
@@ -2952,6 +3202,7 @@ function buildRescueSummary(result, options) {
2952
3202
  lines: [
2953
3203
  "\u{1F50D} Dry run complete \u2014 failures were detected, but no fixes were attempted and no files were modified.",
2954
3204
  " Re-run without --dry-run to let BugZero attempt a fix.",
3205
+ ...budgetLines(result),
2955
3206
  "",
2956
3207
  "\u{1F449} Full error logs have been listed in the generated report."
2957
3208
  ]
@@ -3062,7 +3313,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
3062
3313
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
3063
3314
  }
3064
3315
  });
3065
- 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("--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) => {
3066
3317
  const json = opts.json === true;
3067
3318
  const printPrompt = opts.printPrompt === true;
3068
3319
  if (json || printPrompt) routeLogsToStderr();
@@ -3073,6 +3324,9 @@ program.command("rescue").description("Detect build failures and automatically a
3073
3324
  const timeoutSeconds = parseTimeout(opts.timeout);
3074
3325
  const patience = opts.patience === void 0 ? void 0 : Number(opts.patience);
3075
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);
3329
+ const focusTests = opts.focusTests === false ? false : void 0;
3076
3330
  const dryRun = opts.dryRun;
3077
3331
  let approve;
3078
3332
  if (opts.approve === true && !dryRun && !printPrompt) {
@@ -3093,9 +3347,21 @@ program.command("rescue").description("Detect build failures and automatically a
3093
3347
  console.log(` Max attempts: ${maxAttempts}`);
3094
3348
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
3095
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}`);
3351
+ if (focusTests === false) console.log(` Focus tests: off (the full pipeline runs every time)`);
3096
3352
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
3097
3353
  console.log();
3098
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve, patience });
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
+ });
3099
3365
  if (result.promptPreview !== void 0) {
3100
3366
  if (json) {
3101
3367
  finish(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.59",
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)",