bugzero 0.0.53 → 0.0.54

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 +14 -3
  2. package/dist/index.js +148 -7
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -101,6 +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
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.
105
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.
106
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.
@@ -263,15 +264,25 @@ bugzero rescue --json --dry-run | jq -r '.outcome'
263
264
 
264
265
  ## Configuration
265
266
 
266
- BugZero reads a `.bugzerorc` JSON file in your target project directory to pick up model preferences:
267
+ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick up model preferences and file protection:
267
268
 
268
269
  ```json
269
270
  {
270
- "model": "deepseek/deepseek-chat"
271
+ "model": "deepseek/deepseek-chat",
272
+ "protect": ["config/prod.json", "migrations/**"],
273
+ "allow": [".env.example"]
271
274
  }
272
275
  ```
273
276
 
274
- This file is created automatically when you run `bugzero vibe`.
277
+ | Key | Meaning |
278
+ |---|---|
279
+ | `model` | The OpenRouter model to use. Set it with `bugzero vibe`. |
280
+ | `protect` | Extra files BugZero must never edit, added to the built-in list (see Protected files above). |
281
+ | `allow` | Files from the built-in list that BugZero may edit and read after all, such as `.env.example`. A `protect` pattern still wins. |
282
+
283
+ 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.
284
+
285
+ `bugzero vibe` creates the file if it is missing and only changes `model`, so your other settings are kept.
275
286
 
276
287
  ---
277
288
 
package/dist/index.js CHANGED
@@ -381,6 +381,7 @@ var require_dist = __commonJS({
381
381
  __export(index_exports, {
382
382
  env: () => env,
383
383
  getLocalConfig: () => getLocalConfig,
384
+ getProtectionSettings: () => getProtectionSettings,
384
385
  getSelectedModel: () => getSelectedModel,
385
386
  loadProjectEnv: () => loadProjectEnv2,
386
387
  saveLocalConfig: () => saveLocalConfig
@@ -423,7 +424,6 @@ var require_dist = __commonJS({
423
424
  if (!envPath) return void 0;
424
425
  return applyEnvFile(envPath) ? envPath : void 0;
425
426
  }
426
- loadProjectEnv2(process.cwd());
427
427
  var env = {
428
428
  // Read on access, so a key loaded later by loadProjectEnv() is seen.
429
429
  get openRouterKey() {
@@ -446,7 +446,16 @@ var require_dist = __commonJS({
446
446
  }
447
447
  function saveLocalConfig(config, cwd = process.cwd()) {
448
448
  const configPath = import_path22.default.resolve(cwd, CONFIG_FILENAME);
449
- import_fs22.default.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
449
+ const merged = { ...getLocalConfig(cwd), ...config };
450
+ import_fs22.default.writeFileSync(configPath, JSON.stringify(merged, null, 2), "utf-8");
451
+ }
452
+ function stringList(value) {
453
+ if (!Array.isArray(value)) return [];
454
+ return value.filter((entry) => typeof entry === "string" && entry.trim() !== "");
455
+ }
456
+ function getProtectionSettings(cwd = process.cwd()) {
457
+ const config = getLocalConfig(cwd);
458
+ return { protect: stringList(config.protect), allow: stringList(config.allow) };
450
459
  }
451
460
  function getSelectedModel(cwd = process.cwd()) {
452
461
  const config = getLocalConfig(cwd);
@@ -872,8 +881,12 @@ var require_dist4 = __commonJS({
872
881
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
873
882
  var index_exports = {};
874
883
  __export(index_exports, {
884
+ DEFAULT_PROTECTED_PATTERNS: () => DEFAULT_PROTECTED_PATTERNS,
885
+ DEFAULT_SECRET_PATTERNS: () => DEFAULT_SECRET_PATTERNS,
886
+ createProtectedPathRules: () => createProtectedPathRules,
875
887
  isInsideDirectory: () => isInsideDirectory,
876
888
  isLexicallyInside: () => isLexicallyInside,
889
+ projectRelativePaths: () => projectRelativePaths,
877
890
  resolveInsideProject: () => resolveInsideProject,
878
891
  uniqueFilePaths: () => uniqueFilePaths3
879
892
  });
@@ -922,6 +935,112 @@ var require_dist4 = __commonJS({
922
935
  }
923
936
  return { ok: true, absolutePath };
924
937
  }
938
+ var import_fs22 = __toESM2(require("fs"));
939
+ var import_path22 = __toESM2(require("path"));
940
+ var DEFAULT_SECRET_PATTERNS = [".env", ".env.*", "*.pem", "*.key"];
941
+ var DEFAULT_PROTECTED_PATTERNS = [
942
+ ...DEFAULT_SECRET_PATTERNS,
943
+ ".git/",
944
+ ".github/workflows/",
945
+ ".gitlab-ci.yml",
946
+ ".circleci/",
947
+ "azure-pipelines.yml",
948
+ "bitbucket-pipelines.yml",
949
+ "Jenkinsfile",
950
+ "package-lock.json",
951
+ "pnpm-lock.yaml",
952
+ "yarn.lock",
953
+ "bun.lockb",
954
+ "node_modules/",
955
+ "*.opspilot.bak"
956
+ ];
957
+ function normalizePath(relPath) {
958
+ return relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+/, "").toLowerCase();
959
+ }
960
+ function compilePattern(pattern) {
961
+ if (typeof pattern !== "string") return void 0;
962
+ let p = pattern.trim().replace(/\\/g, "/").toLowerCase();
963
+ if (p === "" || p.startsWith("#")) return void 0;
964
+ const anchored = p.startsWith("/") || p.replace(/\/+$/, "").includes("/");
965
+ p = p.replace(/^(\.\/)+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
966
+ if (p === "") return void 0;
967
+ let source = "";
968
+ for (let i = 0; i < p.length; i++) {
969
+ const c = p[i];
970
+ if (c === "*") {
971
+ if (p[i + 1] === "*") {
972
+ i++;
973
+ if (p[i + 1] === "/") {
974
+ i++;
975
+ source += "(?:.*/)?";
976
+ } else {
977
+ source += ".*";
978
+ }
979
+ } else {
980
+ source += "[^/]*";
981
+ }
982
+ } else if (c === "?") {
983
+ source += "[^/]";
984
+ } else {
985
+ source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
986
+ }
987
+ }
988
+ const regex = new RegExp(`^${anchored ? "" : "(?:.*/)?"}${source}(?:/.*)?$`);
989
+ return { pattern: pattern.trim(), test: (normalizedPath) => regex.test(normalizedPath) };
990
+ }
991
+ function compileAll(patterns) {
992
+ return (patterns ?? []).map(compilePattern).filter((m) => m !== void 0);
993
+ }
994
+ function firstMatch(matchers, normalizedPath) {
995
+ return matchers.find((m) => m.test(normalizedPath));
996
+ }
997
+ function createProtectedPathRules(settings = {}) {
998
+ const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
999
+ const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
1000
+ const extra = compileAll(settings.protect);
1001
+ const allowed = compileAll(settings.allow);
1002
+ return {
1003
+ editBlockedBy(relPath) {
1004
+ const normalized = normalizePath(relPath);
1005
+ const own = firstMatch(extra, normalized);
1006
+ if (own) return own.pattern;
1007
+ if (firstMatch(allowed, normalized)) return void 0;
1008
+ return firstMatch(defaults, normalized)?.pattern;
1009
+ },
1010
+ secretBlockedBy(relPath) {
1011
+ const normalized = normalizePath(relPath);
1012
+ if (firstMatch(allowed, normalized)) return void 0;
1013
+ return firstMatch(secrets, normalized)?.pattern;
1014
+ }
1015
+ };
1016
+ }
1017
+ function toRelative(root, target) {
1018
+ return import_path22.default.relative(root, target).split(import_path22.default.sep).join("/");
1019
+ }
1020
+ function realPathAllowingMissing(target) {
1021
+ let current = import_path22.default.resolve(target);
1022
+ const rest = [];
1023
+ while (true) {
1024
+ try {
1025
+ return import_path22.default.join(import_fs22.default.realpathSync.native(current), ...rest.reverse());
1026
+ } catch {
1027
+ const parent = import_path22.default.dirname(current);
1028
+ if (parent === current) return void 0;
1029
+ rest.push(import_path22.default.basename(current));
1030
+ current = parent;
1031
+ }
1032
+ }
1033
+ }
1034
+ function projectRelativePaths(cwd, absolutePath) {
1035
+ const paths = [toRelative(import_path22.default.resolve(cwd), import_path22.default.resolve(absolutePath))];
1036
+ const realRoot = realPathAllowingMissing(cwd);
1037
+ const realTarget = realPathAllowingMissing(absolutePath);
1038
+ if (realRoot && realTarget) {
1039
+ const real = toRelative(realRoot, realTarget);
1040
+ if (real !== paths[0] && !real.startsWith("..")) paths.push(real);
1041
+ }
1042
+ return paths;
1043
+ }
925
1044
  }
926
1045
  });
927
1046
 
@@ -1001,7 +1120,7 @@ ${tail}`;
1001
1120
  }
1002
1121
  return null;
1003
1122
  }
1004
- function getContextFiles(logs, cwd) {
1123
+ function getContextFiles(logs, cwd, rules) {
1005
1124
  const candidates = /* @__PURE__ */ new Set();
1006
1125
  const quotedRegex = /['"`]([^'"`\n]+)['"`]/g;
1007
1126
  let match;
@@ -1040,6 +1159,7 @@ ${tail}`;
1040
1159
  if (relPath.includes("node_modules") || relPath.startsWith("build") || relPath.startsWith("dist") || relPath.startsWith(".git")) {
1041
1160
  return;
1042
1161
  }
1162
+ if ((0, import_shared3.projectRelativePaths)(cwd, filePath).some((rel) => rules.secretBlockedBy(rel) !== void 0)) return;
1043
1163
  if (processedFiles.has(filePath)) return;
1044
1164
  if (context.length >= MAX_CONTEXT_CHARS) return;
1045
1165
  processedFiles.add(filePath);
@@ -1118,7 +1238,7 @@ ${content}
1118
1238
  }
1119
1239
  return context;
1120
1240
  }
1121
- function buildAnalysisPrompt(errorOutput, cwd) {
1241
+ function buildAnalysisPrompt(errorOutput, cwd, options = {}) {
1122
1242
  const warningMarker = "\u26A0\uFE0F [BugZero System Warning]";
1123
1243
  let compilerLogs = errorOutput;
1124
1244
  let historySection = "";
@@ -1135,7 +1255,7 @@ ${w}`).join("\n\n")}
1135
1255
  **CRITICAL RULE:** Do NOT suggest modifying or creating the files listed under "Previous Failed Attempts" if they failed with a "File not found" or "Search string not found" error. You must inspect the compiler error logs below to find the actual file that exists and contains the error.`;
1136
1256
  }
1137
1257
  compilerLogs = truncateLogs(compilerLogs);
1138
- const contextSection = getContextFiles(compilerLogs, cwd);
1258
+ const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared3.createProtectedPathRules)());
1139
1259
  return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1140
1260
 
1141
1261
  A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
@@ -1165,6 +1285,7 @@ Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fence
1165
1285
  Critical rules:
1166
1286
  - "patches" must contain at least one entry. Only include more than one when the fix truly requires editing multiple files \u2014 most fixes need just one.
1167
1287
  - Each "filePath" must be a relative path from the project root (no leading /).
1288
+ - Never change secret files (.env and key files), lockfiles, CI workflow files, .git or node_modules. Patches to them are rejected, so fix the problem in another file.
1168
1289
  - Each "search" must be an EXACT character-for-character substring of that file's current content.
1169
1290
  - Each "replace" must be syntactically valid code.
1170
1291
  - 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.
@@ -1381,6 +1502,7 @@ var require_dist6 = __commonJS({
1381
1502
  if (patches.length === 0) {
1382
1503
  return { success: false, error: "No patches to apply.", applied: [] };
1383
1504
  }
1505
+ const protection = options.protection ?? (0, import_shared3.createProtectedPathRules)();
1384
1506
  const absolutePaths = [];
1385
1507
  for (const patch of patches) {
1386
1508
  const resolved = (0, import_shared3.resolveInsideProject)(cwd, patch.filePath);
@@ -1391,6 +1513,16 @@ var require_dist6 = __commonJS({
1391
1513
  applied: []
1392
1514
  };
1393
1515
  }
1516
+ for (const relPath of (0, import_shared3.projectRelativePaths)(cwd, resolved.absolutePath)) {
1517
+ const pattern = protection.editBlockedBy(relPath);
1518
+ if (pattern !== void 0) {
1519
+ return {
1520
+ success: false,
1521
+ error: `Failed to patch "${patch.filePath}": this file is protected (it matches "${pattern}"), so BugZero never edits it. Fix the problem in a different file.`,
1522
+ applied: []
1523
+ };
1524
+ }
1525
+ }
1394
1526
  absolutePaths.push(resolved.absolutePath);
1395
1527
  }
1396
1528
  const originalContent = /* @__PURE__ */ new Map();
@@ -1557,15 +1689,20 @@ var require_dist7 = __commonJS({
1557
1689
  });
1558
1690
  var import_ai_provider = require_dist3();
1559
1691
  var import_prompts = require_dist5();
1692
+ var import_config2 = require_dist();
1560
1693
  var import_patcher = require_dist6();
1561
1694
  var import_analyzers = require_dist2();
1695
+ var import_shared3 = require_dist4();
1562
1696
  var provider = new import_ai_provider.OpenRouterProvider();
1697
+ function protectionFor(cwd) {
1698
+ return (0, import_shared3.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
1699
+ }
1563
1700
  async function analyzeNode(state) {
1564
1701
  console.log(
1565
1702
  `
1566
1703
  [BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
1567
1704
  );
1568
- const prompt = (0, import_prompts.buildAnalysisPrompt)(state.logs, state.cwd);
1705
+ const prompt = (0, import_prompts.buildAnalysisPrompt)(state.logs, state.cwd, { rules: protectionFor(state.cwd) });
1569
1706
  const result = await provider.invoke(prompt, { cwd: state.cwd });
1570
1707
  const response = result.content;
1571
1708
  let fixSuggestion = null;
@@ -1603,7 +1740,10 @@ var require_dist7 = __commonJS({
1603
1740
  const fileList = patches.map((p) => p.filePath).join(", ");
1604
1741
  console.log(`[BugZero] Patching ${patches.length} file${patches.length === 1 ? "" : "s"}: ${fileList}`);
1605
1742
  console.log(`[BugZero] Reason: ${explanation}`);
1606
- const result = (0, import_patcher.applyPatches)(state.cwd, patches, { alreadyBackedUp: state.backedUpFiles });
1743
+ const result = (0, import_patcher.applyPatches)(state.cwd, patches, {
1744
+ alreadyBackedUp: state.backedUpFiles,
1745
+ protection: protectionFor(state.cwd)
1746
+ });
1607
1747
  if (!result.success) {
1608
1748
  console.error(`[BugZero] Patch failed: ${result.error}`);
1609
1749
  const updatedLogs = `${state.logs}
@@ -2298,6 +2438,7 @@ function buildRescueSummary(result, options) {
2298
2438
  }
2299
2439
 
2300
2440
  // src/index.ts
2441
+ (0, import_config.loadProjectEnv)(process.cwd());
2301
2442
  var { version } = JSON.parse(import_fs.default.readFileSync(import_path.default.join(__dirname, "..", "package.json"), "utf-8"));
2302
2443
  var TIMEOUT_DESCRIPTION = "Stop any build/lint/test command that runs longer than this many seconds";
2303
2444
  function parseTimeout(raw) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.53",
3
+ "version": "0.0.54",
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)",