bugzero 0.0.60 → 0.0.62

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 +9 -4
  2. package/dist/index.js +232 -36
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -101,7 +101,7 @@ bugzero rescue
101
101
 
102
102
  - **Backups on every patch.** Each file BugZero modifies gets a `.opspilot.bak` copy of its original content first. The backup is written once per run, so it always restores what you had, even if the fix took several attempts. A leftover backup from an earlier run is replaced.
103
103
  - **Project boundary.** BugZero only reads and edits files inside the project you point it at. A patch whose path leaves the project (with `../`, an absolute path elsewhere, or a symlink or junction that points out) is refused before any file changes, and the model is told why. Files outside the project are never added to what is sent to the model, even if an error log mentions them.
104
- - **Protected files.** BugZero never edits secrets (`.env`, `.env.*`, `*.pem`, `*.key`), `.git/`, CI configuration (`.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`, and similar), lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`), `node_modules/`, or its own `.opspilot.bak` backups. A patch to one of them is refused before any file changes, and the model is told to fix the problem elsewhere. Secret files are also never sent to the model, even if an error log names them. You can adjust the list in `.bugzerorc` (see Configuration).
104
+ - **Protected files.** BugZero never edits secrets (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `.git/`, CI configuration (`.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`, and similar), lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`), `node_modules/`, or its own `.opspilot.bak` backups. A patch to one of them is refused before any file changes, and the model is told to fix the problem elsewhere. Secret files are also never sent to the model, even if an error log names them. You can adjust the list in `.bugzerorc` (see Configuration).
105
105
  - **Dry-run mode.** `bugzero rescue --dry-run` runs validation and error analysis, but makes no fix attempts and never modifies your source files (it still writes a report that diagnoses the failures it found). It exits with code 1 if it found failures and 0 if everything already passes, so you can use it as a check in scripts.
106
106
  - **Prompt size limits.** Very long error output and very large source files are shortened before being sent to the model (for logs, the start and end are kept), so a big failure can't exceed the model's context window or waste tokens.
107
107
  - **Command timeouts.** `--timeout <seconds>` (available on both `hunt` and `rescue`) stops any build, lint, or test command that runs longer than that. It kills the whole process tree rather than just the shell, so a hung test run cannot linger in the background, and the step is reported as failed along with whatever output it produced. Without it, a command that hangs will hang BugZero too, so it is worth setting in CI.
@@ -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
 
@@ -300,7 +303,7 @@ bugzero rescue --json --dry-run | jq -r '.outcome'
300
303
  BugZero runs your build, lint and tests on your own machine. The only time your code can leave it is when BugZero asks an AI model for help, through [OpenRouter](https://openrouter.ai) with your own API key.
301
304
 
302
305
  - **What is sent:** the error output of the failing command and the contents of the project's source files that output mentions (each shortened to a size limit), plus your project folder's path. Nothing is sent when your project already passes.
303
- - **What is never sent:** files outside your project, secret files (`.env`, `.env.*`, `*.pem`, `*.key`), `node_modules`, build output and `.git`. BugZero cannot recognise a secret by its content, so a password that your build prints is sent like any other text.
306
+ - **What is never sent:** files outside your project, secret files (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `node_modules`, build output and `.git`. BugZero cannot recognise a secret by its content, so a password that your build prints is sent like any other text.
304
307
  - **See it first:** `bugzero rescue --print-prompt` prints the exact prompt and sends nothing.
305
308
  - **Stay offline:** `bugzero hunt --no-ai-report` makes no network call.
306
309
  - There is no telemetry, analytics or update check.
@@ -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,13 @@ 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
+ DEFAULT_UNREADABLE_PATTERNS: () => DEFAULT_UNREADABLE_PATTERNS,
503
+ MAX_REPLY_TOKENS: () => MAX_REPLY_TOKENS,
504
+ MIN_REPLY_TOKENS: () => MIN_REPLY_TOKENS,
505
+ checkBudget: () => checkBudget,
506
+ countCallTokens: () => countCallTokens,
502
507
  createProtectedPathRules: () => createProtectedPathRules2,
508
+ estimateTokens: () => estimateTokens,
503
509
  isInsideDirectory: () => isInsideDirectory,
504
510
  isLexicallyInside: () => isLexicallyInside,
505
511
  projectRelativePaths: () => projectRelativePaths,
@@ -553,7 +559,23 @@ var require_dist2 = __commonJS({
553
559
  }
554
560
  var import_fs22 = __toESM2(require("fs"));
555
561
  var import_path22 = __toESM2(require("path"));
556
- var DEFAULT_SECRET_PATTERNS = [".env", ".env.*", "*.pem", "*.key"];
562
+ var DEFAULT_SECRET_PATTERNS = [
563
+ ".env",
564
+ ".env.*",
565
+ "*.pem",
566
+ "*.key",
567
+ // These can hold registry or login tokens.
568
+ ".npmrc",
569
+ ".netrc",
570
+ ".pypirc"
571
+ ];
572
+ var DEFAULT_UNREADABLE_PATTERNS = [
573
+ ...DEFAULT_SECRET_PATTERNS,
574
+ ".git/",
575
+ "node_modules/",
576
+ "*.opspilot.bak",
577
+ "*.opspilot.bak.sha"
578
+ ];
557
579
  var DEFAULT_PROTECTED_PATTERNS = [
558
580
  ...DEFAULT_SECRET_PATTERNS,
559
581
  ".git/",
@@ -614,8 +636,14 @@ var require_dist2 = __commonJS({
614
636
  function createProtectedPathRules2(settings = {}) {
615
637
  const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
616
638
  const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
639
+ const unreadable = compileAll(DEFAULT_UNREADABLE_PATTERNS);
617
640
  const extra = compileAll(settings.protect);
618
641
  const allowed = compileAll(settings.allow);
642
+ const blockedUnlessAllowed = (matchers, relPath) => {
643
+ const normalized = normalizePath(relPath);
644
+ if (firstMatch(allowed, normalized)) return void 0;
645
+ return firstMatch(matchers, normalized)?.pattern;
646
+ };
619
647
  return {
620
648
  editBlockedBy(relPath) {
621
649
  const normalized = normalizePath(relPath);
@@ -624,11 +652,8 @@ var require_dist2 = __commonJS({
624
652
  if (firstMatch(allowed, normalized)) return void 0;
625
653
  return firstMatch(defaults, normalized)?.pattern;
626
654
  },
627
- secretBlockedBy(relPath) {
628
- const normalized = normalizePath(relPath);
629
- if (firstMatch(allowed, normalized)) return void 0;
630
- return firstMatch(secrets, normalized)?.pattern;
631
- }
655
+ secretBlockedBy: (relPath) => blockedUnlessAllowed(secrets, relPath),
656
+ readBlockedBy: (relPath) => blockedUnlessAllowed(unreadable, relPath)
632
657
  };
633
658
  }
634
659
  function toRelative(root, target) {
@@ -658,6 +683,39 @@ var require_dist2 = __commonJS({
658
683
  }
659
684
  return paths;
660
685
  }
686
+ var CHARS_PER_TOKEN = 4;
687
+ var MIN_REPLY_TOKENS = 500;
688
+ var MAX_REPLY_TOKENS = 8192;
689
+ function estimateTokens(text) {
690
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
691
+ }
692
+ function checkBudget(limit, used, prompt) {
693
+ if (limit === void 0) return { allowed: true, maxReplyTokens: void 0 };
694
+ const promptTokens = estimateTokens(prompt);
695
+ const left = limit - used - promptTokens;
696
+ if (left < MIN_REPLY_TOKENS) {
697
+ return {
698
+ allowed: false,
699
+ 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}).`
700
+ };
701
+ }
702
+ return { allowed: true, maxReplyTokens: Math.min(left, MAX_REPLY_TOKENS) };
703
+ }
704
+ function reported(value) {
705
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
706
+ }
707
+ function countCallTokens(limit, prompt, reply) {
708
+ const promptTokens = reply.usage?.prompt_tokens;
709
+ const completionTokens = reply.usage?.completion_tokens;
710
+ if (limit === void 0) {
711
+ return { promptTokens: promptTokens ?? 0, completionTokens: completionTokens ?? 0, estimated: false };
712
+ }
713
+ return {
714
+ promptTokens: reported(promptTokens) ? promptTokens : estimateTokens(prompt),
715
+ completionTokens: reported(completionTokens) ? completionTokens : estimateTokens(reply.content),
716
+ estimated: !reported(promptTokens) || !reported(completionTokens)
717
+ };
718
+ }
661
719
  }
662
720
  });
663
721
 
@@ -1682,7 +1740,8 @@ var require_dist5 = __commonJS({
1682
1740
  role: "user",
1683
1741
  content: prompt
1684
1742
  }
1685
- ]
1743
+ ],
1744
+ ...options?.maxTokens !== void 0 ? { max_tokens: options.maxTokens } : {}
1686
1745
  },
1687
1746
  {
1688
1747
  headers: {
@@ -1694,10 +1753,12 @@ var require_dist5 = __commonJS({
1694
1753
  if (response.data?.error) {
1695
1754
  throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1696
1755
  }
1756
+ const choice = response.data.choices[0];
1697
1757
  return {
1698
- content: response.data.choices[0].message.content,
1758
+ content: choice.message.content ?? "",
1699
1759
  model,
1700
- usage: response.data.usage
1760
+ usage: response.data.usage,
1761
+ ...choice.finish_reason === "length" ? { truncated: true } : {}
1701
1762
  };
1702
1763
  } catch (error) {
1703
1764
  let msg = error.message;
@@ -1751,13 +1812,30 @@ var require_dist6 = __commonJS({
1751
1812
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1752
1813
  var index_exports = {};
1753
1814
  __export(index_exports, {
1815
+ FILE_REQUEST_EXAMPLE: () => FILE_REQUEST_EXAMPLE,
1816
+ MAX_FILES_PER_REQUEST: () => MAX_FILES_PER_REQUEST,
1817
+ MAX_REQUESTED_FILE_CHARS: () => MAX_REQUESTED_FILE_CHARS,
1818
+ MAX_REQUEST_CHARS: () => MAX_REQUEST_CHARS,
1754
1819
  buildAnalysisPrompt: () => buildAnalysisPrompt,
1820
+ fileRequestInstructions: () => fileRequestInstructions,
1755
1821
  truncateLogs: () => truncateLogs
1756
1822
  });
1757
1823
  module2.exports = __toCommonJS(index_exports);
1758
1824
  var import_shared4 = require_dist2();
1759
1825
  var import_fs2 = __toESM2(require("fs"));
1760
1826
  var import_path3 = __toESM2(require("path"));
1827
+ var MAX_FILES_PER_REQUEST = 5;
1828
+ var MAX_REQUESTED_FILE_CHARS = 2e4;
1829
+ var MAX_REQUEST_CHARS = 6e4;
1830
+ var FILE_REQUEST_EXAMPLE = '{"tool": "read_file", "files": [{"path": "src/types.ts"}, {"path": "src/server.ts", "startLine": 200, "endLine": 320}]}';
1831
+ function fileRequestInstructions() {
1832
+ return `### Asking for files
1833
+ If you cannot write a correct fix without seeing a file that is not shown above, reply with ONLY a request like this instead of a fix:
1834
+ ${FILE_REQUEST_EXAMPLE}
1835
+ - "path" is relative to the project root. "startLine" and "endLine" are optional.
1836
+ - One request may ask for at most ${MAX_FILES_PER_REQUEST} files. At most ${MAX_REQUESTED_FILE_CHARS} characters of each file, and ${MAX_REQUEST_CHARS} in total, are returned; use line ranges to see the rest.
1837
+ - Secret files, .git and node_modules are never shown.`;
1838
+ }
1761
1839
  var MAX_LOG_CHARS = 2e4;
1762
1840
  var MAX_FILE_CHARS = 2e4;
1763
1841
  var MAX_CONTEXT_CHARS = 6e4;
@@ -1930,6 +2008,9 @@ ${w}`).join("\n\n")}
1930
2008
  }
1931
2009
  compilerLogs = truncateLogs(compilerLogs);
1932
2010
  const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
2011
+ const fileRequestSection = options.fileRequests ? `
2012
+
2013
+ ${fileRequestInstructions()}` : "";
1933
2014
  return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1934
2015
 
1935
2016
  A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
@@ -1963,7 +2044,7 @@ Critical rules:
1963
2044
  - Each "search" must be an EXACT character-for-character substring of that file's current content.
1964
2045
  - Each "replace" must be syntactically valid code.
1965
2046
  - If two patches target the same file, list them in the order they should be applied, and make sure each "search" reflects the file's content *after* the previous patch in this list has been applied to it.
1966
- - Do NOT add backticks, markdown, or any text outside the JSON object.`;
2047
+ - Do NOT add backticks, markdown, or any text outside the JSON object.${fileRequestSection}`;
1967
2048
  }
1968
2049
  }
1969
2050
  });
@@ -2111,6 +2192,21 @@ var require_dist7 = __commonJS({
2111
2192
  reducer: (_, value) => value,
2112
2193
  default: () => false
2113
2194
  }),
2195
+ /** The most AI tokens the run may use (undefined = no limit) */
2196
+ maxTokens: (0, import_langgraph.Annotation)({
2197
+ reducer: (_, value) => value,
2198
+ default: () => void 0
2199
+ }),
2200
+ /** True once any token count is an estimate because the model did not report it */
2201
+ tokensEstimated: (0, import_langgraph.Annotation)({
2202
+ reducer: (previous, estimated) => previous || estimated,
2203
+ default: () => false
2204
+ }),
2205
+ /** Why the run stopped for lack of token budget, or null when it did not */
2206
+ budgetStop: (0, import_langgraph.Annotation)({
2207
+ reducer: (_, value) => value,
2208
+ default: () => null
2209
+ }),
2114
2210
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
2115
2211
  timeoutMs: (0, import_langgraph.Annotation)({
2116
2212
  reducer: (_, value) => value,
@@ -2166,13 +2262,27 @@ var require_dist7 = __commonJS({
2166
2262
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
2167
2263
  }
2168
2264
  async function analyzeNode(state) {
2265
+ const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2266
+ const used = state.promptTokens + state.completionTokens;
2267
+ const budget = (0, import_shared4.checkBudget)(state.maxTokens, used, prompt);
2268
+ if (!budget.allowed) {
2269
+ console.log(`
2270
+ [BugZero] ${budget.reason} Stopping before attempt ${state.attempts + 1}.`);
2271
+ return { budgetStop: budget.reason };
2272
+ }
2169
2273
  console.log(
2170
2274
  `
2171
2275
  [BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
2172
2276
  );
2173
- const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2174
- const result = await provider.invoke(prompt, { cwd: state.cwd });
2277
+ const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
2175
2278
  const response = result.content;
2279
+ const tokens = (0, import_shared4.countCallTokens)(state.maxTokens, prompt, result);
2280
+ if (state.maxTokens !== void 0) {
2281
+ const total = used + tokens.promptTokens + tokens.completionTokens;
2282
+ const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
2283
+ console.log(`[BugZero] Token budget: ${total} of ${state.maxTokens} used${note}.`);
2284
+ if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
2285
+ }
2176
2286
  let fixSuggestion = null;
2177
2287
  try {
2178
2288
  const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
@@ -2195,8 +2305,9 @@ var require_dist7 = __commonJS({
2195
2305
  fixSuggestion,
2196
2306
  attempts: state.attempts + 1,
2197
2307
  modelUsed: result.model,
2198
- promptTokens: result.usage?.prompt_tokens ?? 0,
2199
- completionTokens: result.usage?.completion_tokens ?? 0
2308
+ promptTokens: tokens.promptTokens,
2309
+ completionTokens: tokens.completionTokens,
2310
+ tokensEstimated: tokens.estimated
2200
2311
  };
2201
2312
  }
2202
2313
  function patchFailure(state, error) {
@@ -2315,7 +2426,10 @@ Any other files from that same suggestion were rolled back to keep the change at
2315
2426
  }
2316
2427
  return "analyze";
2317
2428
  }
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();
2429
+ function afterAnalyze(state) {
2430
+ return state.budgetStop ? import_langgraph2.END : "apply_fix";
2431
+ }
2432
+ 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
2433
  function runRepairWorkflow(input) {
2320
2434
  const { initialStep, ...rest } = input;
2321
2435
  return workflow.invoke(
@@ -2373,6 +2487,7 @@ var require_dist8 = __commonJS({
2373
2487
  orchestrateAndFix: () => orchestrateAndFix2,
2374
2488
  resolveFocusTests: () => resolveFocusTests,
2375
2489
  resolveMaxAttempts: () => resolveMaxAttempts2,
2490
+ resolveMaxTokens: () => resolveMaxTokens2,
2376
2491
  resolvePatience: () => resolvePatience2,
2377
2492
  resolveTimeoutMs: () => resolveTimeoutMs2
2378
2493
  });
@@ -2545,6 +2660,15 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2545
2660
  }
2546
2661
  return configured;
2547
2662
  }
2663
+ function resolveMaxTokens2(flag, configured) {
2664
+ const source = flag !== void 0 ? "--max-tokens" : "maxTokens in .bugzerorc";
2665
+ const value = flag !== void 0 ? flag : configured;
2666
+ if (value === void 0) return void 0;
2667
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
2668
+ throw new Error(`${source} must be a whole number of 0 or more, where 0 means no limit (received ${JSON.stringify(value) ?? String(value)}).`);
2669
+ }
2670
+ return value === 0 ? void 0 : value;
2671
+ }
2548
2672
  var DEFAULT_PATIENCE = 2;
2549
2673
  function resolvePatience2(flag, configured) {
2550
2674
  const source = flag !== void 0 ? "--patience" : "patience in .bugzerorc";
@@ -2564,8 +2688,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2564
2688
  }
2565
2689
  var import_ai_provider = require_dist5();
2566
2690
  var REPORT_FILENAME2 = "bugzero-report.md";
2567
- function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter) {
2691
+ function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter, budgetStop) {
2568
2692
  const plural = declined === 1 ? "fix" : "fixes";
2693
+ if (budgetStop !== void 0) {
2694
+ const base2 = `Stopped: ${budgetStop} Raise it with --max-tokens.`;
2695
+ return declined > 0 ? `${base2} You declined ${declined} proposed ${plural}.` : base2;
2696
+ }
2569
2697
  if (declined > 0 && !appliedAnything) {
2570
2698
  return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2571
2699
  }
@@ -2602,6 +2730,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2602
2730
  const config = (0, import_config2.getLocalConfig)(cwd);
2603
2731
  const patience = resolvePatience2(options.patience, config.patience);
2604
2732
  const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
2733
+ const maxTokens = resolveMaxTokens2(options.maxTokens, config.maxTokens);
2605
2734
  console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
2606
2735
  const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
2607
2736
  if (pipelineResult.success) {
@@ -2632,19 +2761,21 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2632
2761
  }
2633
2762
  if (options.dryRun) {
2634
2763
  console.log("[BugZero] Dry-run mode \u2014 skipping AI fix.");
2635
- await writeReport(cwd, "rescue", {
2764
+ const spend2 = await writeReport(cwd, "rescue", {
2636
2765
  success: false,
2637
2766
  attempts: 0,
2638
2767
  maxAttempts,
2639
2768
  error: "Dry-run: analysis complete, no files modified.",
2640
2769
  rawOutput: pipelineResult.output,
2641
- dryRun: true
2770
+ dryRun: true,
2771
+ maxTokens
2642
2772
  });
2643
2773
  return {
2644
2774
  success: false,
2645
2775
  attempts: 0,
2646
2776
  finalOutput: pipelineResult.output,
2647
- error: "Dry-run: analysis complete, no files modified."
2777
+ error: "Dry-run: analysis complete, no files modified.",
2778
+ ...tokenBudgetUse(maxTokens, spend2)
2648
2779
  };
2649
2780
  }
2650
2781
  const finalState = await (0, import_agents.runRepairWorkflow)({
@@ -2655,6 +2786,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2655
2786
  approve: options.approve,
2656
2787
  patience,
2657
2788
  focusTests,
2789
+ maxTokens,
2658
2790
  initialStep: pipelineResult.step
2659
2791
  });
2660
2792
  const result = {
@@ -2666,15 +2798,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2666
2798
  maxAttempts,
2667
2799
  finalState.declinedFixes ?? 0,
2668
2800
  Boolean(finalState.appliedFix),
2669
- finalState.stoppedForNoProgress ? patience : void 0
2801
+ finalState.stoppedForNoProgress ? patience : void 0,
2802
+ finalState.budgetStop ?? void 0
2670
2803
  ),
2671
- stoppedEarly: finalState.stoppedForNoProgress ? "no-progress" : void 0,
2804
+ stoppedEarly: finalState.budgetStop ? "token-budget" : finalState.stoppedForNoProgress ? "no-progress" : void 0,
2672
2805
  declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2673
2806
  modelUsed: finalState.modelUsed,
2674
2807
  promptTokens: finalState.promptTokens,
2675
2808
  completionTokens: finalState.completionTokens
2676
2809
  };
2677
- await writeReport(cwd, "rescue", {
2810
+ const spend = await writeReport(cwd, "rescue", {
2678
2811
  success: result.success,
2679
2812
  attempts: result.attempts,
2680
2813
  maxAttempts,
@@ -2683,9 +2816,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2683
2816
  rawOutput: result.finalOutput,
2684
2817
  modelUsed: result.modelUsed,
2685
2818
  promptTokens: result.promptTokens,
2686
- completionTokens: result.completionTokens
2819
+ completionTokens: result.completionTokens,
2820
+ maxTokens,
2821
+ tokensUsed: (result.promptTokens ?? 0) + (result.completionTokens ?? 0),
2822
+ tokensEstimated: finalState.tokensEstimated
2687
2823
  });
2688
- return result;
2824
+ return { ...result, ...tokenBudgetUse(maxTokens, spend) };
2825
+ }
2826
+ function tokenBudgetUse(maxTokens, spend) {
2827
+ if (maxTokens === void 0) return {};
2828
+ return { tokenBudget: { limit: maxTokens, used: spend.tokensUsed, estimated: spend.tokensEstimated } };
2689
2829
  }
2690
2830
  function formatPatchesMarkdown(appliedFix) {
2691
2831
  return appliedFix.patches.map(
@@ -2705,6 +2845,30 @@ ${p.replace}
2705
2845
  async function writeReport(cwd, type, data) {
2706
2846
  let content = "";
2707
2847
  const provider = new import_ai_provider.OpenRouterProvider();
2848
+ const spend = { tokensUsed: data.tokensUsed ?? 0, tokensEstimated: data.tokensEstimated ?? false };
2849
+ const askForReport = async (prompt, announcement) => {
2850
+ const budget = (0, import_shared22.checkBudget)(data.maxTokens, spend.tokensUsed, prompt);
2851
+ if (!budget.allowed) {
2852
+ console.log(`[BugZero] ${budget.reason} Writing the report without the AI.`);
2853
+ throw new Error(budget.reason);
2854
+ }
2855
+ console.log(announcement);
2856
+ const result = await provider.invoke(prompt, { cwd, maxTokens: budget.maxReplyTokens });
2857
+ if (data.maxTokens === void 0) return result;
2858
+ const cost = (0, import_shared22.countCallTokens)(data.maxTokens, prompt, result);
2859
+ spend.tokensUsed += cost.promptTokens + cost.completionTokens;
2860
+ spend.tokensEstimated ||= cost.estimated;
2861
+ if (result.content.trim() === "") {
2862
+ throw new Error("The AI returned an empty reply within the token budget.");
2863
+ }
2864
+ if (!result.truncated) return result;
2865
+ return { ...result, content: `${result.content}
2866
+
2867
+ > \u26A0\uFE0F This AI-written text was cut off by its length limit (see --max-tokens).` };
2868
+ };
2869
+ const aiNote = (reason) => data.maxTokens === void 0 ? "" : `
2870
+ *The AI did not write this report: ${reason}*
2871
+ `;
2708
2872
  if (type === "hunt") {
2709
2873
  const { build, lint, test } = data;
2710
2874
  if (!build.success || !lint.success || !test.success) {
@@ -2788,9 +2952,11 @@ ${logs}
2788
2952
 
2789
2953
  Your project already passes its build, lint, and tests, so BugZero made no changes and did not call an AI model.`;
2790
2954
  } else if (data.dryRun) {
2791
- console.log("[BugZero] Calling AI to diagnose the detected errors and write report...");
2792
2955
  try {
2793
- const result = await provider.invoke(buildDryRunPrompt(cwd, rawOutput ?? ""), { cwd });
2956
+ const result = await askForReport(
2957
+ buildDryRunPrompt(cwd, rawOutput ?? ""),
2958
+ "[BugZero] Calling AI to diagnose the detected errors and write report..."
2959
+ );
2794
2960
  content = result.content + buildDryRunMetadata(result);
2795
2961
  } catch (e) {
2796
2962
  content = buildDryRunFallbackReport({
@@ -2801,10 +2967,9 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2801
2967
  });
2802
2968
  }
2803
2969
  } else if (success && appliedFix) {
2804
- console.log("[BugZero] Calling AI to write solution summary report...");
2805
2970
  const prompt = buildRescueSuccessPrompt({ cwd, attempts, appliedFix });
2806
2971
  try {
2807
- const result = await provider.invoke(prompt, { cwd });
2972
+ const result = await askForReport(prompt, "[BugZero] Calling AI to write solution summary report...");
2808
2973
  content = result.content;
2809
2974
  content += `
2810
2975
 
@@ -2823,7 +2988,7 @@ Your project already passes its build, lint, and tests, so BugZero made no chang
2823
2988
 
2824
2989
  ## \u{1F4CA} Repair Summary
2825
2990
  - **Status:** \u2705 Fixed successfully!
2826
- - **Attempts:** ${attempts} / ${maxAttempts}
2991
+ ${aiNote(e.message)}- **Attempts:** ${attempts} / ${maxAttempts}
2827
2992
  - **AI Brain (Model):** \`${modelUsed || "unknown"}\`
2828
2993
  - **Token Usage:** ${promptTokens !== void 0 && completionTokens !== void 0 ? `Prompt: **${promptTokens}** | Completion: **${completionTokens}** | Total: **${promptTokens + completionTokens}**` : "*N/A*"}
2829
2994
 
@@ -2837,10 +3002,9 @@ ${formatPatchesMarkdown(appliedFix)}
2837
3002
  `;
2838
3003
  }
2839
3004
  } else {
2840
- console.log("[BugZero] Calling AI to analyze unresolved errors and write report...");
2841
3005
  const prompt = buildRescueFailurePrompt({ cwd, attempts, rawOutput });
2842
3006
  try {
2843
- const result = await provider.invoke(prompt, { cwd });
3007
+ const result = await askForReport(prompt, "[BugZero] Calling AI to analyze unresolved errors and write report...");
2844
3008
  content = result.content;
2845
3009
  content += `
2846
3010
 
@@ -2865,7 +3029,7 @@ ${formatPatchesMarkdown(appliedFix)}
2865
3029
 
2866
3030
  ## \u274C Failed to Repair
2867
3031
  **Reason:** ${error || "Max attempts reached without finding a solution."}
2868
-
3032
+ ${aiNote(e.message)}
2869
3033
  ### \u{1F7E5} Unresolved Errors & Logs
2870
3034
  \`\`\`text
2871
3035
  ${rawOutput}
@@ -2874,6 +3038,13 @@ ${rawOutput}
2874
3038
  }
2875
3039
  }
2876
3040
  }
3041
+ if (data.maxTokens !== void 0) {
3042
+ const estimates = spend.tokensEstimated ? " (includes estimates)" : "";
3043
+ content += `
3044
+
3045
+ ---
3046
+ **Token budget:** ${spend.tokensUsed} of ${data.maxTokens} tokens used${estimates}`;
3047
+ }
2877
3048
  content += `
2878
3049
 
2879
3050
  ---
@@ -2895,6 +3066,7 @@ ${rawOutput}
2895
3066
  console.log(content);
2896
3067
  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
3068
  }
3069
+ return spend;
2898
3070
  }
2899
3071
  var import_analyzers2 = require_dist4();
2900
3072
  }
@@ -2955,6 +3127,8 @@ function buildRescueJson(result, info) {
2955
3127
  attempts: result.attempts,
2956
3128
  model: result.modelUsed || null,
2957
3129
  tokens,
3130
+ tokenBudget: result.tokenBudget ?? null,
3131
+ stoppedEarly: result.stoppedEarly ?? null,
2958
3132
  fix: result.appliedFix ? {
2959
3133
  rootCause: result.appliedFix.rootCause,
2960
3134
  explanation: result.appliedFix.explanation,
@@ -3025,10 +3199,18 @@ function createApprovalHandler(io) {
3025
3199
  var import_patcher = __toESM(require_dist3());
3026
3200
  var import_path = __toESM(require("path"));
3027
3201
  var import_shared2 = __toESM(require_dist2());
3202
+ function budgetLines(result) {
3203
+ if (!result.tokenBudget) return [];
3204
+ const { used, limit, estimated } = result.tokenBudget;
3205
+ return [` Token budget: ${used} of ${limit} used${estimated ? " (includes estimates)" : ""}`];
3206
+ }
3028
3207
  function tokenLines(result) {
3029
- if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
3208
+ if (result.promptTokens === void 0 || result.completionTokens === void 0) return budgetLines(result);
3030
3209
  const total = result.promptTokens + result.completionTokens;
3031
- return [` Tokens: Prompt: ${result.promptTokens} | Completion: ${result.completionTokens} | Total: ${total}`];
3210
+ return [
3211
+ ` Tokens: Prompt: ${result.promptTokens} | Completion: ${result.completionTokens} | Total: ${total}`,
3212
+ ...budgetLines(result)
3213
+ ];
3032
3214
  }
3033
3215
  function buildRescueSummary(result, options) {
3034
3216
  if (result.success && result.attempts === 0) {
@@ -3060,6 +3242,7 @@ function buildRescueSummary(result, options) {
3060
3242
  lines: [
3061
3243
  "\u{1F50D} Dry run complete \u2014 failures were detected, but no fixes were attempted and no files were modified.",
3062
3244
  " Re-run without --dry-run to let BugZero attempt a fix.",
3245
+ ...budgetLines(result),
3063
3246
  "",
3064
3247
  "\u{1F449} Full error logs have been listed in the generated report."
3065
3248
  ]
@@ -3170,7 +3353,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
3170
3353
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
3171
3354
  }
3172
3355
  });
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) => {
3356
+ 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
3357
  const json = opts.json === true;
3175
3358
  const printPrompt = opts.printPrompt === true;
3176
3359
  if (json || printPrompt) routeLogsToStderr();
@@ -3181,6 +3364,8 @@ program.command("rescue").description("Detect build failures and automatically a
3181
3364
  const timeoutSeconds = parseTimeout(opts.timeout);
3182
3365
  const patience = opts.patience === void 0 ? void 0 : Number(opts.patience);
3183
3366
  (0, import_core.resolvePatience)(patience, void 0);
3367
+ const maxTokens = opts.maxTokens === void 0 ? void 0 : Number(opts.maxTokens);
3368
+ (0, import_core.resolveMaxTokens)(maxTokens, void 0);
3184
3369
  const focusTests = opts.focusTests === false ? false : void 0;
3185
3370
  const dryRun = opts.dryRun;
3186
3371
  let approve;
@@ -3202,10 +3387,21 @@ program.command("rescue").description("Detect build failures and automatically a
3202
3387
  console.log(` Max attempts: ${maxAttempts}`);
3203
3388
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
3204
3389
  if (patience !== void 0) console.log(` Patience: ${patience === 0 ? "off" : `${patience} attempt(s) without progress`}`);
3390
+ if (maxTokens !== void 0) console.log(` Token budget: ${maxTokens === 0 ? "no limit" : maxTokens}`);
3205
3391
  if (focusTests === false) console.log(` Focus tests: off (the full pipeline runs every time)`);
3206
3392
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
3207
3393
  console.log();
3208
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve, patience, focusTests });
3394
+ const result = await (0, import_core.orchestrateAndFix)({
3395
+ cwd,
3396
+ maxAttempts,
3397
+ dryRun,
3398
+ timeoutSeconds,
3399
+ printPrompt,
3400
+ approve,
3401
+ patience,
3402
+ focusTests,
3403
+ maxTokens
3404
+ });
3209
3405
  if (result.promptPreview !== void 0) {
3210
3406
  if (json) {
3211
3407
  finish(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.60",
3
+ "version": "0.0.62",
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)",