bugzero 0.0.56 → 0.0.58

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 +25 -1
  2. package/dist/index.js +1422 -1109
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ var require_main = __commonJS({
31
31
  "../../node_modules/.pnpm/dotenv@17.4.2/node_modules/dotenv/lib/main.js"(exports2, module2) {
32
32
  "use strict";
33
33
  var fs2 = require("fs");
34
- var path2 = require("path");
34
+ var path3 = require("path");
35
35
  var os = require("os");
36
36
  var crypto = require("crypto");
37
37
  var TIPS = [
@@ -170,7 +170,7 @@ var require_main = __commonJS({
170
170
  possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
171
171
  }
172
172
  } else {
173
- possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
173
+ possibleVaultPath = path3.resolve(process.cwd(), ".env.vault");
174
174
  }
175
175
  if (fs2.existsSync(possibleVaultPath)) {
176
176
  return possibleVaultPath;
@@ -178,7 +178,7 @@ var require_main = __commonJS({
178
178
  return null;
179
179
  }
180
180
  function _resolveHome(envPath) {
181
- return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
181
+ return envPath[0] === "~" ? path3.join(os.homedir(), envPath.slice(1)) : envPath;
182
182
  }
183
183
  function _configVault(options) {
184
184
  const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
@@ -195,7 +195,7 @@ var require_main = __commonJS({
195
195
  return { parsed };
196
196
  }
197
197
  function configDotenv(options) {
198
- const dotenvPath = path2.resolve(process.cwd(), ".env");
198
+ const dotenvPath = path3.resolve(process.cwd(), ".env");
199
199
  let encoding = "utf8";
200
200
  let processEnv = process.env;
201
201
  if (options && options.processEnv != null) {
@@ -223,13 +223,13 @@ var require_main = __commonJS({
223
223
  }
224
224
  let lastError;
225
225
  const parsedAll = {};
226
- for (const path3 of optionPaths) {
226
+ for (const path4 of optionPaths) {
227
227
  try {
228
- const parsed = DotenvModule.parse(fs2.readFileSync(path3, { encoding }));
228
+ const parsed = DotenvModule.parse(fs2.readFileSync(path4, { encoding }));
229
229
  DotenvModule.populate(parsedAll, parsed, options);
230
230
  } catch (e) {
231
231
  if (debug) {
232
- _debug(`failed to load ${path3} ${e.message}`);
232
+ _debug(`failed to load ${path4} ${e.message}`);
233
233
  }
234
234
  lastError = e;
235
235
  }
@@ -242,7 +242,7 @@ var require_main = __commonJS({
242
242
  const shortPaths = [];
243
243
  for (const filePath of optionPaths) {
244
244
  try {
245
- const relative = path2.relative(process.cwd(), filePath);
245
+ const relative = path3.relative(process.cwd(), filePath);
246
246
  shortPaths.push(relative);
247
247
  } catch (e) {
248
248
  if (debug) {
@@ -381,7 +381,7 @@ var require_dist = __commonJS({
381
381
  __export(index_exports, {
382
382
  env: () => env,
383
383
  getLocalConfig: () => getLocalConfig,
384
- getProtectionSettings: () => getProtectionSettings,
384
+ getProtectionSettings: () => getProtectionSettings2,
385
385
  getSelectedModel: () => getSelectedModel,
386
386
  loadProjectEnv: () => loadProjectEnv2,
387
387
  saveLocalConfig: () => saveLocalConfig
@@ -389,17 +389,17 @@ var require_dist = __commonJS({
389
389
  module2.exports = __toCommonJS(index_exports);
390
390
  var import_dotenv = __toESM2(require_main());
391
391
  var import_fs2 = __toESM2(require("fs"));
392
- var import_path2 = __toESM2(require("path"));
392
+ var import_path3 = __toESM2(require("path"));
393
393
  var loadedFromFiles = /* @__PURE__ */ new Map();
394
394
  function findEnvFile(startDir) {
395
- let dir = import_path2.default.resolve(startDir);
395
+ let dir = import_path3.default.resolve(startDir);
396
396
  while (true) {
397
- const envPath = import_path2.default.join(dir, ".env");
397
+ const envPath = import_path3.default.join(dir, ".env");
398
398
  try {
399
399
  if (import_fs2.default.statSync(envPath).isFile()) return envPath;
400
400
  } catch {
401
401
  }
402
- const parent = import_path2.default.dirname(dir);
402
+ const parent = import_path3.default.dirname(dir);
403
403
  if (parent === dir) return void 0;
404
404
  dir = parent;
405
405
  }
@@ -453,7 +453,7 @@ var require_dist = __commonJS({
453
453
  if (!Array.isArray(value)) return [];
454
454
  return value.filter((entry) => typeof entry === "string" && entry.trim() !== "");
455
455
  }
456
- function getProtectionSettings(cwd = process.cwd()) {
456
+ function getProtectionSettings2(cwd = process.cwd()) {
457
457
  const config = getLocalConfig(cwd);
458
458
  return { protect: stringList(config.protect), allow: stringList(config.allow) };
459
459
  }
@@ -464,9 +464,9 @@ var require_dist = __commonJS({
464
464
  }
465
465
  });
466
466
 
467
- // ../../packages/analyzers/dist/index.js
467
+ // ../../packages/shared/dist/index.js
468
468
  var require_dist2 = __commonJS({
469
- "../../packages/analyzers/dist/index.js"(exports2, module2) {
469
+ "../../packages/shared/dist/index.js"(exports2, module2) {
470
470
  "use strict";
471
471
  var __create2 = Object.create;
472
472
  var __defProp2 = Object.defineProperty;
@@ -497,230 +497,189 @@ var require_dist2 = __commonJS({
497
497
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
498
498
  var index_exports = {};
499
499
  __export(index_exports, {
500
- detectPackageManager: () => detectPackageManager3,
501
- getRunScriptCommand: () => getRunScriptCommand,
502
- parseErrors: () => parseErrors,
503
- readScripts: () => readScripts,
504
- runBuild: () => runBuild,
505
- runCommand: () => runCommand,
506
- runLint: () => runLint,
507
- runScript: () => runScript,
508
- runTests: () => runTests,
509
- runValidationPipeline: () => runValidationPipeline
500
+ DEFAULT_PROTECTED_PATTERNS: () => DEFAULT_PROTECTED_PATTERNS,
501
+ DEFAULT_SECRET_PATTERNS: () => DEFAULT_SECRET_PATTERNS,
502
+ createProtectedPathRules: () => createProtectedPathRules2,
503
+ isInsideDirectory: () => isInsideDirectory,
504
+ isLexicallyInside: () => isLexicallyInside,
505
+ projectRelativePaths: () => projectRelativePaths,
506
+ resolveInsideProject: () => resolveInsideProject,
507
+ uniqueFilePaths: () => uniqueFilePaths3
510
508
  });
511
509
  module2.exports = __toCommonJS(index_exports);
510
+ function uniqueFilePaths3(patches) {
511
+ return [...new Set(patches.map((patch) => patch.filePath))];
512
+ }
512
513
  var import_fs2 = __toESM2(require("fs"));
513
514
  var import_path3 = __toESM2(require("path"));
514
- var import_fs3 = __toESM2(require("fs"));
515
- var import_path2 = __toESM2(require("path"));
516
- var VALID_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
517
- var LOCKFILE_MANAGERS = [
518
- { file: "pnpm-workspace.yaml", manager: "pnpm" },
519
- { file: "pnpm-lock.yaml", manager: "pnpm" },
520
- { file: "yarn.lock", manager: "yarn" },
521
- { file: "bun.lockb", manager: "bun" },
522
- { file: "bun.lock", manager: "bun" },
523
- { file: "package-lock.json", manager: "npm" }
524
- ];
525
- function detectPackageManager3(cwd = process.cwd()) {
515
+ function isLexicallyInside(root, target) {
516
+ const relative = import_path3.default.relative(import_path3.default.resolve(root), import_path3.default.resolve(target));
517
+ const escapes = relative === ".." || relative.startsWith(`..${import_path3.default.sep}`) || import_path3.default.isAbsolute(relative);
518
+ return !escapes;
519
+ }
520
+ function isInsideDirectory(root, target) {
521
+ const absoluteTarget = import_path3.default.resolve(target);
522
+ if (!isLexicallyInside(root, absoluteTarget)) return false;
526
523
  try {
527
- const pkgPath = import_path2.default.join(cwd, "package.json");
528
- if (import_fs3.default.existsSync(pkgPath)) {
529
- const pkg = JSON.parse(import_fs3.default.readFileSync(pkgPath, "utf-8"));
530
- if (typeof pkg.packageManager === "string") {
531
- const name = pkg.packageManager.split("@")[0].trim();
532
- if (VALID_MANAGERS.includes(name)) {
533
- return name;
534
- }
535
- }
524
+ let probe = absoluteTarget;
525
+ while (!import_fs2.default.existsSync(probe)) {
526
+ const parent = import_path3.default.dirname(probe);
527
+ if (parent === probe) return false;
528
+ probe = parent;
536
529
  }
530
+ return isLexicallyInside(import_fs2.default.realpathSync.native(root), import_fs2.default.realpathSync.native(probe));
537
531
  } catch {
532
+ return false;
538
533
  }
539
- for (const { file, manager } of LOCKFILE_MANAGERS) {
540
- if (import_fs3.default.existsSync(import_path2.default.join(cwd, file))) return manager;
541
- }
542
- return "npm";
543
534
  }
544
- function getRunScriptCommand(manager, script) {
545
- return `${manager} run ${script}`;
535
+ function resolveInsideProject(cwd, filePath) {
536
+ if (typeof filePath !== "string" || filePath.trim() === "") {
537
+ return { ok: false, error: "The file path is empty. Use a path relative to the project root." };
538
+ }
539
+ if (filePath.includes("\0")) {
540
+ return { ok: false, error: "The file path contains a null character." };
541
+ }
542
+ const absolutePath = import_path3.default.resolve(cwd, filePath);
543
+ if (import_path3.default.resolve(cwd) === absolutePath) {
544
+ return { ok: false, error: `"${filePath}" is the project directory itself, not a file.` };
545
+ }
546
+ if (!isInsideDirectory(cwd, absolutePath)) {
547
+ return {
548
+ ok: false,
549
+ error: `"${filePath}" is outside the project directory. Use a path relative to the project root.`
550
+ };
551
+ }
552
+ return { ok: true, absolutePath };
546
553
  }
547
- var import_child_process = require("child_process");
554
+ var import_fs22 = __toESM2(require("fs"));
548
555
  var import_path22 = __toESM2(require("path"));
549
- var import_tree_kill = __toESM2(require("tree-kill"));
550
- function killProcessTree(pid) {
551
- if (process.platform === "win32") {
552
- const systemRoot = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
553
- const taskkill = import_path22.default.join(systemRoot, "System32", "taskkill.exe");
554
- (0, import_child_process.spawnSync)(taskkill, ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
555
- return;
556
+ var DEFAULT_SECRET_PATTERNS = [".env", ".env.*", "*.pem", "*.key"];
557
+ var DEFAULT_PROTECTED_PATTERNS = [
558
+ ...DEFAULT_SECRET_PATTERNS,
559
+ ".git/",
560
+ ".github/workflows/",
561
+ ".gitlab-ci.yml",
562
+ ".circleci/",
563
+ "azure-pipelines.yml",
564
+ "bitbucket-pipelines.yml",
565
+ "Jenkinsfile",
566
+ "package-lock.json",
567
+ "pnpm-lock.yaml",
568
+ "yarn.lock",
569
+ "bun.lockb",
570
+ "node_modules/",
571
+ "*.opspilot.bak",
572
+ "*.opspilot.bak.sha"
573
+ ];
574
+ function normalizePath(relPath) {
575
+ return relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+/, "").toLowerCase();
576
+ }
577
+ function compilePattern(pattern) {
578
+ if (typeof pattern !== "string") return void 0;
579
+ let p = pattern.trim().replace(/\\/g, "/").toLowerCase();
580
+ if (p === "" || p.startsWith("#")) return void 0;
581
+ const anchored = p.startsWith("/") || p.replace(/\/+$/, "").includes("/");
582
+ p = p.replace(/^(\.\/)+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
583
+ if (p === "") return void 0;
584
+ let source = "";
585
+ for (let i = 0; i < p.length; i++) {
586
+ const c = p[i];
587
+ if (c === "*") {
588
+ if (p[i + 1] === "*") {
589
+ i++;
590
+ if (p[i + 1] === "/") {
591
+ i++;
592
+ source += "(?:.*/)?";
593
+ } else {
594
+ source += ".*";
595
+ }
596
+ } else {
597
+ source += "[^/]*";
598
+ }
599
+ } else if (c === "?") {
600
+ source += "[^/]";
601
+ } else {
602
+ source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
603
+ }
556
604
  }
557
- (0, import_tree_kill.default)(pid, "SIGKILL");
605
+ const regex = new RegExp(`^${anchored ? "" : "(?:.*/)?"}${source}(?:/.*)?$`);
606
+ return { pattern: pattern.trim(), test: (normalizedPath) => regex.test(normalizedPath) };
558
607
  }
559
- var KILL_GRACE_MS = 5e3;
560
- async function runCommand(command, cwd, options = {}) {
561
- const { execa } = await import("execa");
562
- const subprocess = execa(command, {
563
- shell: true,
564
- cwd: cwd ?? process.cwd(),
565
- all: true,
566
- env: {
567
- ...process.env,
568
- CI: "true"
608
+ function compileAll(patterns) {
609
+ return (patterns ?? []).map(compilePattern).filter((m) => m !== void 0);
610
+ }
611
+ function firstMatch(matchers, normalizedPath) {
612
+ return matchers.find((m) => m.test(normalizedPath));
613
+ }
614
+ function createProtectedPathRules2(settings = {}) {
615
+ const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
616
+ const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
617
+ const extra = compileAll(settings.protect);
618
+ const allowed = compileAll(settings.allow);
619
+ return {
620
+ editBlockedBy(relPath) {
621
+ const normalized = normalizePath(relPath);
622
+ const own = firstMatch(extra, normalized);
623
+ if (own) return own.pattern;
624
+ if (firstMatch(allowed, normalized)) return void 0;
625
+ return firstMatch(defaults, normalized)?.pattern;
626
+ },
627
+ secretBlockedBy(relPath) {
628
+ const normalized = normalizePath(relPath);
629
+ if (firstMatch(allowed, normalized)) return void 0;
630
+ return firstMatch(secrets, normalized)?.pattern;
569
631
  }
570
- });
571
- const timedOutResult = (output, confirmedStopped) => {
572
- const seconds = options.timeoutMs / 1e3;
573
- const note = confirmedStopped ? "and was stopped" : "and could not be confirmed stopped";
574
- return {
575
- success: false,
576
- timedOut: true,
577
- output: `${output}
578
-
579
- [BugZero] Command timed out after ${seconds}s ${note}: ${command}`
580
- };
581
632
  };
582
- let timedOut = false;
583
- let timer;
584
- let graceTimer;
585
- const gaveUp = new Promise((resolve) => {
586
- if (options.timeoutMs === void 0) return;
587
- timer = setTimeout(() => {
588
- timedOut = true;
589
- if (subprocess.pid !== void 0) killProcessTree(subprocess.pid);
590
- graceTimer = setTimeout(() => resolve(timedOutResult("", false)), KILL_GRACE_MS);
591
- }, options.timeoutMs);
592
- });
593
- const finished = subprocess.then(
594
- (result) => ({ success: true, output: result.all ?? result.stdout }),
595
- (err) => {
596
- const output = err.all ?? err.stderr ?? err.stdout ?? err.message;
597
- return timedOut ? timedOutResult(output, true) : { success: false, output };
633
+ }
634
+ function toRelative(root, target) {
635
+ return import_path22.default.relative(root, target).split(import_path22.default.sep).join("/");
636
+ }
637
+ function realPathAllowingMissing(target) {
638
+ let current = import_path22.default.resolve(target);
639
+ const rest = [];
640
+ while (true) {
641
+ try {
642
+ return import_path22.default.join(import_fs22.default.realpathSync.native(current), ...rest.reverse());
643
+ } catch {
644
+ const parent = import_path22.default.dirname(current);
645
+ if (parent === current) return void 0;
646
+ rest.push(import_path22.default.basename(current));
647
+ current = parent;
598
648
  }
599
- );
600
- try {
601
- return await Promise.race([finished, gaveUp]);
602
- } finally {
603
- clearTimeout(timer);
604
- clearTimeout(graceTimer);
605
649
  }
606
650
  }
607
- function readScripts(cwd = process.cwd()) {
608
- try {
609
- const pkgPath = import_path3.default.join(cwd, "package.json");
610
- if (!import_fs2.default.existsSync(pkgPath)) return [];
611
- const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
612
- if (typeof pkg.scripts !== "object" || pkg.scripts === null) return [];
613
- return Object.keys(pkg.scripts);
614
- } catch {
615
- return [];
651
+ function projectRelativePaths(cwd, absolutePath) {
652
+ const paths = [toRelative(import_path22.default.resolve(cwd), import_path22.default.resolve(absolutePath))];
653
+ const realRoot = realPathAllowingMissing(cwd);
654
+ const realTarget = realPathAllowingMissing(absolutePath);
655
+ if (realRoot && realTarget) {
656
+ const real = toRelative(realRoot, realTarget);
657
+ if (real !== paths[0] && !real.startsWith("..")) paths.push(real);
616
658
  }
659
+ return paths;
617
660
  }
618
- async function runScript(script, cwd, options) {
619
- if (!readScripts(cwd).includes(script)) {
620
- return { success: true, output: "", skipped: true };
621
- }
622
- return runCommand(getRunScriptCommand(detectPackageManager3(cwd), script), cwd, options);
623
- }
624
- var runBuild = (cwd, options) => runScript("build", cwd, options);
625
- var runLint = (cwd, options) => runScript("lint", cwd, options);
626
- var runTests = (cwd, options) => runScript("test", cwd, options);
627
- var TS_ERROR_RE = /^(.+)\((\d+),(\d+)\):\s+error\s+TS\d+:\s+(.+)$/gm;
628
- var ESLINT_ERROR_RE = /^\s+(\d+):(\d+)\s+error\s+(.+)$/gm;
629
- var JEST_FAIL_RE = /● (.+)/g;
630
- var JEST_FILE_RE = /FAIL\s+([\w/\\.\-]+)/g;
631
- function parseErrors(output) {
632
- const errors = [];
633
- const tsMatches = [...output.matchAll(TS_ERROR_RE)];
634
- for (const m of tsMatches) {
635
- errors.push({
636
- type: "typescript",
637
- file: m[1].trim(),
638
- line: parseInt(m[2], 10),
639
- column: parseInt(m[3], 10),
640
- message: m[4].trim(),
641
- raw: m[0]
642
- });
643
- }
644
- if (errors.length > 0) return errors;
645
- const eslintMatches = [...output.matchAll(ESLINT_ERROR_RE)];
646
- for (const m of eslintMatches) {
647
- errors.push({
648
- type: "eslint",
649
- line: parseInt(m[1], 10),
650
- column: parseInt(m[2], 10),
651
- message: m[3].trim(),
652
- raw: m[0]
653
- });
654
- }
655
- if (errors.length > 0) return errors;
656
- const jestFiles = [...output.matchAll(JEST_FILE_RE)].map((m) => m[1]);
657
- const jestFails = [...output.matchAll(JEST_FAIL_RE)];
658
- for (const m of jestFails) {
659
- errors.push({
660
- type: "jest",
661
- file: jestFiles[0],
662
- message: m[1].trim(),
663
- raw: m[0]
664
- });
665
- }
666
- if (errors.length > 0) return errors;
667
- if (output.trim()) {
668
- errors.push({
669
- type: "unknown",
670
- message: output.slice(0, 500),
671
- raw: output
672
- });
673
- }
674
- return errors;
675
- }
676
- var STEPS = [
677
- { step: "build", label: "build", run: runBuild },
678
- { step: "lint", label: "lint", run: runLint },
679
- { step: "test", label: "tests", run: runTests }
680
- ];
681
- async function runValidationPipeline(cwd, options) {
682
- const targetCwd = cwd ?? process.cwd();
683
- const scripts = readScripts(targetCwd);
684
- let ranAnyStep = false;
685
- for (const { step, label, run } of STEPS) {
686
- if (!scripts.includes(step)) {
687
- console.log(`[BugZero] Skipping ${label}: no "${step}" script in package.json.`);
688
- continue;
689
- }
690
- ranAnyStep = true;
691
- console.log(`[BugZero] Running ${label}...`);
692
- const result = await run(targetCwd, options);
693
- if (!result.success) {
694
- return { success: false, step, output: result.output };
695
- }
696
- }
697
- if (!ranAnyStep) {
698
- console.warn(`[BugZero] No build, lint, or test scripts found in package.json \u2014 nothing to validate.`);
699
- }
700
- return { success: true, step: "none", output: "" };
701
- }
702
- }
703
- });
704
-
705
- // ../../packages/ai-provider/dist/index.js
706
- var require_dist3 = __commonJS({
707
- "../../packages/ai-provider/dist/index.js"(exports2, module2) {
708
- "use strict";
709
- var __create2 = Object.create;
710
- var __defProp2 = Object.defineProperty;
711
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
712
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
713
- var __getProtoOf2 = Object.getPrototypeOf;
714
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
715
- var __export = (target, all) => {
716
- for (var name in all)
717
- __defProp2(target, name, { get: all[name], enumerable: true });
718
- };
719
- var __copyProps2 = (to, from, except, desc) => {
720
- if (from && typeof from === "object" || typeof from === "function") {
721
- for (let key of __getOwnPropNames2(from))
722
- if (!__hasOwnProp2.call(to, key) && key !== except)
723
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
661
+ }
662
+ });
663
+
664
+ // ../../packages/patcher/dist/index.js
665
+ var require_dist3 = __commonJS({
666
+ "../../packages/patcher/dist/index.js"(exports2, module2) {
667
+ "use strict";
668
+ var __create2 = Object.create;
669
+ var __defProp2 = Object.defineProperty;
670
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
671
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
672
+ var __getProtoOf2 = Object.getPrototypeOf;
673
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
674
+ var __export = (target, all) => {
675
+ for (var name in all)
676
+ __defProp2(target, name, { get: all[name], enumerable: true });
677
+ };
678
+ var __copyProps2 = (to, from, except, desc) => {
679
+ if (from && typeof from === "object" || typeof from === "function") {
680
+ for (let key of __getOwnPropNames2(from))
681
+ if (!__hasOwnProp2.call(to, key) && key !== except)
682
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
724
683
  }
725
684
  return to;
726
685
  };
@@ -735,318 +694,576 @@ var require_dist3 = __commonJS({
735
694
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
736
695
  var index_exports = {};
737
696
  __export(index_exports, {
738
- OpenRouterProvider: () => OpenRouterProvider,
739
- getErrorHints: () => getErrorHints
697
+ applyPatch: () => applyPatch,
698
+ applyPatches: () => applyPatches,
699
+ findBackups: () => findBackups,
700
+ findMatch: () => findMatch,
701
+ fingerprintOf: () => fingerprintOf,
702
+ lineSimilarity: () => lineSimilarity,
703
+ patchContent: () => patchContent,
704
+ previewPatches: () => previewPatches,
705
+ renderChangesFromBackups: () => renderChangesFromBackups2,
706
+ renderUnifiedDiff: () => renderUnifiedDiff,
707
+ resolvePatchTargets: () => resolvePatchTargets,
708
+ undoChanges: () => undoChanges2
740
709
  });
741
710
  module2.exports = __toCommonJS(index_exports);
742
- var import_axios = __toESM2(require("axios"));
743
711
  var import_fs2 = __toESM2(require("fs"));
744
- var import_path2 = __toESM2(require("path"));
745
- var CREDITS_PATTERN = /insufficient credits|credit balance|add more credits|requires more credits|token_limit_exceeded/i;
746
- var CONTEXT_PATTERN = /context length|context window|maximum context|context_length_exceeded|string_too_long|too many tokens|reduce the length/i;
747
- var MODEL_PATTERN = /not a valid model|no endpoints found|model.{0,40}(not found|does not exist|unavailable)/i;
748
- function getErrorHints({ status, message, model }) {
749
- if (status === 401) {
750
- return ["\u{1F449} Please check if your OPENROUTER_API_KEY is correct and active."];
751
- }
752
- if (status === 402 || CREDITS_PATTERN.test(message)) {
753
- return [
754
- "\u{1F449} Your OpenRouter credit balance is too low for this request.",
755
- " Add credits at https://openrouter.ai/settings/credits, or run 'bugzero vibe' to switch to a cheaper model",
756
- " (models that cost nothing are listed at https://openrouter.ai/models?max_price=0)."
757
- ];
758
- }
759
- if (status === 429) {
760
- return [
761
- "\u{1F449} OpenRouter is rate limiting these requests. Wait a moment and try again.",
762
- " Free models have stricter limits; run 'bugzero vibe' to switch models, or add credits to raise them."
763
- ];
764
- }
765
- if (CONTEXT_PATTERN.test(message)) {
766
- return [
767
- `\u{1F449} The prompt was too large for the context window of "${model}".`,
768
- " Run 'bugzero vibe' to pick a model with a larger context window, or try again on a smaller failing scope."
769
- ];
770
- }
771
- if (status === 404 || MODEL_PATTERN.test(message)) {
772
- return [
773
- `\u{1F449} The model "${model}" isn't available on OpenRouter (it wasn't found, or no provider currently serves it).`,
774
- " Run 'bugzero vibe' to choose a different model."
775
- ];
712
+ var import_path3 = __toESM2(require("path"));
713
+ var SIMILARITY_THRESHOLD = 0.85;
714
+ var AMBIGUITY_MARGIN = 0.05;
715
+ var MAX_LINES_FOR_SIMILARITY_PASS = 2e4;
716
+ function splitLinesWithOffsets(text) {
717
+ const lines = [];
718
+ let start = 0;
719
+ for (let i = 0; i < text.length; i++) {
720
+ if (text[i] === "\n") {
721
+ let end = i;
722
+ if (end > start && text[end - 1] === "\r") end -= 1;
723
+ lines.push({ text: text.slice(start, end), start, end });
724
+ start = i + 1;
725
+ }
776
726
  }
777
- return [];
727
+ lines.push({ text: text.slice(start), start, end: text.length });
728
+ return lines;
778
729
  }
779
- function resolveModel(cwd) {
780
- try {
781
- const configPath = import_path2.default.resolve(cwd ?? process.cwd(), ".bugzerorc");
782
- if (import_fs2.default.existsSync(configPath)) {
783
- const config = JSON.parse(import_fs2.default.readFileSync(configPath, "utf-8"));
784
- if (config.model) return config.model;
730
+ function normalizeLine(line) {
731
+ return line.trim().replace(/\s+/g, " ");
732
+ }
733
+ function levenshtein(a, b) {
734
+ const m = a.length;
735
+ const n = b.length;
736
+ if (m === 0) return n;
737
+ if (n === 0) return m;
738
+ const dp = new Array(n + 1);
739
+ for (let j = 0; j <= n; j++) dp[j] = j;
740
+ for (let i = 1; i <= m; i++) {
741
+ let prev = dp[0];
742
+ dp[0] = i;
743
+ for (let j = 1; j <= n; j++) {
744
+ const temp = dp[j];
745
+ dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j], dp[j - 1]);
746
+ prev = temp;
785
747
  }
786
- } catch {
787
748
  }
788
- return "deepseek/deepseek-chat";
749
+ return dp[n];
789
750
  }
790
- var OpenRouterProvider = class {
791
- async invoke(prompt, options) {
792
- const model = resolveModel(options?.cwd);
793
- const apiKey = process.env.OPENROUTER_API_KEY;
794
- if (!apiKey) {
795
- console.error(`
796
- \u274C [BugZero] Error: OPENROUTER_API_KEY environment variable is not set.`);
797
- console.error(`\u{1F449} Please configure it using one of the following methods:`);
798
- console.error(` - On macOS/Linux: export OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
799
- console.error(` - On Windows (PowerShell): $env:OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
800
- console.error(` - Or add it to a .env file at the root of the project you are fixing:`);
801
- console.error(` OPENROUTER_API_KEY=your_openrouter_api_key_here
802
- `);
803
- throw new Error("Missing OPENROUTER_API_KEY environment variable.");
804
- }
805
- try {
806
- const response = await import_axios.default.post(
807
- "https://openrouter.ai/api/v1/chat/completions",
808
- {
809
- model,
810
- messages: [
811
- {
812
- role: "user",
813
- content: prompt
814
- }
815
- ]
816
- },
817
- {
818
- headers: {
819
- Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
820
- "Content-Type": "application/json"
821
- }
822
- }
823
- );
824
- if (response.data?.error) {
825
- throw new Error(response.data.error.message || JSON.stringify(response.data.error));
826
- }
827
- return {
828
- content: response.data.choices[0].message.content,
829
- model,
830
- usage: response.data.usage
831
- };
832
- } catch (error) {
833
- let msg = error.message;
834
- if (error.response?.data?.error?.message) {
835
- msg = error.response.data.error.message;
836
- } else if (error.response?.data?.message) {
837
- msg = error.response.data.message;
751
+ function lineSimilarity(a, b) {
752
+ const maxLen = Math.max(a.length, b.length);
753
+ if (maxLen === 0) return 1;
754
+ return 1 - levenshtein(a, b) / maxLen;
755
+ }
756
+ function findWhitespaceNormalizedMatch(content, search) {
757
+ const searchLines = search.split(/\r\n|\n/).map(normalizeLine);
758
+ const contentLines = splitLinesWithOffsets(content);
759
+ if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
760
+ const normalizedContentLines = contentLines.map((l) => normalizeLine(l.text));
761
+ for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
762
+ let matches = true;
763
+ for (let j = 0; j < searchLines.length; j++) {
764
+ if (normalizedContentLines[i + j] !== searchLines[j]) {
765
+ matches = false;
766
+ break;
838
767
  }
839
- console.error(`
840
- \u274C [BugZero] OpenRouter API Error: ${msg}`);
841
- const hints = getErrorHints({ status: error.response?.status, message: msg, model });
842
- for (const line of hints) console.error(line);
843
- if (hints.length > 0) console.error();
844
- throw new Error(`OpenRouter API failed: ${msg}`);
768
+ }
769
+ if (matches) {
770
+ const firstLine = contentLines[i];
771
+ const lastLine = contentLines[i + searchLines.length - 1];
772
+ return { start: firstLine.start, end: lastLine.end, strategy: "whitespace", score: 1 };
845
773
  }
846
774
  }
847
- };
848
- }
849
- });
850
-
851
- // ../../packages/shared/dist/index.js
852
- var require_dist4 = __commonJS({
853
- "../../packages/shared/dist/index.js"(exports2, module2) {
854
- "use strict";
855
- var __create2 = Object.create;
856
- var __defProp2 = Object.defineProperty;
857
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
858
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
859
- var __getProtoOf2 = Object.getPrototypeOf;
860
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
861
- var __export = (target, all) => {
862
- for (var name in all)
863
- __defProp2(target, name, { get: all[name], enumerable: true });
864
- };
865
- var __copyProps2 = (to, from, except, desc) => {
866
- if (from && typeof from === "object" || typeof from === "function") {
867
- for (let key of __getOwnPropNames2(from))
868
- if (!__hasOwnProp2.call(to, key) && key !== except)
869
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
870
- }
871
- return to;
872
- };
873
- var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
874
- // If the importer is in node compatibility mode or this is not an ESM
875
- // file that has been converted to a CommonJS file using a Babel-
876
- // compatible transform (i.e. "__esModule" has not been set), then set
877
- // "default" to the CommonJS "module.exports" for node compatibility.
878
- isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
879
- mod
880
- ));
881
- var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
882
- var index_exports = {};
883
- __export(index_exports, {
884
- DEFAULT_PROTECTED_PATTERNS: () => DEFAULT_PROTECTED_PATTERNS,
885
- DEFAULT_SECRET_PATTERNS: () => DEFAULT_SECRET_PATTERNS,
886
- createProtectedPathRules: () => createProtectedPathRules,
887
- isInsideDirectory: () => isInsideDirectory,
888
- isLexicallyInside: () => isLexicallyInside,
889
- projectRelativePaths: () => projectRelativePaths,
890
- resolveInsideProject: () => resolveInsideProject,
891
- uniqueFilePaths: () => uniqueFilePaths3
892
- });
893
- module2.exports = __toCommonJS(index_exports);
894
- function uniqueFilePaths3(patches) {
895
- return [...new Set(patches.map((patch) => patch.filePath))];
896
- }
897
- var import_fs2 = __toESM2(require("fs"));
898
- var import_path2 = __toESM2(require("path"));
899
- function isLexicallyInside(root, target) {
900
- const relative = import_path2.default.relative(import_path2.default.resolve(root), import_path2.default.resolve(target));
901
- const escapes = relative === ".." || relative.startsWith(`..${import_path2.default.sep}`) || import_path2.default.isAbsolute(relative);
902
- return !escapes;
775
+ return null;
903
776
  }
904
- function isInsideDirectory(root, target) {
905
- const absoluteTarget = import_path2.default.resolve(target);
906
- if (!isLexicallyInside(root, absoluteTarget)) return false;
907
- try {
908
- let probe = absoluteTarget;
909
- while (!import_fs2.default.existsSync(probe)) {
910
- const parent = import_path2.default.dirname(probe);
911
- if (parent === probe) return false;
912
- probe = parent;
777
+ function findSimilarityMatch(content, search) {
778
+ const searchLines = search.split(/\r\n|\n/);
779
+ const contentLines = splitLinesWithOffsets(content);
780
+ if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
781
+ if (contentLines.length > MAX_LINES_FOR_SIMILARITY_PASS) return null;
782
+ let bestIndex = -1;
783
+ let bestScore = -1;
784
+ let secondBestScore = -1;
785
+ for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
786
+ let total = 0;
787
+ for (let j = 0; j < searchLines.length; j++) {
788
+ total += lineSimilarity(searchLines[j], contentLines[i + j].text);
789
+ }
790
+ const avgScore = total / searchLines.length;
791
+ if (avgScore > bestScore) {
792
+ secondBestScore = bestScore;
793
+ bestScore = avgScore;
794
+ bestIndex = i;
795
+ } else if (avgScore > secondBestScore) {
796
+ secondBestScore = avgScore;
913
797
  }
914
- return isLexicallyInside(import_fs2.default.realpathSync.native(root), import_fs2.default.realpathSync.native(probe));
915
- } catch {
916
- return false;
917
798
  }
799
+ if (bestIndex === -1 || bestScore < SIMILARITY_THRESHOLD) return null;
800
+ if (secondBestScore >= 0 && bestScore - secondBestScore < AMBIGUITY_MARGIN) return null;
801
+ const firstLine = contentLines[bestIndex];
802
+ const lastLine = contentLines[bestIndex + searchLines.length - 1];
803
+ return { start: firstLine.start, end: lastLine.end, strategy: "similarity", score: bestScore };
918
804
  }
919
- function resolveInsideProject(cwd, filePath) {
920
- if (typeof filePath !== "string" || filePath.trim() === "") {
921
- return { ok: false, error: "The file path is empty. Use a path relative to the project root." };
922
- }
923
- if (filePath.includes("\0")) {
924
- return { ok: false, error: "The file path contains a null character." };
925
- }
926
- const absolutePath = import_path2.default.resolve(cwd, filePath);
927
- if (import_path2.default.resolve(cwd) === absolutePath) {
928
- return { ok: false, error: `"${filePath}" is the project directory itself, not a file.` };
805
+ function findMatch(content, search) {
806
+ const exactIndex = content.indexOf(search);
807
+ if (exactIndex !== -1) {
808
+ return { start: exactIndex, end: exactIndex + search.length, strategy: "exact", score: 1 };
929
809
  }
930
- if (!isInsideDirectory(cwd, absolutePath)) {
810
+ return findWhitespaceNormalizedMatch(content, search) ?? findSimilarityMatch(content, search);
811
+ }
812
+ var CRLF = "\r\n";
813
+ var LF = "\n";
814
+ function countEndings(text) {
815
+ const crlf = text.split(CRLF).length - 1;
816
+ const lf = text.split(LF).length - 1 - crlf;
817
+ return { crlf, lf };
818
+ }
819
+ function detectLineEnding(text, start, end) {
820
+ const inside = countEndings(text.slice(start, end));
821
+ if (inside.crlf !== inside.lf) return inside.crlf > inside.lf ? CRLF : LF;
822
+ const nextBreak = text.indexOf(LF, end);
823
+ if (nextBreak !== -1) return text[nextBreak - 1] === "\r" ? CRLF : LF;
824
+ const previousBreak = start > 0 ? text.lastIndexOf(LF, start - 1) : -1;
825
+ if (previousBreak !== -1) return text[previousBreak - 1] === "\r" ? CRLF : LF;
826
+ const whole = countEndings(text);
827
+ return whole.crlf > whole.lf ? CRLF : LF;
828
+ }
829
+ function withLineEnding(text, ending) {
830
+ return text.replace(/\r\n|\n/g, ending);
831
+ }
832
+ function patchContent(original, search, replace, fileName) {
833
+ const match = findMatch(original, search);
834
+ if (!match) {
931
835
  return {
932
836
  ok: false,
933
- error: `"${filePath}" is outside the project directory. Use a path relative to the project root.`
837
+ error: `Search string not found in ${fileName} (tried exact, whitespace-normalized, and fuzzy matching). The AI's "search" field did not match file content.`
934
838
  };
935
839
  }
936
- return { ok: true, absolutePath };
840
+ const replacement = withLineEnding(replace, detectLineEnding(original, match.start, match.end));
841
+ const content = original.slice(0, match.start) + replacement + original.slice(match.end);
842
+ return { ok: true, content, matchStrategy: match.strategy };
937
843
  }
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, "\\$&");
844
+ function applyPatch(absoluteFilePath, search, replace, options = {}) {
845
+ try {
846
+ if (!import_fs2.default.existsSync(absoluteFilePath)) {
847
+ return {
848
+ success: false,
849
+ error: `File not found: ${absoluteFilePath}`
850
+ };
851
+ }
852
+ const original = import_fs2.default.readFileSync(absoluteFilePath, "utf-8");
853
+ const patched = patchContent(original, search, replace, import_path3.default.basename(absoluteFilePath));
854
+ if (!patched.ok) return { success: false, error: patched.error };
855
+ const backupPath = absoluteFilePath + ".opspilot.bak";
856
+ if (options.backup !== false) {
857
+ import_fs2.default.writeFileSync(backupPath, original, "utf-8");
986
858
  }
859
+ import_fs2.default.writeFileSync(absoluteFilePath, patched.content, "utf-8");
860
+ return { success: true, backupPath, matchStrategy: patched.matchStrategy };
861
+ } catch (err) {
862
+ return { success: false, error: err.message };
987
863
  }
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
864
  }
994
- function firstMatch(matchers, normalizedPath) {
995
- return matchers.find((m) => m.test(normalizedPath));
865
+ var import_fs3 = __toESM2(require("fs"));
866
+ var import_crypto = __toESM2(require("crypto"));
867
+ var import_fs22 = __toESM2(require("fs"));
868
+ var FINGERPRINT_SUFFIX = ".sha";
869
+ function fingerprintOf(content) {
870
+ return import_crypto.default.createHash("sha256").update(content).digest("hex");
996
871
  }
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;
872
+ function saveFingerprint(absoluteFilePath, backupPath) {
873
+ const notePath = backupPath + FINGERPRINT_SUFFIX;
874
+ try {
875
+ import_fs22.default.writeFileSync(notePath, fingerprintOf(import_fs22.default.readFileSync(absoluteFilePath)) + "\n", "utf-8");
876
+ } catch {
877
+ try {
878
+ import_fs22.default.unlinkSync(notePath);
879
+ } catch {
1014
880
  }
1015
- };
881
+ }
1016
882
  }
1017
- function toRelative(root, target) {
1018
- return import_path22.default.relative(root, target).split(import_path22.default.sep).join("/");
883
+ var import_shared4 = require_dist2();
884
+ function resolvePatchTargets(cwd, patches, protection = (0, import_shared4.createProtectedPathRules)()) {
885
+ const absolutePaths = [];
886
+ for (const patch of patches) {
887
+ const resolved = (0, import_shared4.resolveInsideProject)(cwd, patch.filePath);
888
+ if (!resolved.ok) {
889
+ return { ok: false, error: `Failed to patch "${patch.filePath}": ${resolved.error}` };
890
+ }
891
+ for (const relPath of (0, import_shared4.projectRelativePaths)(cwd, resolved.absolutePath)) {
892
+ const pattern = protection.editBlockedBy(relPath);
893
+ if (pattern !== void 0) {
894
+ return {
895
+ ok: false,
896
+ 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.`
897
+ };
898
+ }
899
+ }
900
+ absolutePaths.push(resolved.absolutePath);
901
+ }
902
+ return { ok: true, absolutePaths };
1019
903
  }
1020
- function realPathAllowingMissing(target) {
1021
- let current = import_path22.default.resolve(target);
1022
- const rest = [];
1023
- while (true) {
904
+ function rollback(originalContent, backupPaths) {
905
+ for (const [absolutePath, content] of originalContent) {
1024
906
  try {
1025
- return import_path22.default.join(import_fs22.default.realpathSync.native(current), ...rest.reverse());
907
+ import_fs3.default.writeFileSync(absolutePath, content, "utf-8");
908
+ } catch {
909
+ }
910
+ }
911
+ for (const backupPath of backupPaths) {
912
+ try {
913
+ import_fs3.default.unlinkSync(backupPath);
1026
914
  } 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
915
  }
1032
916
  }
1033
917
  }
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);
918
+ function applyPatches(cwd, patches, options = {}) {
919
+ if (patches.length === 0) {
920
+ return { success: false, error: "No patches to apply.", applied: [] };
1041
921
  }
1042
- return paths;
922
+ const targets = resolvePatchTargets(cwd, patches, options.protection);
923
+ if (!targets.ok) {
924
+ return { success: false, error: targets.error, applied: [] };
925
+ }
926
+ const absolutePaths = targets.absolutePaths;
927
+ const originalContent = /* @__PURE__ */ new Map();
928
+ const backupPaths = /* @__PURE__ */ new Set();
929
+ const applied = [];
930
+ const backedUp = new Set(options.alreadyBackedUp ?? []);
931
+ for (const [index, patch] of patches.entries()) {
932
+ const absolutePath = absolutePaths[index];
933
+ if (!originalContent.has(absolutePath)) {
934
+ try {
935
+ originalContent.set(absolutePath, import_fs3.default.readFileSync(absolutePath, "utf-8"));
936
+ } catch {
937
+ rollback(originalContent, backupPaths);
938
+ return {
939
+ success: false,
940
+ error: `Failed to patch "${patch.filePath}": File not found: ${absolutePath}`,
941
+ applied: []
942
+ };
943
+ }
944
+ }
945
+ const needsBackup = !backedUp.has(absolutePath);
946
+ const result = applyPatch(absolutePath, patch.search, patch.replace, { backup: needsBackup });
947
+ if (result.success && needsBackup) {
948
+ backedUp.add(absolutePath);
949
+ backupPaths.add(result.backupPath);
950
+ }
951
+ if (!result.success) {
952
+ rollback(originalContent, backupPaths);
953
+ return {
954
+ success: false,
955
+ error: `Failed to patch "${patch.filePath}": ${result.error}`,
956
+ applied: []
957
+ };
958
+ }
959
+ applied.push({
960
+ filePath: patch.filePath,
961
+ absolutePath,
962
+ backupPath: result.backupPath,
963
+ matchStrategy: result.matchStrategy
964
+ });
965
+ }
966
+ const noted = /* @__PURE__ */ new Set();
967
+ for (const item of applied) {
968
+ if (noted.has(item.absolutePath)) continue;
969
+ noted.add(item.absolutePath);
970
+ saveFingerprint(item.absolutePath, item.backupPath);
971
+ }
972
+ return { success: true, applied };
973
+ }
974
+ var import_shared22 = require_dist2();
975
+ var import_fs4 = __toESM2(require("fs"));
976
+ var import_path22 = __toESM2(require("path"));
977
+ var DEFAULT_CONTEXT = 3;
978
+ var DEFAULT_MAX_LINE_LENGTH = 200;
979
+ var MAX_EDIT_DISTANCE = 1500;
980
+ var NO_NEWLINE = "\0no-newline";
981
+ function toLines(text) {
982
+ if (text === "") return [];
983
+ const parts = text.split("\n");
984
+ if (parts[parts.length - 1] === "") parts.pop();
985
+ else parts[parts.length - 1] += NO_NEWLINE;
986
+ return parts;
987
+ }
988
+ function diffLines(a, b) {
989
+ const n = a.length;
990
+ const m = b.length;
991
+ if (n === 0) return b.map(() => ({ kind: "insert" }));
992
+ if (m === 0) return a.map(() => ({ kind: "delete" }));
993
+ const limit = Math.min(n + m, MAX_EDIT_DISTANCE);
994
+ const offset = limit + 1;
995
+ const v = new Int32Array(2 * limit + 3);
996
+ const trace = [];
997
+ for (let d = 0; d <= limit; d++) {
998
+ trace.push(v.slice());
999
+ for (let k = -d; k <= d; k += 2) {
1000
+ let x;
1001
+ if (k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1]) x = v[offset + k + 1];
1002
+ else x = v[offset + k - 1] + 1;
1003
+ let y = x - k;
1004
+ while (x < n && y < m && a[x] === b[y]) {
1005
+ x++;
1006
+ y++;
1007
+ }
1008
+ v[offset + k] = x;
1009
+ if (x >= n && y >= m) {
1010
+ const ops = [];
1011
+ let px = n;
1012
+ let py = m;
1013
+ for (let step = d; step >= 0; step--) {
1014
+ const snapshot = trace[step];
1015
+ const diagonal = px - py;
1016
+ const prevDiagonal = diagonal === -step || diagonal !== step && snapshot[offset + diagonal - 1] < snapshot[offset + diagonal + 1] ? diagonal + 1 : diagonal - 1;
1017
+ const prevX = snapshot[offset + prevDiagonal];
1018
+ const prevY = prevX - prevDiagonal;
1019
+ while (px > prevX && py > prevY) {
1020
+ ops.push({ kind: "equal" });
1021
+ px--;
1022
+ py--;
1023
+ }
1024
+ if (step > 0) {
1025
+ ops.push({ kind: px === prevX ? "insert" : "delete" });
1026
+ if (px === prevX) py--;
1027
+ else px--;
1028
+ }
1029
+ }
1030
+ return ops.reverse();
1031
+ }
1032
+ }
1033
+ }
1034
+ return null;
1035
+ }
1036
+ function computeOps(oldLines, newLines) {
1037
+ let prefix = 0;
1038
+ while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) prefix++;
1039
+ let suffix = 0;
1040
+ while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix && oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]) {
1041
+ suffix++;
1042
+ }
1043
+ const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);
1044
+ const newMiddle = newLines.slice(prefix, newLines.length - suffix);
1045
+ const middle = diffLines(oldMiddle, newMiddle) ?? [...oldMiddle.map(() => ({ kind: "delete" })), ...newMiddle.map(() => ({ kind: "insert" }))];
1046
+ return [
1047
+ ...Array.from({ length: prefix }, () => ({ kind: "equal" })),
1048
+ ...middle,
1049
+ ...Array.from({ length: suffix }, () => ({ kind: "equal" }))
1050
+ ];
1051
+ }
1052
+ function formatRange(start, count) {
1053
+ return count === 1 ? String(start) : `${start},${count}`;
1054
+ }
1055
+ function renderLine(prefix, raw, maxLineLength) {
1056
+ const missingNewline = raw.endsWith(NO_NEWLINE);
1057
+ let text = (missingNewline ? raw.slice(0, -NO_NEWLINE.length) : raw).replace(/\r$/, "");
1058
+ if (text.length > maxLineLength) {
1059
+ text = `${text.slice(0, maxLineLength)}\u2026 [${text.length - maxLineLength} more characters]`;
1060
+ }
1061
+ const rendered = [`${prefix}${text}`];
1062
+ if (missingNewline) rendered.push("\");
1063
+ return rendered;
1064
+ }
1065
+ function renderOne(change, context, maxLineLength) {
1066
+ if (change.before === change.after) return [];
1067
+ const oldLines = toLines(change.before);
1068
+ const newLines = toLines(change.after);
1069
+ const ops = computeOps(oldLines, newLines);
1070
+ const oldBefore = [];
1071
+ const newBefore = [];
1072
+ let oldCount = 0;
1073
+ let newCount = 0;
1074
+ for (const op of ops) {
1075
+ oldBefore.push(oldCount);
1076
+ newBefore.push(newCount);
1077
+ if (op.kind !== "insert") oldCount++;
1078
+ if (op.kind !== "delete") newCount++;
1079
+ }
1080
+ const changed = [];
1081
+ ops.forEach((op, index) => {
1082
+ if (op.kind !== "equal") changed.push(index);
1083
+ });
1084
+ if (changed.length === 0) return [];
1085
+ const groups = [];
1086
+ for (const index of changed) {
1087
+ const current = groups[groups.length - 1];
1088
+ if (current && index - current.last - 1 <= 2 * context) current.last = index;
1089
+ else groups.push({ first: index, last: index });
1090
+ }
1091
+ const output = [`--- a/${change.filePath}`, `+++ b/${change.filePath}`];
1092
+ for (const group of groups) {
1093
+ const from = Math.max(0, group.first - context);
1094
+ const to = Math.min(ops.length - 1, group.last + context);
1095
+ let oldInHunk = 0;
1096
+ let newInHunk = 0;
1097
+ for (let i = from; i <= to; i++) {
1098
+ if (ops[i].kind !== "insert") oldInHunk++;
1099
+ if (ops[i].kind !== "delete") newInHunk++;
1100
+ }
1101
+ const oldStart = oldInHunk === 0 ? oldBefore[from] : oldBefore[from] + 1;
1102
+ const newStart = newInHunk === 0 ? newBefore[from] : newBefore[from] + 1;
1103
+ output.push(`@@ -${formatRange(oldStart, oldInHunk)} +${formatRange(newStart, newInHunk)} @@`);
1104
+ for (let i = from; i <= to; i++) {
1105
+ const op = ops[i];
1106
+ if (op.kind === "equal") output.push(...renderLine(" ", oldLines[oldBefore[i]], maxLineLength));
1107
+ else if (op.kind === "delete") output.push(...renderLine("-", oldLines[oldBefore[i]], maxLineLength));
1108
+ else output.push(...renderLine("+", newLines[newBefore[i]], maxLineLength));
1109
+ }
1110
+ }
1111
+ return output;
1112
+ }
1113
+ function renderUnifiedDiff(changes, options = {}) {
1114
+ const context = Math.max(0, options.context ?? DEFAULT_CONTEXT);
1115
+ const maxLineLength = Math.max(1, options.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH);
1116
+ const list = Array.isArray(changes) ? changes : [changes];
1117
+ return list.flatMap(
1118
+ (change) => renderOne({ ...change, filePath: change.filePath.replace(/\\/g, "/") }, context, maxLineLength)
1119
+ ).join("\n");
1120
+ }
1121
+ function renderChangesFromBackups2(cwd, filePaths, options = {}) {
1122
+ const changes = [];
1123
+ for (const filePath of filePaths) {
1124
+ const resolved = (0, import_shared22.resolveInsideProject)(cwd, filePath);
1125
+ if (!resolved.ok) continue;
1126
+ try {
1127
+ changes.push({
1128
+ filePath: import_path22.default.relative(import_path22.default.resolve(cwd), resolved.absolutePath),
1129
+ before: import_fs4.default.readFileSync(`${resolved.absolutePath}.opspilot.bak`, "utf-8"),
1130
+ after: import_fs4.default.readFileSync(resolved.absolutePath, "utf-8")
1131
+ });
1132
+ } catch {
1133
+ }
1134
+ }
1135
+ return renderUnifiedDiff(changes, options);
1136
+ }
1137
+ var import_fs5 = __toESM2(require("fs"));
1138
+ var import_path32 = __toESM2(require("path"));
1139
+ function previewPatches(cwd, patches, options = {}) {
1140
+ if (patches.length === 0) {
1141
+ return { success: false, error: "No patches to apply." };
1142
+ }
1143
+ const targets = resolvePatchTargets(cwd, patches, options.protection);
1144
+ if (!targets.ok) return { success: false, error: targets.error };
1145
+ const originals = /* @__PURE__ */ new Map();
1146
+ const current = /* @__PURE__ */ new Map();
1147
+ for (const [index, patch] of patches.entries()) {
1148
+ const absolutePath = targets.absolutePaths[index];
1149
+ if (!current.has(absolutePath)) {
1150
+ try {
1151
+ const content = import_fs5.default.readFileSync(absolutePath, "utf-8");
1152
+ originals.set(absolutePath, content);
1153
+ current.set(absolutePath, content);
1154
+ } catch {
1155
+ return { success: false, error: `Failed to patch "${patch.filePath}": File not found: ${absolutePath}` };
1156
+ }
1157
+ }
1158
+ const patched = patchContent(current.get(absolutePath), patch.search, patch.replace, import_path32.default.basename(absolutePath));
1159
+ if (!patched.ok) {
1160
+ return { success: false, error: `Failed to patch "${patch.filePath}": ${patched.error}` };
1161
+ }
1162
+ current.set(absolutePath, patched.content);
1163
+ }
1164
+ const root = import_path32.default.resolve(cwd);
1165
+ const changes = [...originals.keys()].map((absolutePath) => ({
1166
+ filePath: import_path32.default.relative(root, absolutePath).split(import_path32.default.sep).join("/"),
1167
+ before: originals.get(absolutePath),
1168
+ after: current.get(absolutePath)
1169
+ }));
1170
+ return { success: true, changes };
1171
+ }
1172
+ var import_shared32 = require_dist2();
1173
+ var import_fs6 = __toESM2(require("fs"));
1174
+ var import_path4 = __toESM2(require("path"));
1175
+ var BACKUP_SUFFIX = ".opspilot.bak";
1176
+ var SKIPPED_FOLDERS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
1177
+ function findBackups(cwd) {
1178
+ const found = [];
1179
+ const walk = (dir) => {
1180
+ let entries;
1181
+ try {
1182
+ entries = import_fs6.default.readdirSync(dir, { withFileTypes: true });
1183
+ } catch {
1184
+ return;
1185
+ }
1186
+ for (const entry of entries) {
1187
+ const full = import_path4.default.join(dir, entry.name);
1188
+ if (entry.isDirectory()) {
1189
+ if (!SKIPPED_FOLDERS.has(entry.name)) walk(full);
1190
+ } else if (entry.isFile() && entry.name.endsWith(BACKUP_SUFFIX)) {
1191
+ found.push(full);
1192
+ }
1193
+ }
1194
+ };
1195
+ walk(import_path4.default.resolve(cwd));
1196
+ return found.sort();
1197
+ }
1198
+ function readFingerprint(backupPath) {
1199
+ try {
1200
+ const text = import_fs6.default.readFileSync(backupPath + FINGERPRINT_SUFFIX, "utf-8").trim();
1201
+ return text === "" ? void 0 : text;
1202
+ } catch {
1203
+ return void 0;
1204
+ }
1205
+ }
1206
+ function remove(filePath) {
1207
+ try {
1208
+ import_fs6.default.unlinkSync(filePath);
1209
+ } catch {
1210
+ }
1211
+ }
1212
+ function undoChanges2(cwd, options = {}) {
1213
+ const root = import_path4.default.resolve(cwd);
1214
+ const protection = options.protection ?? (0, import_shared32.createProtectedPathRules)();
1215
+ const entries = [];
1216
+ for (const backupPath of findBackups(root)) {
1217
+ const target = backupPath.slice(0, -BACKUP_SUFFIX.length);
1218
+ const filePath = import_path4.default.relative(root, target).split(import_path4.default.sep).join("/");
1219
+ const entry = (status, detail) => ({ filePath, status, ...detail ? { detail } : {} });
1220
+ if (!(0, import_shared32.isInsideDirectory)(root, target)) {
1221
+ entries.push(entry("failed", "The file is outside the project."));
1222
+ continue;
1223
+ }
1224
+ const blockedBy = (0, import_shared32.projectRelativePaths)(root, target).map((relPath) => protection.editBlockedBy(relPath)).find((pattern) => pattern !== void 0);
1225
+ if (blockedBy !== void 0) {
1226
+ entries.push(entry("protected", `It is protected (it matches "${blockedBy}"), so BugZero does not write to it.`));
1227
+ continue;
1228
+ }
1229
+ try {
1230
+ const original = import_fs6.default.readFileSync(backupPath);
1231
+ const exists = import_fs6.default.existsSync(target);
1232
+ if (exists && !import_fs6.default.statSync(target).isFile()) {
1233
+ entries.push(entry("failed", "It is not a regular file."));
1234
+ continue;
1235
+ }
1236
+ const current = exists ? import_fs6.default.readFileSync(target) : void 0;
1237
+ const alreadyOriginal = current !== void 0 && current.equals(original);
1238
+ if (current !== void 0 && !alreadyOriginal && !options.force) {
1239
+ const fixed = readFingerprint(backupPath);
1240
+ if (fixed !== void 0 && fingerprintOf(current) !== fixed) {
1241
+ entries.push(
1242
+ entry("edited-since", "It was changed after BugZero fixed it. Use --force to restore it anyway (your changes would be lost).")
1243
+ );
1244
+ continue;
1245
+ }
1246
+ }
1247
+ if (options.dryRun) {
1248
+ entries.push(entry("would-restore"));
1249
+ continue;
1250
+ }
1251
+ if (!alreadyOriginal) import_fs6.default.writeFileSync(target, original);
1252
+ remove(backupPath);
1253
+ remove(backupPath + FINGERPRINT_SUFFIX);
1254
+ entries.push(entry("restored"));
1255
+ } catch (error) {
1256
+ entries.push(entry("failed", error?.message ?? String(error)));
1257
+ }
1258
+ }
1259
+ return entries;
1043
1260
  }
1044
1261
  }
1045
1262
  });
1046
1263
 
1047
- // ../../packages/prompts/dist/index.js
1048
- var require_dist5 = __commonJS({
1049
- "../../packages/prompts/dist/index.js"(exports2, module2) {
1264
+ // ../../packages/analyzers/dist/index.js
1265
+ var require_dist4 = __commonJS({
1266
+ "../../packages/analyzers/dist/index.js"(exports2, module2) {
1050
1267
  "use strict";
1051
1268
  var __create2 = Object.create;
1052
1269
  var __defProp2 = Object.defineProperty;
@@ -1077,226 +1294,214 @@ var require_dist5 = __commonJS({
1077
1294
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1078
1295
  var index_exports = {};
1079
1296
  __export(index_exports, {
1080
- buildAnalysisPrompt: () => buildAnalysisPrompt,
1081
- truncateLogs: () => truncateLogs
1082
- });
1083
- module2.exports = __toCommonJS(index_exports);
1084
- var import_shared3 = require_dist4();
1085
- var import_fs2 = __toESM2(require("fs"));
1086
- var import_path2 = __toESM2(require("path"));
1087
- var MAX_LOG_CHARS = 2e4;
1088
- var MAX_FILE_CHARS = 2e4;
1089
- var MAX_CONTEXT_CHARS = 6e4;
1090
- function truncateLogs(logs, maxChars = MAX_LOG_CHARS) {
1091
- if (logs.length <= maxChars) return logs;
1092
- const head = logs.slice(0, Math.floor(maxChars * 0.6));
1093
- const tail = logs.slice(logs.length - Math.floor(maxChars * 0.4));
1094
- const omitted = logs.length - head.length - tail.length;
1095
- return `${head}
1096
-
1097
- ... [${omitted} characters of log output omitted to fit the model's context] ...
1098
-
1099
- ${tail}`;
1100
- }
1101
- function resolveExistingPathPrefix(candidate) {
1102
- let current = candidate.replace(/(?::\d+)+$/, "").replace(/['"()\[\]`]+$/, "").trim();
1103
- while (current.length > 0) {
1104
- try {
1105
- if (import_fs2.default.existsSync(current)) {
1106
- return current;
1107
- }
1108
- } catch {
1109
- }
1110
- const lastSpace = current.lastIndexOf(" ");
1111
- if (lastSpace === -1) {
1112
- const lastSlash = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
1113
- if (lastSlash === -1) {
1114
- break;
1297
+ detectPackageManager: () => detectPackageManager3,
1298
+ getRunScriptCommand: () => getRunScriptCommand,
1299
+ parseErrors: () => parseErrors,
1300
+ readScripts: () => readScripts,
1301
+ runBuild: () => runBuild,
1302
+ runCommand: () => runCommand,
1303
+ runLint: () => runLint,
1304
+ runScript: () => runScript,
1305
+ runTests: () => runTests,
1306
+ runValidationPipeline: () => runValidationPipeline
1307
+ });
1308
+ module2.exports = __toCommonJS(index_exports);
1309
+ var import_fs2 = __toESM2(require("fs"));
1310
+ var import_path3 = __toESM2(require("path"));
1311
+ var import_fs3 = __toESM2(require("fs"));
1312
+ var import_path4 = __toESM2(require("path"));
1313
+ var VALID_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
1314
+ var LOCKFILE_MANAGERS = [
1315
+ { file: "pnpm-workspace.yaml", manager: "pnpm" },
1316
+ { file: "pnpm-lock.yaml", manager: "pnpm" },
1317
+ { file: "yarn.lock", manager: "yarn" },
1318
+ { file: "bun.lockb", manager: "bun" },
1319
+ { file: "bun.lock", manager: "bun" },
1320
+ { file: "package-lock.json", manager: "npm" }
1321
+ ];
1322
+ function detectPackageManager3(cwd = process.cwd()) {
1323
+ try {
1324
+ const pkgPath = import_path4.default.join(cwd, "package.json");
1325
+ if (import_fs3.default.existsSync(pkgPath)) {
1326
+ const pkg = JSON.parse(import_fs3.default.readFileSync(pkgPath, "utf-8"));
1327
+ if (typeof pkg.packageManager === "string") {
1328
+ const name = pkg.packageManager.split("@")[0].trim();
1329
+ if (VALID_MANAGERS.includes(name)) {
1330
+ return name;
1331
+ }
1115
1332
  }
1116
- current = current.slice(0, lastSlash).trim();
1117
- } else {
1118
- current = current.slice(0, lastSpace).trim();
1119
1333
  }
1334
+ } catch {
1120
1335
  }
1121
- return null;
1336
+ for (const { file, manager } of LOCKFILE_MANAGERS) {
1337
+ if (import_fs3.default.existsSync(import_path4.default.join(cwd, file))) return manager;
1338
+ }
1339
+ return "npm";
1122
1340
  }
1123
- function getContextFiles(logs, cwd, rules) {
1124
- const candidates = /* @__PURE__ */ new Set();
1125
- const quotedRegex = /['"`]([^'"`\n]+)['"`]/g;
1126
- let match;
1127
- while ((match = quotedRegex.exec(logs)) !== null) {
1128
- const p = match[1].trim();
1129
- if (p.includes("/") || p.includes("\\") || p === "." || p.startsWith(".")) {
1130
- candidates.add(p);
1341
+ function getRunScriptCommand(manager, script) {
1342
+ return `${manager} run ${script}`;
1343
+ }
1344
+ var import_child_process = require("child_process");
1345
+ var import_path22 = __toESM2(require("path"));
1346
+ var import_tree_kill = __toESM2(require("tree-kill"));
1347
+ function killProcessTree(pid) {
1348
+ if (process.platform === "win32") {
1349
+ const systemRoot = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
1350
+ const taskkill = import_path22.default.join(systemRoot, "System32", "taskkill.exe");
1351
+ (0, import_child_process.spawnSync)(taskkill, ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
1352
+ return;
1353
+ }
1354
+ (0, import_tree_kill.default)(pid, "SIGKILL");
1355
+ }
1356
+ var KILL_GRACE_MS = 5e3;
1357
+ async function runCommand(command, cwd, options = {}) {
1358
+ const { execa } = await import("execa");
1359
+ const subprocess = execa(command, {
1360
+ shell: true,
1361
+ cwd: cwd ?? process.cwd(),
1362
+ all: true,
1363
+ env: {
1364
+ ...process.env,
1365
+ CI: "true"
1131
1366
  }
1367
+ });
1368
+ const timedOutResult = (output, confirmedStopped) => {
1369
+ const seconds = options.timeoutMs / 1e3;
1370
+ const note = confirmedStopped ? "and was stopped" : "and could not be confirmed stopped";
1371
+ return {
1372
+ success: false,
1373
+ timedOut: true,
1374
+ output: `${output}
1375
+
1376
+ [BugZero] Command timed out after ${seconds}s ${note}: ${command}`
1377
+ };
1378
+ };
1379
+ let timedOut = false;
1380
+ let timer;
1381
+ let graceTimer;
1382
+ const gaveUp = new Promise((resolve) => {
1383
+ if (options.timeoutMs === void 0) return;
1384
+ timer = setTimeout(() => {
1385
+ timedOut = true;
1386
+ if (subprocess.pid !== void 0) killProcessTree(subprocess.pid);
1387
+ graceTimer = setTimeout(() => resolve(timedOutResult("", false)), KILL_GRACE_MS);
1388
+ }, options.timeoutMs);
1389
+ });
1390
+ const finished = subprocess.then(
1391
+ (result) => ({ success: true, output: result.all ?? result.stdout }),
1392
+ (err) => {
1393
+ const output = err.all ?? err.stderr ?? err.stdout ?? err.message;
1394
+ return timedOut ? timedOutResult(output, true) : { success: false, output };
1395
+ }
1396
+ );
1397
+ try {
1398
+ return await Promise.race([finished, gaveUp]);
1399
+ } finally {
1400
+ clearTimeout(timer);
1401
+ clearTimeout(graceTimer);
1132
1402
  }
1133
- const winAbsRegex = /([a-zA-Z]:\\[^*?"<>|\n\r]+)/g;
1134
- while ((match = winAbsRegex.exec(logs)) !== null) {
1135
- candidates.add(match[1].trim());
1403
+ }
1404
+ function readScripts(cwd = process.cwd()) {
1405
+ try {
1406
+ const pkgPath = import_path3.default.join(cwd, "package.json");
1407
+ if (!import_fs2.default.existsSync(pkgPath)) return [];
1408
+ const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
1409
+ if (typeof pkg.scripts !== "object" || pkg.scripts === null) return [];
1410
+ return Object.keys(pkg.scripts);
1411
+ } catch {
1412
+ return [];
1136
1413
  }
1137
- const unixAbsRegex = /(\/[^*?"<>|\n\r\t]+)/g;
1138
- while ((match = unixAbsRegex.exec(logs)) !== null) {
1139
- candidates.add(match[1].trim());
1414
+ }
1415
+ async function runScript(script, cwd, options) {
1416
+ if (!readScripts(cwd).includes(script)) {
1417
+ return { success: true, output: "", skipped: true };
1140
1418
  }
1141
- const fallbackRegex = /(?:[a-zA-Z]:)?[a-zA-Z0-9_\-\/\\.]+\.(?:tsx?|jsx?|json|css|html|js|jsx)/g;
1142
- const fallbackMatches = logs.match(fallbackRegex) || [];
1143
- for (const m of fallbackMatches) {
1144
- candidates.add(m.trim());
1419
+ return runCommand(getRunScriptCommand(detectPackageManager3(cwd), script), cwd, options);
1420
+ }
1421
+ var runBuild = (cwd, options) => runScript("build", cwd, options);
1422
+ var runLint = (cwd, options) => runScript("lint", cwd, options);
1423
+ var runTests = (cwd, options) => runScript("test", cwd, options);
1424
+ var TS_ERROR_RE = /^(.+)\((\d+),(\d+)\):\s+error\s+TS\d+:\s+(.+)$/gm;
1425
+ var ESLINT_ERROR_RE = /^\s+(\d+):(\d+)\s+error\s+(.+)$/gm;
1426
+ var JEST_FAIL_RE = /● (.+)/g;
1427
+ var JEST_FILE_RE = /FAIL\s+([\w/\\.\-]+)/g;
1428
+ function parseErrors(output) {
1429
+ const errors = [];
1430
+ const tsMatches = [...output.matchAll(TS_ERROR_RE)];
1431
+ for (const m of tsMatches) {
1432
+ errors.push({
1433
+ type: "typescript",
1434
+ file: m[1].trim(),
1435
+ line: parseInt(m[2], 10),
1436
+ column: parseInt(m[3], 10),
1437
+ message: m[4].trim(),
1438
+ raw: m[0]
1439
+ });
1145
1440
  }
1146
- const resolvedPaths = /* @__PURE__ */ new Set();
1147
- for (const candidate of candidates) {
1148
- const absPathCandidate = import_path2.default.isAbsolute(candidate) ? candidate : import_path2.default.resolve(cwd, candidate);
1149
- const resolved = resolveExistingPathPrefix(absPathCandidate);
1150
- if (resolved && (0, import_shared3.isInsideDirectory)(cwd, resolved)) {
1151
- resolvedPaths.add(import_path2.default.resolve(resolved));
1152
- }
1441
+ if (errors.length > 0) return errors;
1442
+ const eslintMatches = [...output.matchAll(ESLINT_ERROR_RE)];
1443
+ for (const m of eslintMatches) {
1444
+ errors.push({
1445
+ type: "eslint",
1446
+ line: parseInt(m[1], 10),
1447
+ column: parseInt(m[2], 10),
1448
+ message: m[3].trim(),
1449
+ raw: m[0]
1450
+ });
1153
1451
  }
1154
- if (resolvedPaths.size === 0) return "";
1155
- let context = "\n\n### \u{1F4C1} Codebase Context:\n";
1156
- const processedFiles = /* @__PURE__ */ new Set();
1157
- const addFileToContext = (filePath) => {
1158
- const relPath = import_path2.default.relative(cwd, filePath);
1159
- if (relPath.includes("node_modules") || relPath.startsWith("build") || relPath.startsWith("dist") || relPath.startsWith(".git")) {
1160
- return;
1161
- }
1162
- if ((0, import_shared3.projectRelativePaths)(cwd, filePath).some((rel) => rules.secretBlockedBy(rel) !== void 0)) return;
1163
- if (processedFiles.has(filePath)) return;
1164
- if (context.length >= MAX_CONTEXT_CHARS) return;
1165
- processedFiles.add(filePath);
1166
- try {
1167
- let content = import_fs2.default.readFileSync(filePath, "utf-8");
1168
- if (content.length > MAX_FILE_CHARS) {
1169
- const omitted = content.length - MAX_FILE_CHARS;
1170
- content = `${content.slice(0, MAX_FILE_CHARS)}
1171
- ... [file truncated: ${omitted} more characters not shown]`;
1172
- }
1173
- context += `
1174
- --- File: ${relPath} ---
1175
- \`\`\`
1176
- ${content}
1177
- \`\`\`
1178
- `;
1179
- } catch {
1452
+ if (errors.length > 0) return errors;
1453
+ const jestFiles = [...output.matchAll(JEST_FILE_RE)].map((m) => m[1]);
1454
+ const jestFails = [...output.matchAll(JEST_FAIL_RE)];
1455
+ for (const m of jestFails) {
1456
+ errors.push({
1457
+ type: "jest",
1458
+ file: jestFiles[0],
1459
+ message: m[1].trim(),
1460
+ raw: m[0]
1461
+ });
1462
+ }
1463
+ if (errors.length > 0) return errors;
1464
+ if (output.trim()) {
1465
+ errors.push({
1466
+ type: "unknown",
1467
+ message: output.slice(0, 500),
1468
+ raw: output
1469
+ });
1470
+ }
1471
+ return errors;
1472
+ }
1473
+ var STEPS = [
1474
+ { step: "build", label: "build", run: runBuild },
1475
+ { step: "lint", label: "lint", run: runLint },
1476
+ { step: "test", label: "tests", run: runTests }
1477
+ ];
1478
+ async function runValidationPipeline(cwd, options) {
1479
+ const targetCwd = cwd ?? process.cwd();
1480
+ const scripts = readScripts(targetCwd);
1481
+ let ranAnyStep = false;
1482
+ for (const { step, label, run } of STEPS) {
1483
+ if (!scripts.includes(step)) {
1484
+ console.log(`[BugZero] Skipping ${label}: no "${step}" script in package.json.`);
1485
+ continue;
1180
1486
  }
1181
- };
1182
- for (const absPath of resolvedPaths) {
1183
- try {
1184
- const stats = import_fs2.default.statSync(absPath);
1185
- if (stats.isFile()) {
1186
- addFileToContext(absPath);
1187
- const parentDir = import_path2.default.dirname(absPath);
1188
- const filesInDir = import_fs2.default.readdirSync(parentDir);
1189
- const relParentDir = import_path2.default.relative(cwd, parentDir) || ".";
1190
- context += `
1191
- --- Directory files in "${relParentDir}": ---
1192
- `;
1193
- for (const file of filesInDir) {
1194
- try {
1195
- const fileStats = import_fs2.default.statSync(import_path2.default.join(parentDir, file));
1196
- const marker = fileStats.isDirectory() ? "/" : "";
1197
- context += `- ${file}${marker}
1198
- `;
1199
- } catch {
1200
- context += `- ${file}
1201
- `;
1202
- }
1203
- }
1204
- } else if (stats.isDirectory()) {
1205
- const relParentDir = import_path2.default.relative(cwd, absPath) || ".";
1206
- if (relParentDir !== ".") {
1207
- const filesInDir = import_fs2.default.readdirSync(absPath);
1208
- context += `
1209
- --- Directory files in "${relParentDir}": ---
1210
- `;
1211
- for (const file of filesInDir) {
1212
- try {
1213
- const fileStats = import_fs2.default.statSync(import_path2.default.join(absPath, file));
1214
- const marker = fileStats.isDirectory() ? "/" : "";
1215
- context += `- ${file}${marker}
1216
- `;
1217
- } catch {
1218
- context += `- ${file}
1219
- `;
1220
- }
1221
- }
1222
- if (filesInDir.length <= 15) {
1223
- for (const file of filesInDir) {
1224
- const filePathFull = import_path2.default.join(absPath, file);
1225
- const fileExt = import_path2.default.extname(file).toLowerCase();
1226
- try {
1227
- if (import_fs2.default.statSync(filePathFull).isFile() && [".js", ".jsx", ".ts", ".tsx", ".json", ".css"].includes(fileExt)) {
1228
- addFileToContext(filePathFull);
1229
- }
1230
- } catch {
1231
- }
1232
- }
1233
- }
1234
- }
1235
- }
1236
- } catch {
1487
+ ranAnyStep = true;
1488
+ console.log(`[BugZero] Running ${label}...`);
1489
+ const result = await run(targetCwd, options);
1490
+ if (!result.success) {
1491
+ return { success: false, step, output: result.output };
1237
1492
  }
1238
1493
  }
1239
- return context;
1240
- }
1241
- function buildAnalysisPrompt(errorOutput, cwd, options = {}) {
1242
- const warningMarker = "\u26A0\uFE0F [BugZero System Warning]";
1243
- let compilerLogs = errorOutput;
1244
- let historySection = "";
1245
- if (errorOutput.includes(warningMarker)) {
1246
- const parts = errorOutput.split(warningMarker);
1247
- compilerLogs = parts[0].trim();
1248
- const warnings = parts.slice(1).map((w) => w.trim());
1249
- historySection = `
1250
-
1251
- ### \u26A0\uFE0F Previous Failed Attempts:
1252
- ${warnings.map((w, idx) => `Failed Attempt ${idx + 1}:
1253
- ${w}`).join("\n\n")}
1254
-
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.`;
1494
+ if (!ranAnyStep) {
1495
+ console.warn(`[BugZero] No build, lint, or test scripts found in package.json \u2014 nothing to validate.`);
1256
1496
  }
1257
- compilerLogs = truncateLogs(compilerLogs);
1258
- const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared3.createProtectedPathRules)());
1259
- return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1260
-
1261
- A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
1262
-
1263
- \`\`\`
1264
- ${compilerLogs}
1265
- \`\`\`${historySection}${contextSection}
1266
-
1267
- Your task:
1268
- 1. Root Cause: Identify the root cause of the build failure.
1269
- 2. Codebase Context: Read the provided file contents and directory listings under "\u{1F4C1} Codebase Context" to locate the correct files, imports, and file paths. Do not guess filenames or contents that are not in the context.
1270
- 3. Patch: Provide the minimal, precise fix. If the fix genuinely requires changes in more than one file (for example, a renamed export and every place that imports it), include one patch entry per file \u2014 all patches in your response are applied together, atomically.
1271
-
1272
- Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fences, no extra text:
1273
- {
1274
- "rootCause": "One-sentence explanation of the error",
1275
- "explanation": "short explanation of what you changed and why",
1276
- "patches": [
1277
- {
1278
- "filePath": "relative/path/from/project/root/to/file.ts",
1279
- "search": "exact code that currently exists in the file and must be replaced",
1280
- "replace": "the corrected code that replaces the search string"
1281
- }
1282
- ]
1283
- }
1284
-
1285
- Critical rules:
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.
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.
1289
- - Each "search" must be an EXACT character-for-character substring of that file's current content.
1290
- - Each "replace" must be syntactically valid code.
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.
1292
- - Do NOT add backticks, markdown, or any text outside the JSON object.`;
1497
+ return { success: true, step: "none", output: "" };
1293
1498
  }
1294
1499
  }
1295
1500
  });
1296
1501
 
1297
- // ../../packages/patcher/dist/index.js
1298
- var require_dist6 = __commonJS({
1299
- "../../packages/patcher/dist/index.js"(exports2, module2) {
1502
+ // ../../packages/ai-provider/dist/index.js
1503
+ var require_dist5 = __commonJS({
1504
+ "../../packages/ai-provider/dist/index.js"(exports2, module2) {
1300
1505
  "use strict";
1301
1506
  var __create2 = Object.create;
1302
1507
  var __defProp2 = Object.defineProperty;
@@ -1327,409 +1532,365 @@ var require_dist6 = __commonJS({
1327
1532
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1328
1533
  var index_exports = {};
1329
1534
  __export(index_exports, {
1330
- applyPatch: () => applyPatch,
1331
- applyPatches: () => applyPatches,
1332
- findMatch: () => findMatch,
1333
- lineSimilarity: () => lineSimilarity,
1334
- renderChangesFromBackups: () => renderChangesFromBackups2,
1335
- renderUnifiedDiff: () => renderUnifiedDiff
1535
+ OpenRouterProvider: () => OpenRouterProvider,
1536
+ getErrorHints: () => getErrorHints
1336
1537
  });
1337
1538
  module2.exports = __toCommonJS(index_exports);
1539
+ var import_axios = __toESM2(require("axios"));
1338
1540
  var import_fs2 = __toESM2(require("fs"));
1339
- var import_path2 = __toESM2(require("path"));
1340
- var SIMILARITY_THRESHOLD = 0.85;
1341
- var AMBIGUITY_MARGIN = 0.05;
1342
- var MAX_LINES_FOR_SIMILARITY_PASS = 2e4;
1343
- function splitLinesWithOffsets(text) {
1344
- const lines = [];
1345
- let start = 0;
1346
- for (let i = 0; i < text.length; i++) {
1347
- if (text[i] === "\n") {
1348
- let end = i;
1349
- if (end > start && text[end - 1] === "\r") end -= 1;
1350
- lines.push({ text: text.slice(start, end), start, end });
1351
- start = i + 1;
1352
- }
1541
+ var import_path3 = __toESM2(require("path"));
1542
+ var CREDITS_PATTERN = /insufficient credits|credit balance|add more credits|requires more credits|token_limit_exceeded/i;
1543
+ var CONTEXT_PATTERN = /context length|context window|maximum context|context_length_exceeded|string_too_long|too many tokens|reduce the length/i;
1544
+ var MODEL_PATTERN = /not a valid model|no endpoints found|model.{0,40}(not found|does not exist|unavailable)/i;
1545
+ function getErrorHints({ status, message, model }) {
1546
+ if (status === 401) {
1547
+ return ["\u{1F449} Please check if your OPENROUTER_API_KEY is correct and active."];
1353
1548
  }
1354
- lines.push({ text: text.slice(start), start, end: text.length });
1355
- return lines;
1356
- }
1357
- function normalizeLine(line) {
1358
- return line.trim().replace(/\s+/g, " ");
1359
- }
1360
- function levenshtein(a, b) {
1361
- const m = a.length;
1362
- const n = b.length;
1363
- if (m === 0) return n;
1364
- if (n === 0) return m;
1365
- const dp = new Array(n + 1);
1366
- for (let j = 0; j <= n; j++) dp[j] = j;
1367
- for (let i = 1; i <= m; i++) {
1368
- let prev = dp[0];
1369
- dp[0] = i;
1370
- for (let j = 1; j <= n; j++) {
1371
- const temp = dp[j];
1372
- dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j], dp[j - 1]);
1373
- prev = temp;
1374
- }
1549
+ if (status === 402 || CREDITS_PATTERN.test(message)) {
1550
+ return [
1551
+ "\u{1F449} Your OpenRouter credit balance is too low for this request.",
1552
+ " Add credits at https://openrouter.ai/settings/credits, or run 'bugzero vibe' to switch to a cheaper model",
1553
+ " (models that cost nothing are listed at https://openrouter.ai/models?max_price=0)."
1554
+ ];
1375
1555
  }
1376
- return dp[n];
1377
- }
1378
- function lineSimilarity(a, b) {
1379
- const maxLen = Math.max(a.length, b.length);
1380
- if (maxLen === 0) return 1;
1381
- return 1 - levenshtein(a, b) / maxLen;
1382
- }
1383
- function findWhitespaceNormalizedMatch(content, search) {
1384
- const searchLines = search.split(/\r\n|\n/).map(normalizeLine);
1385
- const contentLines = splitLinesWithOffsets(content);
1386
- if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
1387
- const normalizedContentLines = contentLines.map((l) => normalizeLine(l.text));
1388
- for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
1389
- let matches = true;
1390
- for (let j = 0; j < searchLines.length; j++) {
1391
- if (normalizedContentLines[i + j] !== searchLines[j]) {
1392
- matches = false;
1393
- break;
1394
- }
1395
- }
1396
- if (matches) {
1397
- const firstLine = contentLines[i];
1398
- const lastLine = contentLines[i + searchLines.length - 1];
1399
- return { start: firstLine.start, end: lastLine.end, strategy: "whitespace", score: 1 };
1400
- }
1556
+ if (status === 429) {
1557
+ return [
1558
+ "\u{1F449} OpenRouter is rate limiting these requests. Wait a moment and try again.",
1559
+ " Free models have stricter limits; run 'bugzero vibe' to switch models, or add credits to raise them."
1560
+ ];
1401
1561
  }
1402
- return null;
1403
- }
1404
- function findSimilarityMatch(content, search) {
1405
- const searchLines = search.split(/\r\n|\n/);
1406
- const contentLines = splitLinesWithOffsets(content);
1407
- if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
1408
- if (contentLines.length > MAX_LINES_FOR_SIMILARITY_PASS) return null;
1409
- let bestIndex = -1;
1410
- let bestScore = -1;
1411
- let secondBestScore = -1;
1412
- for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
1413
- let total = 0;
1414
- for (let j = 0; j < searchLines.length; j++) {
1415
- total += lineSimilarity(searchLines[j], contentLines[i + j].text);
1416
- }
1417
- const avgScore = total / searchLines.length;
1418
- if (avgScore > bestScore) {
1419
- secondBestScore = bestScore;
1420
- bestScore = avgScore;
1421
- bestIndex = i;
1422
- } else if (avgScore > secondBestScore) {
1423
- secondBestScore = avgScore;
1424
- }
1562
+ if (CONTEXT_PATTERN.test(message)) {
1563
+ return [
1564
+ `\u{1F449} The prompt was too large for the context window of "${model}".`,
1565
+ " Run 'bugzero vibe' to pick a model with a larger context window, or try again on a smaller failing scope."
1566
+ ];
1425
1567
  }
1426
- if (bestIndex === -1 || bestScore < SIMILARITY_THRESHOLD) return null;
1427
- if (secondBestScore >= 0 && bestScore - secondBestScore < AMBIGUITY_MARGIN) return null;
1428
- const firstLine = contentLines[bestIndex];
1429
- const lastLine = contentLines[bestIndex + searchLines.length - 1];
1430
- return { start: firstLine.start, end: lastLine.end, strategy: "similarity", score: bestScore };
1431
- }
1432
- function findMatch(content, search) {
1433
- const exactIndex = content.indexOf(search);
1434
- if (exactIndex !== -1) {
1435
- return { start: exactIndex, end: exactIndex + search.length, strategy: "exact", score: 1 };
1568
+ if (status === 404 || MODEL_PATTERN.test(message)) {
1569
+ return [
1570
+ `\u{1F449} The model "${model}" isn't available on OpenRouter (it wasn't found, or no provider currently serves it).`,
1571
+ " Run 'bugzero vibe' to choose a different model."
1572
+ ];
1436
1573
  }
1437
- return findWhitespaceNormalizedMatch(content, search) ?? findSimilarityMatch(content, search);
1438
- }
1439
- var CRLF = "\r\n";
1440
- var LF = "\n";
1441
- function countEndings(text) {
1442
- const crlf = text.split(CRLF).length - 1;
1443
- const lf = text.split(LF).length - 1 - crlf;
1444
- return { crlf, lf };
1445
- }
1446
- function detectLineEnding(text, start, end) {
1447
- const inside = countEndings(text.slice(start, end));
1448
- if (inside.crlf !== inside.lf) return inside.crlf > inside.lf ? CRLF : LF;
1449
- const nextBreak = text.indexOf(LF, end);
1450
- if (nextBreak !== -1) return text[nextBreak - 1] === "\r" ? CRLF : LF;
1451
- const previousBreak = start > 0 ? text.lastIndexOf(LF, start - 1) : -1;
1452
- if (previousBreak !== -1) return text[previousBreak - 1] === "\r" ? CRLF : LF;
1453
- const whole = countEndings(text);
1454
- return whole.crlf > whole.lf ? CRLF : LF;
1455
- }
1456
- function withLineEnding(text, ending) {
1457
- return text.replace(/\r\n|\n/g, ending);
1574
+ return [];
1458
1575
  }
1459
- function applyPatch(absoluteFilePath, search, replace, options = {}) {
1576
+ function resolveModel(cwd) {
1460
1577
  try {
1461
- if (!import_fs2.default.existsSync(absoluteFilePath)) {
1462
- return {
1463
- success: false,
1464
- error: `File not found: ${absoluteFilePath}`
1465
- };
1466
- }
1467
- const original = import_fs2.default.readFileSync(absoluteFilePath, "utf-8");
1468
- const match = findMatch(original, search);
1469
- if (!match) {
1470
- return {
1471
- success: false,
1472
- error: `Search string not found in ${import_path2.default.basename(absoluteFilePath)} (tried exact, whitespace-normalized, and fuzzy matching). The AI's "search" field did not match file content.`
1473
- };
1474
- }
1475
- const backupPath = absoluteFilePath + ".opspilot.bak";
1476
- if (options.backup !== false) {
1477
- import_fs2.default.writeFileSync(backupPath, original, "utf-8");
1578
+ const configPath = import_path3.default.resolve(cwd ?? process.cwd(), ".bugzerorc");
1579
+ if (import_fs2.default.existsSync(configPath)) {
1580
+ const config = JSON.parse(import_fs2.default.readFileSync(configPath, "utf-8"));
1581
+ if (config.model) return config.model;
1478
1582
  }
1479
- const replacement = withLineEnding(replace, detectLineEnding(original, match.start, match.end));
1480
- const fixed = original.slice(0, match.start) + replacement + original.slice(match.end);
1481
- import_fs2.default.writeFileSync(absoluteFilePath, fixed, "utf-8");
1482
- return { success: true, backupPath, matchStrategy: match.strategy };
1483
- } catch (err) {
1484
- return { success: false, error: err.message };
1583
+ } catch {
1485
1584
  }
1585
+ return "deepseek/deepseek-chat";
1486
1586
  }
1487
- var import_shared3 = require_dist4();
1488
- var import_fs22 = __toESM2(require("fs"));
1489
- function rollback(originalContent, backupPaths) {
1490
- for (const [absolutePath, content] of originalContent) {
1491
- try {
1492
- import_fs22.default.writeFileSync(absolutePath, content, "utf-8");
1493
- } catch {
1587
+ var OpenRouterProvider = class {
1588
+ async invoke(prompt, options) {
1589
+ const model = resolveModel(options?.cwd);
1590
+ const apiKey = process.env.OPENROUTER_API_KEY;
1591
+ if (!apiKey) {
1592
+ console.error(`
1593
+ \u274C [BugZero] Error: OPENROUTER_API_KEY environment variable is not set.`);
1594
+ console.error(`\u{1F449} Please configure it using one of the following methods:`);
1595
+ console.error(` - On macOS/Linux: export OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1596
+ console.error(` - On Windows (PowerShell): $env:OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1597
+ console.error(` - Or add it to a .env file at the root of the project you are fixing:`);
1598
+ console.error(` OPENROUTER_API_KEY=your_openrouter_api_key_here
1599
+ `);
1600
+ throw new Error("Missing OPENROUTER_API_KEY environment variable.");
1494
1601
  }
1495
- }
1496
- for (const backupPath of backupPaths) {
1497
1602
  try {
1498
- import_fs22.default.unlinkSync(backupPath);
1499
- } catch {
1500
- }
1501
- }
1502
- }
1503
- function applyPatches(cwd, patches, options = {}) {
1504
- if (patches.length === 0) {
1505
- return { success: false, error: "No patches to apply.", applied: [] };
1506
- }
1507
- const protection = options.protection ?? (0, import_shared3.createProtectedPathRules)();
1508
- const absolutePaths = [];
1509
- for (const patch of patches) {
1510
- const resolved = (0, import_shared3.resolveInsideProject)(cwd, patch.filePath);
1511
- if (!resolved.ok) {
1603
+ const response = await import_axios.default.post(
1604
+ "https://openrouter.ai/api/v1/chat/completions",
1605
+ {
1606
+ model,
1607
+ messages: [
1608
+ {
1609
+ role: "user",
1610
+ content: prompt
1611
+ }
1612
+ ]
1613
+ },
1614
+ {
1615
+ headers: {
1616
+ Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
1617
+ "Content-Type": "application/json"
1618
+ }
1619
+ }
1620
+ );
1621
+ if (response.data?.error) {
1622
+ throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1623
+ }
1512
1624
  return {
1513
- success: false,
1514
- error: `Failed to patch "${patch.filePath}": ${resolved.error}`,
1515
- applied: []
1625
+ content: response.data.choices[0].message.content,
1626
+ model,
1627
+ usage: response.data.usage
1516
1628
  };
1517
- }
1518
- for (const relPath of (0, import_shared3.projectRelativePaths)(cwd, resolved.absolutePath)) {
1519
- const pattern = protection.editBlockedBy(relPath);
1520
- if (pattern !== void 0) {
1521
- return {
1522
- success: false,
1523
- 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.`,
1524
- applied: []
1525
- };
1629
+ } catch (error) {
1630
+ let msg = error.message;
1631
+ if (error.response?.data?.error?.message) {
1632
+ msg = error.response.data.error.message;
1633
+ } else if (error.response?.data?.message) {
1634
+ msg = error.response.data.message;
1526
1635
  }
1636
+ console.error(`
1637
+ \u274C [BugZero] OpenRouter API Error: ${msg}`);
1638
+ const hints = getErrorHints({ status: error.response?.status, message: msg, model });
1639
+ for (const line of hints) console.error(line);
1640
+ if (hints.length > 0) console.error();
1641
+ throw new Error(`OpenRouter API failed: ${msg}`);
1527
1642
  }
1528
- absolutePaths.push(resolved.absolutePath);
1529
1643
  }
1530
- const originalContent = /* @__PURE__ */ new Map();
1531
- const backupPaths = /* @__PURE__ */ new Set();
1532
- const applied = [];
1533
- const backedUp = new Set(options.alreadyBackedUp ?? []);
1534
- for (const [index, patch] of patches.entries()) {
1535
- const absolutePath = absolutePaths[index];
1536
- if (!originalContent.has(absolutePath)) {
1537
- try {
1538
- originalContent.set(absolutePath, import_fs22.default.readFileSync(absolutePath, "utf-8"));
1539
- } catch {
1540
- rollback(originalContent, backupPaths);
1541
- return {
1542
- success: false,
1543
- error: `Failed to patch "${patch.filePath}": File not found: ${absolutePath}`,
1544
- applied: []
1545
- };
1546
- }
1547
- }
1548
- const needsBackup = !backedUp.has(absolutePath);
1549
- const result = applyPatch(absolutePath, patch.search, patch.replace, { backup: needsBackup });
1550
- if (result.success && needsBackup) {
1551
- backedUp.add(absolutePath);
1552
- backupPaths.add(result.backupPath);
1553
- }
1554
- if (!result.success) {
1555
- rollback(originalContent, backupPaths);
1556
- return {
1557
- success: false,
1558
- error: `Failed to patch "${patch.filePath}": ${result.error}`,
1559
- applied: []
1560
- };
1561
- }
1562
- applied.push({
1563
- filePath: patch.filePath,
1564
- absolutePath,
1565
- backupPath: result.backupPath,
1566
- matchStrategy: result.matchStrategy
1567
- });
1644
+ };
1645
+ }
1646
+ });
1647
+
1648
+ // ../../packages/prompts/dist/index.js
1649
+ var require_dist6 = __commonJS({
1650
+ "../../packages/prompts/dist/index.js"(exports2, module2) {
1651
+ "use strict";
1652
+ var __create2 = Object.create;
1653
+ var __defProp2 = Object.defineProperty;
1654
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1655
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1656
+ var __getProtoOf2 = Object.getPrototypeOf;
1657
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1658
+ var __export = (target, all) => {
1659
+ for (var name in all)
1660
+ __defProp2(target, name, { get: all[name], enumerable: true });
1661
+ };
1662
+ var __copyProps2 = (to, from, except, desc) => {
1663
+ if (from && typeof from === "object" || typeof from === "function") {
1664
+ for (let key of __getOwnPropNames2(from))
1665
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1666
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1568
1667
  }
1569
- return { success: true, applied };
1570
- }
1571
- var import_shared22 = require_dist4();
1572
- var import_fs3 = __toESM2(require("fs"));
1573
- var import_path22 = __toESM2(require("path"));
1574
- var DEFAULT_CONTEXT = 3;
1575
- var DEFAULT_MAX_LINE_LENGTH = 200;
1576
- var MAX_EDIT_DISTANCE = 1500;
1577
- var NO_NEWLINE = "\0no-newline";
1578
- function toLines(text) {
1579
- if (text === "") return [];
1580
- const parts = text.split("\n");
1581
- if (parts[parts.length - 1] === "") parts.pop();
1582
- else parts[parts.length - 1] += NO_NEWLINE;
1583
- return parts;
1668
+ return to;
1669
+ };
1670
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1671
+ // If the importer is in node compatibility mode or this is not an ESM
1672
+ // file that has been converted to a CommonJS file using a Babel-
1673
+ // compatible transform (i.e. "__esModule" has not been set), then set
1674
+ // "default" to the CommonJS "module.exports" for node compatibility.
1675
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1676
+ mod
1677
+ ));
1678
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1679
+ var index_exports = {};
1680
+ __export(index_exports, {
1681
+ buildAnalysisPrompt: () => buildAnalysisPrompt,
1682
+ truncateLogs: () => truncateLogs
1683
+ });
1684
+ module2.exports = __toCommonJS(index_exports);
1685
+ var import_shared4 = require_dist2();
1686
+ var import_fs2 = __toESM2(require("fs"));
1687
+ var import_path3 = __toESM2(require("path"));
1688
+ var MAX_LOG_CHARS = 2e4;
1689
+ var MAX_FILE_CHARS = 2e4;
1690
+ var MAX_CONTEXT_CHARS = 6e4;
1691
+ function truncateLogs(logs, maxChars = MAX_LOG_CHARS) {
1692
+ if (logs.length <= maxChars) return logs;
1693
+ const head = logs.slice(0, Math.floor(maxChars * 0.6));
1694
+ const tail = logs.slice(logs.length - Math.floor(maxChars * 0.4));
1695
+ const omitted = logs.length - head.length - tail.length;
1696
+ return `${head}
1697
+
1698
+ ... [${omitted} characters of log output omitted to fit the model's context] ...
1699
+
1700
+ ${tail}`;
1584
1701
  }
1585
- function diffLines(a, b) {
1586
- const n = a.length;
1587
- const m = b.length;
1588
- if (n === 0) return b.map(() => ({ kind: "insert" }));
1589
- if (m === 0) return a.map(() => ({ kind: "delete" }));
1590
- const limit = Math.min(n + m, MAX_EDIT_DISTANCE);
1591
- const offset = limit + 1;
1592
- const v = new Int32Array(2 * limit + 3);
1593
- const trace = [];
1594
- for (let d = 0; d <= limit; d++) {
1595
- trace.push(v.slice());
1596
- for (let k = -d; k <= d; k += 2) {
1597
- let x;
1598
- if (k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1]) x = v[offset + k + 1];
1599
- else x = v[offset + k - 1] + 1;
1600
- let y = x - k;
1601
- while (x < n && y < m && a[x] === b[y]) {
1602
- x++;
1603
- y++;
1702
+ function resolveExistingPathPrefix(candidate) {
1703
+ let current = candidate.replace(/(?::\d+)+$/, "").replace(/['"()\[\]`]+$/, "").trim();
1704
+ while (current.length > 0) {
1705
+ try {
1706
+ if (import_fs2.default.existsSync(current)) {
1707
+ return current;
1604
1708
  }
1605
- v[offset + k] = x;
1606
- if (x >= n && y >= m) {
1607
- const ops = [];
1608
- let px = n;
1609
- let py = m;
1610
- for (let step = d; step >= 0; step--) {
1611
- const snapshot = trace[step];
1612
- const diagonal = px - py;
1613
- const prevDiagonal = diagonal === -step || diagonal !== step && snapshot[offset + diagonal - 1] < snapshot[offset + diagonal + 1] ? diagonal + 1 : diagonal - 1;
1614
- const prevX = snapshot[offset + prevDiagonal];
1615
- const prevY = prevX - prevDiagonal;
1616
- while (px > prevX && py > prevY) {
1617
- ops.push({ kind: "equal" });
1618
- px--;
1619
- py--;
1620
- }
1621
- if (step > 0) {
1622
- ops.push({ kind: px === prevX ? "insert" : "delete" });
1623
- if (px === prevX) py--;
1624
- else px--;
1625
- }
1626
- }
1627
- return ops.reverse();
1709
+ } catch {
1710
+ }
1711
+ const lastSpace = current.lastIndexOf(" ");
1712
+ if (lastSpace === -1) {
1713
+ const lastSlash = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
1714
+ if (lastSlash === -1) {
1715
+ break;
1628
1716
  }
1717
+ current = current.slice(0, lastSlash).trim();
1718
+ } else {
1719
+ current = current.slice(0, lastSpace).trim();
1629
1720
  }
1630
1721
  }
1631
1722
  return null;
1632
1723
  }
1633
- function computeOps(oldLines, newLines) {
1634
- let prefix = 0;
1635
- while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) prefix++;
1636
- let suffix = 0;
1637
- while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix && oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]) {
1638
- suffix++;
1724
+ function getContextFiles(logs, cwd, rules) {
1725
+ const candidates = /* @__PURE__ */ new Set();
1726
+ const quotedRegex = /['"`]([^'"`\n]+)['"`]/g;
1727
+ let match;
1728
+ while ((match = quotedRegex.exec(logs)) !== null) {
1729
+ const p = match[1].trim();
1730
+ if (p.includes("/") || p.includes("\\") || p === "." || p.startsWith(".")) {
1731
+ candidates.add(p);
1732
+ }
1639
1733
  }
1640
- const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);
1641
- const newMiddle = newLines.slice(prefix, newLines.length - suffix);
1642
- const middle = diffLines(oldMiddle, newMiddle) ?? [...oldMiddle.map(() => ({ kind: "delete" })), ...newMiddle.map(() => ({ kind: "insert" }))];
1643
- return [
1644
- ...Array.from({ length: prefix }, () => ({ kind: "equal" })),
1645
- ...middle,
1646
- ...Array.from({ length: suffix }, () => ({ kind: "equal" }))
1647
- ];
1648
- }
1649
- function formatRange(start, count) {
1650
- return count === 1 ? String(start) : `${start},${count}`;
1651
- }
1652
- function renderLine(prefix, raw, maxLineLength) {
1653
- const missingNewline = raw.endsWith(NO_NEWLINE);
1654
- let text = (missingNewline ? raw.slice(0, -NO_NEWLINE.length) : raw).replace(/\r$/, "");
1655
- if (text.length > maxLineLength) {
1656
- text = `${text.slice(0, maxLineLength)}\u2026 [${text.length - maxLineLength} more characters]`;
1734
+ const winAbsRegex = /([a-zA-Z]:\\[^*?"<>|\n\r]+)/g;
1735
+ while ((match = winAbsRegex.exec(logs)) !== null) {
1736
+ candidates.add(match[1].trim());
1657
1737
  }
1658
- const rendered = [`${prefix}${text}`];
1659
- if (missingNewline) rendered.push("\");
1660
- return rendered;
1661
- }
1662
- function renderOne(change, context, maxLineLength) {
1663
- if (change.before === change.after) return [];
1664
- const oldLines = toLines(change.before);
1665
- const newLines = toLines(change.after);
1666
- const ops = computeOps(oldLines, newLines);
1667
- const oldBefore = [];
1668
- const newBefore = [];
1669
- let oldCount = 0;
1670
- let newCount = 0;
1671
- for (const op of ops) {
1672
- oldBefore.push(oldCount);
1673
- newBefore.push(newCount);
1674
- if (op.kind !== "insert") oldCount++;
1675
- if (op.kind !== "delete") newCount++;
1738
+ const unixAbsRegex = /(\/[^*?"<>|\n\r\t]+)/g;
1739
+ while ((match = unixAbsRegex.exec(logs)) !== null) {
1740
+ candidates.add(match[1].trim());
1676
1741
  }
1677
- const changed = [];
1678
- ops.forEach((op, index) => {
1679
- if (op.kind !== "equal") changed.push(index);
1680
- });
1681
- if (changed.length === 0) return [];
1682
- const groups = [];
1683
- for (const index of changed) {
1684
- const current = groups[groups.length - 1];
1685
- if (current && index - current.last - 1 <= 2 * context) current.last = index;
1686
- else groups.push({ first: index, last: index });
1742
+ const fallbackRegex = /(?:[a-zA-Z]:)?[a-zA-Z0-9_\-\/\\.]+\.(?:tsx?|jsx?|json|css|html|js|jsx)/g;
1743
+ const fallbackMatches = logs.match(fallbackRegex) || [];
1744
+ for (const m of fallbackMatches) {
1745
+ candidates.add(m.trim());
1687
1746
  }
1688
- const output = [`--- a/${change.filePath}`, `+++ b/${change.filePath}`];
1689
- for (const group of groups) {
1690
- const from = Math.max(0, group.first - context);
1691
- const to = Math.min(ops.length - 1, group.last + context);
1692
- let oldInHunk = 0;
1693
- let newInHunk = 0;
1694
- for (let i = from; i <= to; i++) {
1695
- if (ops[i].kind !== "insert") oldInHunk++;
1696
- if (ops[i].kind !== "delete") newInHunk++;
1697
- }
1698
- const oldStart = oldInHunk === 0 ? oldBefore[from] : oldBefore[from] + 1;
1699
- const newStart = newInHunk === 0 ? newBefore[from] : newBefore[from] + 1;
1700
- output.push(`@@ -${formatRange(oldStart, oldInHunk)} +${formatRange(newStart, newInHunk)} @@`);
1701
- for (let i = from; i <= to; i++) {
1702
- const op = ops[i];
1703
- if (op.kind === "equal") output.push(...renderLine(" ", oldLines[oldBefore[i]], maxLineLength));
1704
- else if (op.kind === "delete") output.push(...renderLine("-", oldLines[oldBefore[i]], maxLineLength));
1705
- else output.push(...renderLine("+", newLines[newBefore[i]], maxLineLength));
1747
+ const resolvedPaths = /* @__PURE__ */ new Set();
1748
+ for (const candidate of candidates) {
1749
+ const absPathCandidate = import_path3.default.isAbsolute(candidate) ? candidate : import_path3.default.resolve(cwd, candidate);
1750
+ const resolved = resolveExistingPathPrefix(absPathCandidate);
1751
+ if (resolved && (0, import_shared4.isInsideDirectory)(cwd, resolved)) {
1752
+ resolvedPaths.add(import_path3.default.resolve(resolved));
1706
1753
  }
1707
1754
  }
1708
- return output;
1709
- }
1710
- function renderUnifiedDiff(changes, options = {}) {
1711
- const context = Math.max(0, options.context ?? DEFAULT_CONTEXT);
1712
- const maxLineLength = Math.max(1, options.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH);
1713
- const list = Array.isArray(changes) ? changes : [changes];
1714
- return list.flatMap(
1715
- (change) => renderOne({ ...change, filePath: change.filePath.replace(/\\/g, "/") }, context, maxLineLength)
1716
- ).join("\n");
1717
- }
1718
- function renderChangesFromBackups2(cwd, filePaths, options = {}) {
1719
- const changes = [];
1720
- for (const filePath of filePaths) {
1721
- const resolved = (0, import_shared22.resolveInsideProject)(cwd, filePath);
1722
- if (!resolved.ok) continue;
1755
+ if (resolvedPaths.size === 0) return "";
1756
+ let context = "\n\n### \u{1F4C1} Codebase Context:\n";
1757
+ const processedFiles = /* @__PURE__ */ new Set();
1758
+ const addFileToContext = (filePath) => {
1759
+ const relPath = import_path3.default.relative(cwd, filePath);
1760
+ if (relPath.includes("node_modules") || relPath.startsWith("build") || relPath.startsWith("dist") || relPath.startsWith(".git")) {
1761
+ return;
1762
+ }
1763
+ if ((0, import_shared4.projectRelativePaths)(cwd, filePath).some((rel) => rules.secretBlockedBy(rel) !== void 0)) return;
1764
+ if (processedFiles.has(filePath)) return;
1765
+ if (context.length >= MAX_CONTEXT_CHARS) return;
1766
+ processedFiles.add(filePath);
1723
1767
  try {
1724
- changes.push({
1725
- filePath: import_path22.default.relative(import_path22.default.resolve(cwd), resolved.absolutePath),
1726
- before: import_fs3.default.readFileSync(`${resolved.absolutePath}.opspilot.bak`, "utf-8"),
1727
- after: import_fs3.default.readFileSync(resolved.absolutePath, "utf-8")
1728
- });
1768
+ let content = import_fs2.default.readFileSync(filePath, "utf-8");
1769
+ if (content.length > MAX_FILE_CHARS) {
1770
+ const omitted = content.length - MAX_FILE_CHARS;
1771
+ content = `${content.slice(0, MAX_FILE_CHARS)}
1772
+ ... [file truncated: ${omitted} more characters not shown]`;
1773
+ }
1774
+ context += `
1775
+ --- File: ${relPath} ---
1776
+ \`\`\`
1777
+ ${content}
1778
+ \`\`\`
1779
+ `;
1780
+ } catch {
1781
+ }
1782
+ };
1783
+ for (const absPath of resolvedPaths) {
1784
+ try {
1785
+ const stats = import_fs2.default.statSync(absPath);
1786
+ if (stats.isFile()) {
1787
+ addFileToContext(absPath);
1788
+ const parentDir = import_path3.default.dirname(absPath);
1789
+ const filesInDir = import_fs2.default.readdirSync(parentDir);
1790
+ const relParentDir = import_path3.default.relative(cwd, parentDir) || ".";
1791
+ context += `
1792
+ --- Directory files in "${relParentDir}": ---
1793
+ `;
1794
+ for (const file of filesInDir) {
1795
+ try {
1796
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(parentDir, file));
1797
+ const marker = fileStats.isDirectory() ? "/" : "";
1798
+ context += `- ${file}${marker}
1799
+ `;
1800
+ } catch {
1801
+ context += `- ${file}
1802
+ `;
1803
+ }
1804
+ }
1805
+ } else if (stats.isDirectory()) {
1806
+ const relParentDir = import_path3.default.relative(cwd, absPath) || ".";
1807
+ if (relParentDir !== ".") {
1808
+ const filesInDir = import_fs2.default.readdirSync(absPath);
1809
+ context += `
1810
+ --- Directory files in "${relParentDir}": ---
1811
+ `;
1812
+ for (const file of filesInDir) {
1813
+ try {
1814
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(absPath, file));
1815
+ const marker = fileStats.isDirectory() ? "/" : "";
1816
+ context += `- ${file}${marker}
1817
+ `;
1818
+ } catch {
1819
+ context += `- ${file}
1820
+ `;
1821
+ }
1822
+ }
1823
+ if (filesInDir.length <= 15) {
1824
+ for (const file of filesInDir) {
1825
+ const filePathFull = import_path3.default.join(absPath, file);
1826
+ const fileExt = import_path3.default.extname(file).toLowerCase();
1827
+ try {
1828
+ if (import_fs2.default.statSync(filePathFull).isFile() && [".js", ".jsx", ".ts", ".tsx", ".json", ".css"].includes(fileExt)) {
1829
+ addFileToContext(filePathFull);
1830
+ }
1831
+ } catch {
1832
+ }
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1729
1837
  } catch {
1730
1838
  }
1731
1839
  }
1732
- return renderUnifiedDiff(changes, options);
1840
+ return context;
1841
+ }
1842
+ function buildAnalysisPrompt(errorOutput, cwd, options = {}) {
1843
+ const warningMarker = "\u26A0\uFE0F [BugZero System Warning]";
1844
+ let compilerLogs = errorOutput;
1845
+ let historySection = "";
1846
+ if (errorOutput.includes(warningMarker)) {
1847
+ const parts = errorOutput.split(warningMarker);
1848
+ compilerLogs = parts[0].trim();
1849
+ const warnings = parts.slice(1).map((w) => w.trim());
1850
+ historySection = `
1851
+
1852
+ ### \u26A0\uFE0F Previous Failed Attempts:
1853
+ ${warnings.map((w, idx) => `Failed Attempt ${idx + 1}:
1854
+ ${w}`).join("\n\n")}
1855
+
1856
+ **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.`;
1857
+ }
1858
+ compilerLogs = truncateLogs(compilerLogs);
1859
+ const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
1860
+ return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1861
+
1862
+ A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
1863
+
1864
+ \`\`\`
1865
+ ${compilerLogs}
1866
+ \`\`\`${historySection}${contextSection}
1867
+
1868
+ Your task:
1869
+ 1. Root Cause: Identify the root cause of the build failure.
1870
+ 2. Codebase Context: Read the provided file contents and directory listings under "\u{1F4C1} Codebase Context" to locate the correct files, imports, and file paths. Do not guess filenames or contents that are not in the context.
1871
+ 3. Patch: Provide the minimal, precise fix. If the fix genuinely requires changes in more than one file (for example, a renamed export and every place that imports it), include one patch entry per file \u2014 all patches in your response are applied together, atomically.
1872
+
1873
+ Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fences, no extra text:
1874
+ {
1875
+ "rootCause": "One-sentence explanation of the error",
1876
+ "explanation": "short explanation of what you changed and why",
1877
+ "patches": [
1878
+ {
1879
+ "filePath": "relative/path/from/project/root/to/file.ts",
1880
+ "search": "exact code that currently exists in the file and must be replaced",
1881
+ "replace": "the corrected code that replaces the search string"
1882
+ }
1883
+ ]
1884
+ }
1885
+
1886
+ Critical rules:
1887
+ - "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.
1888
+ - Each "filePath" must be a relative path from the project root (no leading /).
1889
+ - 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.
1890
+ - Each "search" must be an EXACT character-for-character substring of that file's current content.
1891
+ - Each "replace" must be syntactically valid code.
1892
+ - 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.
1893
+ - Do NOT add backticks, markdown, or any text outside the JSON object.`;
1733
1894
  }
1734
1895
  }
1735
1896
  });
@@ -1847,21 +2008,31 @@ var require_dist7 = __commonJS({
1847
2008
  reducer: (old, value) => old + value,
1848
2009
  default: () => 0
1849
2010
  }),
2011
+ /** When set, each proposed fix is shown to this handler and only written if it approves */
2012
+ approve: (0, import_langgraph.Annotation)({
2013
+ reducer: (_, value) => value,
2014
+ default: () => void 0
2015
+ }),
2016
+ /** How many proposed fixes the person declined */
2017
+ declinedFixes: (0, import_langgraph.Annotation)({
2018
+ reducer: (total, added) => total + added,
2019
+ default: () => 0
2020
+ }),
1850
2021
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
1851
2022
  timeoutMs: (0, import_langgraph.Annotation)({
1852
2023
  reducer: (_, value) => value,
1853
2024
  default: () => void 0
1854
2025
  })
1855
2026
  });
1856
- var import_ai_provider = require_dist3();
1857
- var import_prompts = require_dist5();
2027
+ var import_ai_provider = require_dist5();
2028
+ var import_prompts = require_dist6();
1858
2029
  var import_config2 = require_dist();
1859
- var import_patcher2 = require_dist6();
1860
- var import_analyzers = require_dist2();
1861
- var import_shared3 = require_dist4();
2030
+ var import_patcher3 = require_dist3();
2031
+ var import_analyzers = require_dist4();
2032
+ var import_shared4 = require_dist2();
1862
2033
  var provider = new import_ai_provider.OpenRouterProvider();
1863
2034
  function protectionFor(cwd) {
1864
- return (0, import_shared3.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
2035
+ return (0, import_shared4.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
1865
2036
  }
1866
2037
  function previewAnalysisPrompt(cwd, logs) {
1867
2038
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
@@ -1900,6 +2071,19 @@ var require_dist7 = __commonJS({
1900
2071
  completionTokens: result.usage?.completion_tokens ?? 0
1901
2072
  };
1902
2073
  }
2074
+ function patchFailure(state, error) {
2075
+ console.error(`[BugZero] Patch failed: ${error}`);
2076
+ const updatedLogs = `${state.logs}
2077
+
2078
+ \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion failed with the following error:
2079
+ - ${error}
2080
+
2081
+ Any other files from that same suggestion were rolled back to keep the change atomic. Please check if the file path(s) are correct relative to the project root and make sure you target the correct file(s) that contain the build error.`;
2082
+ return {
2083
+ logs: updatedLogs,
2084
+ patchFailed: true
2085
+ };
2086
+ }
1903
2087
  async function applyFixNode(state) {
1904
2088
  if (!state.fixSuggestion) {
1905
2089
  console.warn("[BugZero] No fix suggestion available \u2014 skipping patch.");
@@ -1909,23 +2093,33 @@ var require_dist7 = __commonJS({
1909
2093
  const fileList = patches.map((p) => p.filePath).join(", ");
1910
2094
  console.log(`[BugZero] Patching ${patches.length} file${patches.length === 1 ? "" : "s"}: ${fileList}`);
1911
2095
  console.log(`[BugZero] Reason: ${explanation}`);
1912
- const result = (0, import_patcher2.applyPatches)(state.cwd, patches, {
2096
+ if (state.approve) {
2097
+ const preview = (0, import_patcher3.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
2098
+ if (!preview.success) return patchFailure(state, preview.error);
2099
+ const files = preview.changes.map((change) => change.filePath);
2100
+ const decision = await state.approve({
2101
+ attempt: state.attempts,
2102
+ maxAttempts: state.maxAttempts,
2103
+ rootCause: state.fixSuggestion.rootCause,
2104
+ explanation,
2105
+ files,
2106
+ diff: (0, import_patcher3.renderUnifiedDiff)(preview.changes)
2107
+ });
2108
+ if (!decision.approved) {
2109
+ console.log("[BugZero] Fix declined \u2014 nothing was changed.");
2110
+ const note = decision.note?.trim();
2111
+ const userNote = note ? ` The user's note: "${note}".` : "";
2112
+ const declinedLogs = `${state.logs}
2113
+
2114
+ \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion was declined by the user, so nothing was changed. The files it would have changed were: ${files.join(", ")}.${userNote} Propose a different fix.`;
2115
+ return { logs: declinedLogs, patchFailed: true, declinedFixes: 1 };
2116
+ }
2117
+ }
2118
+ const result = (0, import_patcher3.applyPatches)(state.cwd, patches, {
1913
2119
  alreadyBackedUp: state.backedUpFiles,
1914
2120
  protection: protectionFor(state.cwd)
1915
2121
  });
1916
- if (!result.success) {
1917
- console.error(`[BugZero] Patch failed: ${result.error}`);
1918
- const updatedLogs = `${state.logs}
1919
-
1920
- \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion failed with the following error:
1921
- - ${result.error}
1922
-
1923
- Any other files from that same suggestion were rolled back to keep the change atomic. Please check if the file path(s) are correct relative to the project root and make sure you target the correct file(s) that contain the build error.`;
1924
- return {
1925
- logs: updatedLogs,
1926
- patchFailed: true
1927
- };
1928
- }
2122
+ if (!result.success) return patchFailure(state, result.error);
1929
2123
  for (const applied of result.applied) {
1930
2124
  console.log(`[BugZero] Backup saved to: ${applied.backupPath}`);
1931
2125
  if (applied.matchStrategy !== "exact") {
@@ -2022,9 +2216,9 @@ var require_dist8 = __commonJS({
2022
2216
  });
2023
2217
  module2.exports = __toCommonJS(index_exports);
2024
2218
  var import_fs2 = __toESM2(require("fs"));
2025
- var import_path2 = __toESM2(require("path"));
2219
+ var import_path3 = __toESM2(require("path"));
2026
2220
  function detectFramework2(cwd = process.cwd()) {
2027
- const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path2.default.join(cwd, f)));
2221
+ const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path3.default.join(cwd, f)));
2028
2222
  if (has("next.config.js", "next.config.ts", "next.config.mjs")) return "nextjs";
2029
2223
  if (has("nest-cli.json")) return "nestjs";
2030
2224
  if (has("vite.config.ts", "vite.config.js", "vite.config.mts")) return "vite";
@@ -2032,7 +2226,7 @@ var require_dist8 = __commonJS({
2032
2226
  if (has("astro.config.mjs", "astro.config.ts", "astro.config.js")) return "astro";
2033
2227
  if (has("svelte.config.js", "svelte.config.ts")) return "sveltekit";
2034
2228
  if (has("nuxt.config.ts", "nuxt.config.js")) return "nuxt";
2035
- const pkgPath = import_path2.default.join(cwd, "package.json");
2229
+ const pkgPath = import_path3.default.join(cwd, "package.json");
2036
2230
  if (import_fs2.default.existsSync(pkgPath)) {
2037
2231
  try {
2038
2232
  const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
@@ -2048,14 +2242,14 @@ var require_dist8 = __commonJS({
2048
2242
  if (has("tsconfig.json")) return "typescript";
2049
2243
  return "unknown";
2050
2244
  }
2051
- var import_analyzers = require_dist2();
2245
+ var import_analyzers = require_dist4();
2052
2246
  var import_agents = require_dist7();
2053
- var import_shared22 = require_dist4();
2247
+ var import_shared22 = require_dist2();
2054
2248
  var import_fs3 = __toESM2(require("fs"));
2055
- var import_path3 = __toESM2(require("path"));
2249
+ var import_path32 = __toESM2(require("path"));
2056
2250
  var import_url = require("url");
2057
- var import_prompts = require_dist5();
2058
- var import_shared3 = require_dist4();
2251
+ var import_prompts = require_dist6();
2252
+ var import_shared4 = require_dist2();
2059
2253
  var MAX_REPORT_LOG_CHARS = 2e4;
2060
2254
  function capReportLogs(logs, maxChars = MAX_REPORT_LOG_CHARS) {
2061
2255
  return (0, import_prompts.truncateLogs)(logs, maxChars);
@@ -2093,7 +2287,7 @@ ${p.replace}`
2093
2287
  }
2094
2288
  function buildRescueSuccessPrompt(params) {
2095
2289
  const { cwd, attempts, appliedFix } = params;
2096
- const patchedFiles = (0, import_shared3.uniqueFilePaths)(appliedFix.patches).join(", ");
2290
+ const patchedFiles = (0, import_shared4.uniqueFilePaths)(appliedFix.patches).join(", ");
2097
2291
  return `You are an expert software engineer assistant. An automated AI agent successfully resolved a build/lint/test failure in a project located at "${cwd}" after ${attempts} attempts by applying a patch to: ${patchedFiles}.
2098
2292
  Here is the patch details:
2099
2293
  - Root Cause: ${appliedFix.rootCause}
@@ -2187,8 +2381,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2187
2381
  throw new Error(`No package.json found in ${cwd}. Point --path at a Node.js project.`);
2188
2382
  }
2189
2383
  }
2190
- var import_ai_provider = require_dist3();
2384
+ var import_ai_provider = require_dist5();
2191
2385
  var REPORT_FILENAME2 = "bugzero-report.md";
2386
+ function failureMessage(maxAttempts, declined, appliedAnything) {
2387
+ const plural = declined === 1 ? "fix" : "fixes";
2388
+ if (declined > 0 && !appliedAnything) {
2389
+ return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2390
+ }
2391
+ const base = `Max attempts (${maxAttempts}) reached without a successful build.`;
2392
+ return declined > 0 ? `${base} You declined ${declined} proposed ${plural}.` : base;
2393
+ }
2192
2394
  function statusLabel(result) {
2193
2395
  if (result.skipped) return "\u23ED\uFE0F Skipped (no script defined)";
2194
2396
  return result.success ? "\u2705 Passed" : "\u274C Failed";
@@ -2265,14 +2467,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2265
2467
  cwd,
2266
2468
  logs: pipelineResult.output,
2267
2469
  maxAttempts,
2268
- timeoutMs
2470
+ timeoutMs,
2471
+ approve: options.approve
2269
2472
  });
2270
2473
  const result = {
2271
2474
  success: finalState.success,
2272
2475
  attempts: finalState.attempts,
2273
2476
  finalOutput: finalState.logs || pipelineResult.output,
2274
2477
  appliedFix: finalState.appliedFix ?? void 0,
2275
- error: finalState.success ? void 0 : `Max attempts (${maxAttempts}) reached without a successful build.`,
2478
+ error: finalState.success ? void 0 : failureMessage(maxAttempts, finalState.declinedFixes ?? 0, Boolean(finalState.appliedFix)),
2479
+ declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2276
2480
  modelUsed: finalState.modelUsed,
2277
2481
  promptTokens: finalState.promptTokens,
2278
2482
  completionTokens: finalState.completionTokens
@@ -2481,7 +2685,7 @@ ${rawOutput}
2481
2685
 
2482
2686
  ---
2483
2687
  *Report generated by **BugZero** on ${(/* @__PURE__ */ new Date()).toLocaleString()}*`;
2484
- const reportPath = import_path3.default.resolve(cwd, REPORT_FILENAME2);
2688
+ const reportPath = import_path32.default.resolve(cwd, REPORT_FILENAME2);
2485
2689
  try {
2486
2690
  import_fs3.default.writeFileSync(reportPath, content, "utf-8");
2487
2691
  const clickableUrl = (0, import_url.pathToFileURL)(reportPath).toString();
@@ -2499,19 +2703,21 @@ ${rawOutput}
2499
2703
  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");
2500
2704
  }
2501
2705
  }
2502
- var import_analyzers2 = require_dist2();
2706
+ var import_analyzers2 = require_dist4();
2503
2707
  }
2504
2708
  });
2505
2709
 
2506
2710
  // src/index.ts
2507
2711
  var import_config = __toESM(require_dist());
2712
+ var import_patcher2 = __toESM(require_dist3());
2713
+ var import_shared3 = __toESM(require_dist2());
2508
2714
  var import_commander = require("commander");
2509
2715
  var import_fs = __toESM(require("fs"));
2510
- var import_path = __toESM(require("path"));
2716
+ var import_path2 = __toESM(require("path"));
2511
2717
  var import_core = __toESM(require_dist8());
2512
2718
 
2513
2719
  // src/json-output.ts
2514
- var import_shared = __toESM(require_dist4());
2720
+ var import_shared = __toESM(require_dist2());
2515
2721
  function stepStatus(step) {
2516
2722
  if (step.skipped) return "skipped";
2517
2723
  return step.success ? "passed" : "failed";
@@ -2570,9 +2776,62 @@ function buildErrorJson(message) {
2570
2776
  return { success: false, error: message };
2571
2777
  }
2572
2778
 
2779
+ // src/approval.ts
2780
+ var import_readline = __toESM(require("readline"));
2781
+ var MAX_INVALID_ANSWERS = 5;
2782
+ function parseApprovalAnswer(raw) {
2783
+ const answer = raw.trim().toLowerCase();
2784
+ if (answer === "y" || answer === "yes") return "yes";
2785
+ if (answer === "" || answer === "n" || answer === "no") return "no";
2786
+ if (answer === "m" || answer === "note") return "note";
2787
+ return "invalid";
2788
+ }
2789
+ function createApprovalHandler(io) {
2790
+ const lines = import_readline.default.createInterface({ input: io.input, terminal: false })[Symbol.asyncIterator]();
2791
+ const ask = async (question) => {
2792
+ io.output.write(question);
2793
+ const next = await lines.next();
2794
+ return next.done ? void 0 : next.value;
2795
+ };
2796
+ return async (request) => {
2797
+ io.output.write(
2798
+ [
2799
+ "",
2800
+ `Proposed fix (attempt ${request.attempt}/${request.maxAttempts})`,
2801
+ ` Root cause: ${request.rootCause}`,
2802
+ ` Explanation: ${request.explanation}`,
2803
+ ` Files: ${request.files.join(", ")}`,
2804
+ "",
2805
+ request.diff,
2806
+ "",
2807
+ ""
2808
+ ].join("\n")
2809
+ );
2810
+ for (let invalid = 0; invalid < MAX_INVALID_ANSWERS; ) {
2811
+ const raw = await ask("Apply this change? [y] yes [n] no [m] no, and leave a note for the AI (Enter = no): ");
2812
+ if (raw === void 0) {
2813
+ io.output.write("\nNo answer, so the change was not applied.\n");
2814
+ return { approved: false };
2815
+ }
2816
+ const answer = parseApprovalAnswer(raw);
2817
+ if (answer === "yes") return { approved: true };
2818
+ if (answer === "no") return { approved: false };
2819
+ if (answer === "note") {
2820
+ const note = (await ask("Note for the AI: "))?.trim();
2821
+ return note ? { approved: false, note } : { approved: false };
2822
+ }
2823
+ invalid++;
2824
+ io.output.write("Please answer y, n or m.\n");
2825
+ }
2826
+ io.output.write("Too many unclear answers, so the change was not applied.\n");
2827
+ return { approved: false };
2828
+ };
2829
+ }
2830
+
2573
2831
  // src/summary.ts
2574
- var import_patcher = __toESM(require_dist6());
2575
- var import_shared2 = __toESM(require_dist4());
2832
+ var import_patcher = __toESM(require_dist3());
2833
+ var import_path = __toESM(require("path"));
2834
+ var import_shared2 = __toESM(require_dist2());
2576
2835
  function tokenLines(result) {
2577
2836
  if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
2578
2837
  const total = result.promptTokens + result.completionTokens;
@@ -2628,10 +2887,35 @@ function buildChangeDiffLines(cwd, result) {
2628
2887
  if (diff === "") return [];
2629
2888
  return ["", "Changes (the original of each file is kept next to it as <file>.opspilot.bak):", "", ...diff.split("\n")];
2630
2889
  }
2890
+ function buildUndoHintLines(cwd, result, options) {
2891
+ if (options.dryRun || !result.appliedFix) return [];
2892
+ const command = import_path.default.resolve(cwd) === import_path.default.resolve(process.cwd()) ? "bugzero undo" : `bugzero undo --path "${import_path.default.resolve(cwd)}"`;
2893
+ const lead = result.success ? "To put the files back as they were:" : "BugZero changed files before giving up. To put them back as they were:";
2894
+ return ["", `${lead} ${command}`];
2895
+ }
2896
+ function buildUndoSummary(entries, options) {
2897
+ if (entries.length === 0) {
2898
+ return { exitCode: 0, lines: ["Nothing to undo \u2014 no BugZero backups (*.opspilot.bak) were found."] };
2899
+ }
2900
+ const lines = [];
2901
+ for (const entry of entries) {
2902
+ if (entry.status === "restored") lines.push(`\u21A9\uFE0F Restored ${entry.filePath}`);
2903
+ else if (entry.status === "would-restore") lines.push(`\u21A9\uFE0F Would restore ${entry.filePath}`);
2904
+ else lines.push(`\u23ED\uFE0F Skipped ${entry.filePath}: ${entry.detail ?? entry.status}`);
2905
+ }
2906
+ const done = entries.filter((entry) => entry.status === "restored" || entry.status === "would-restore").length;
2907
+ const left = entries.length - done;
2908
+ lines.push("");
2909
+ lines.push(
2910
+ options.dryRun ? `Dry run: ${done} file(s) would be restored. Nothing was changed.` : `Restored ${done} file(s).`
2911
+ );
2912
+ if (left > 0) lines.push(`${left} file(s) were left as they are, with their backups kept.`);
2913
+ return { exitCode: left > 0 ? 1 : 0, lines };
2914
+ }
2631
2915
 
2632
2916
  // src/index.ts
2633
2917
  (0, import_config.loadProjectEnv)(process.cwd());
2634
- var { version } = JSON.parse(import_fs.default.readFileSync(import_path.default.join(__dirname, "..", "package.json"), "utf-8"));
2918
+ var { version } = JSON.parse(import_fs.default.readFileSync(import_path2.default.join(__dirname, "..", "package.json"), "utf-8"));
2635
2919
  var TIMEOUT_DESCRIPTION = "Stop any build/lint/test command that runs longer than this many seconds";
2636
2920
  function parseTimeout(raw) {
2637
2921
  if (raw === void 0) return void 0;
@@ -2657,7 +2941,7 @@ program.command("hunt").description("Run build, lint, and tests \u2014 report is
2657
2941
  const json = opts.json === true;
2658
2942
  if (json) routeLogsToStderr();
2659
2943
  try {
2660
- const cwd = import_path.default.resolve(opts.path);
2944
+ const cwd = import_path2.default.resolve(opts.path);
2661
2945
  (0, import_config.loadProjectEnv)(cwd);
2662
2946
  const timeoutSeconds = parseTimeout(opts.timeout);
2663
2947
  const framework = (0, import_core.detectFramework)(cwd);
@@ -2683,7 +2967,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2683
2967
  finish(
2684
2968
  allPassed ? 0 : 1,
2685
2969
  json ? buildHuntJson(
2686
- { path: cwd, framework, packageManager, reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME) },
2970
+ { path: cwd, framework, packageManager, reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME) },
2687
2971
  { build, lint, test }
2688
2972
  ) : void 0
2689
2973
  );
@@ -2693,16 +2977,25 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2693
2977
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2694
2978
  }
2695
2979
  });
2696
- 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("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).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) => {
2980
+ 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("--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) => {
2697
2981
  const json = opts.json === true;
2698
2982
  const printPrompt = opts.printPrompt === true;
2699
2983
  if (json || printPrompt) routeLogsToStderr();
2700
2984
  try {
2701
- const cwd = import_path.default.resolve(opts.path);
2985
+ const cwd = import_path2.default.resolve(opts.path);
2702
2986
  (0, import_config.loadProjectEnv)(cwd);
2703
2987
  const maxAttempts = (0, import_core.resolveMaxAttempts)(Number(opts.maxAttempts));
2704
2988
  const timeoutSeconds = parseTimeout(opts.timeout);
2705
2989
  const dryRun = opts.dryRun;
2990
+ let approve;
2991
+ if (opts.approve === true && !dryRun && !printPrompt) {
2992
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
2993
+ throw new Error(
2994
+ "--approve asks you to confirm each fix, which needs an interactive terminal, and there is none here (for example in CI, or when input is piped). Run it in a terminal, or leave out --approve."
2995
+ );
2996
+ }
2997
+ approve = createApprovalHandler({ input: process.stdin, output: process.stderr });
2998
+ }
2706
2999
  const framework = (0, import_core.detectFramework)(cwd);
2707
3000
  const packageManager = (0, import_core.detectPackageManager)(cwd);
2708
3001
  console.log(`
@@ -2714,7 +3007,7 @@ program.command("rescue").description("Detect build failures and automatically a
2714
3007
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
2715
3008
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
2716
3009
  console.log();
2717
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt });
3010
+ const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve });
2718
3011
  if (result.promptPreview !== void 0) {
2719
3012
  if (json) {
2720
3013
  finish(
@@ -2724,7 +3017,7 @@ program.command("rescue").description("Detect build failures and automatically a
2724
3017
  framework,
2725
3018
  packageManager,
2726
3019
  dryRun,
2727
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3020
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2728
3021
  })
2729
3022
  );
2730
3023
  } else {
@@ -2737,6 +3030,7 @@ program.command("rescue").description("Detect build failures and automatically a
2737
3030
  const summary = buildRescueSummary(result, { dryRun });
2738
3031
  for (const line of summary.lines) console.log(line);
2739
3032
  for (const line of buildChangeDiffLines(cwd, result)) console.log(line);
3033
+ for (const line of buildUndoHintLines(cwd, result, { dryRun })) console.log(line);
2740
3034
  console.log();
2741
3035
  finish(
2742
3036
  summary.exitCode,
@@ -2745,7 +3039,7 @@ program.command("rescue").description("Detect build failures and automatically a
2745
3039
  framework,
2746
3040
  packageManager,
2747
3041
  dryRun,
2748
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3042
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2749
3043
  }) : void 0
2750
3044
  );
2751
3045
  } catch (error) {
@@ -2754,6 +3048,25 @@ program.command("rescue").description("Detect build failures and automatically a
2754
3048
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2755
3049
  }
2756
3050
  });
3051
+ program.command("undo").description("Put back the files BugZero changed, from the backups saved next to them").option("-p, --path <dir>", "Path to the target project", ".").option("--dry-run", "Show what would be restored without changing anything", false).option("--force", "Also restore files that were edited after BugZero fixed them (those edits are lost)", false).action((opts) => {
3052
+ try {
3053
+ const cwd = import_path2.default.resolve(opts.path);
3054
+ const entries = (0, import_patcher2.undoChanges)(cwd, {
3055
+ dryRun: opts.dryRun === true,
3056
+ force: opts.force === true,
3057
+ protection: (0, import_shared3.createProtectedPathRules)((0, import_config.getProtectionSettings)(cwd))
3058
+ });
3059
+ const summary = buildUndoSummary(entries, { dryRun: opts.dryRun === true });
3060
+ console.log();
3061
+ for (const line of summary.lines) console.log(line);
3062
+ console.log();
3063
+ finish(summary.exitCode);
3064
+ } catch (error) {
3065
+ console.error(`
3066
+ \u274C [BugZero] Execution failed: ${error.message || error}`);
3067
+ finish(1);
3068
+ }
3069
+ });
2757
3070
  program.command("protect").description("[Deprecated] Use 'hunt' instead").action(async () => {
2758
3071
  console.warn("\u26A0\uFE0F 'protect' is deprecated \u2014 use 'bugzero hunt' instead.\n");
2759
3072
  const result = await (0, import_core.orchestrate)();
@@ -2761,7 +3074,7 @@ program.command("protect").description("[Deprecated] Use 'hunt' instead").action
2761
3074
  });
2762
3075
  program.command("vibe").description("Select which AI model (brain) to use for resolving bugs").action(async () => {
2763
3076
  const { getLocalConfig, saveLocalConfig } = await Promise.resolve().then(() => __toESM(require_dist()));
2764
- const readline = await import("readline");
3077
+ const readline2 = await import("readline");
2765
3078
  const axios = (await import("axios")).default;
2766
3079
  console.log(`
2767
3080
  \u{1F9E0} BugZero Brain Selector`);
@@ -2804,7 +3117,7 @@ Current active model: \x1B[36m${currentModel}\x1B[0m
2804
3117
  });
2805
3118
  console.log(` [${popularModels.length + 1}] \u{1F58B}\uFE0F Custom Model (Type manually)`);
2806
3119
  console.log();
2807
- const rl = readline.createInterface({
3120
+ const rl = readline2.createInterface({
2808
3121
  input: process.stdin,
2809
3122
  output: process.stdout
2810
3123
  });