bugzero 0.0.57 → 0.0.59

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 +22 -2
  2. package/dist/index.js +1430 -1178
  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,568 +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 };
937
- }
938
- var import_fs22 = __toESM2(require("fs"));
939
- var import_path22 = __toESM2(require("path"));
940
- var DEFAULT_SECRET_PATTERNS = [".env", ".env.*", "*.pem", "*.key"];
941
- var DEFAULT_PROTECTED_PATTERNS = [
942
- ...DEFAULT_SECRET_PATTERNS,
943
- ".git/",
944
- ".github/workflows/",
945
- ".gitlab-ci.yml",
946
- ".circleci/",
947
- "azure-pipelines.yml",
948
- "bitbucket-pipelines.yml",
949
- "Jenkinsfile",
950
- "package-lock.json",
951
- "pnpm-lock.yaml",
952
- "yarn.lock",
953
- "bun.lockb",
954
- "node_modules/",
955
- "*.opspilot.bak"
956
- ];
957
- function normalizePath(relPath) {
958
- return relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+/, "").toLowerCase();
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 };
959
843
  }
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
+ };
986
851
  }
987
- }
988
- const regex = new RegExp(`^${anchored ? "" : "(?:.*/)?"}${source}(?:/.*)?$`);
989
- return { pattern: pattern.trim(), test: (normalizedPath) => regex.test(normalizedPath) };
990
- }
991
- function compileAll(patterns) {
992
- return (patterns ?? []).map(compilePattern).filter((m) => m !== void 0);
993
- }
994
- function firstMatch(matchers, normalizedPath) {
995
- return matchers.find((m) => m.test(normalizedPath));
996
- }
997
- function createProtectedPathRules(settings = {}) {
998
- const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
999
- const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
1000
- const extra = compileAll(settings.protect);
1001
- const allowed = compileAll(settings.allow);
1002
- return {
1003
- editBlockedBy(relPath) {
1004
- const normalized = normalizePath(relPath);
1005
- const own = firstMatch(extra, normalized);
1006
- if (own) return own.pattern;
1007
- if (firstMatch(allowed, normalized)) return void 0;
1008
- return firstMatch(defaults, normalized)?.pattern;
1009
- },
1010
- secretBlockedBy(relPath) {
1011
- const normalized = normalizePath(relPath);
1012
- if (firstMatch(allowed, normalized)) return void 0;
1013
- return firstMatch(secrets, normalized)?.pattern;
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");
1014
858
  }
1015
- };
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 };
863
+ }
1016
864
  }
1017
- function toRelative(root, target) {
1018
- return import_path22.default.relative(root, target).split(import_path22.default.sep).join("/");
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");
1019
871
  }
1020
- function realPathAllowingMissing(target) {
1021
- let current = import_path22.default.resolve(target);
1022
- const rest = [];
1023
- while (true) {
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 {
1024
877
  try {
1025
- return import_path22.default.join(import_fs22.default.realpathSync.native(current), ...rest.reverse());
878
+ import_fs22.default.unlinkSync(notePath);
1026
879
  } 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
880
  }
1032
881
  }
1033
882
  }
1034
- function projectRelativePaths(cwd, absolutePath) {
1035
- const paths = [toRelative(import_path22.default.resolve(cwd), import_path22.default.resolve(absolutePath))];
1036
- const realRoot = realPathAllowingMissing(cwd);
1037
- const realTarget = realPathAllowingMissing(absolutePath);
1038
- if (realRoot && realTarget) {
1039
- const real = toRelative(realRoot, realTarget);
1040
- if (real !== paths[0] && !real.startsWith("..")) paths.push(real);
1041
- }
1042
- return paths;
1043
- }
1044
- }
1045
- });
1046
-
1047
- // ../../packages/prompts/dist/index.js
1048
- var require_dist5 = __commonJS({
1049
- "../../packages/prompts/dist/index.js"(exports2, module2) {
1050
- "use strict";
1051
- var __create2 = Object.create;
1052
- var __defProp2 = Object.defineProperty;
1053
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1054
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
1055
- var __getProtoOf2 = Object.getPrototypeOf;
1056
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1057
- var __export = (target, all) => {
1058
- for (var name in all)
1059
- __defProp2(target, name, { get: all[name], enumerable: true });
1060
- };
1061
- var __copyProps2 = (to, from, except, desc) => {
1062
- if (from && typeof from === "object" || typeof from === "function") {
1063
- for (let key of __getOwnPropNames2(from))
1064
- if (!__hasOwnProp2.call(to, key) && key !== except)
1065
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1066
- }
1067
- return to;
1068
- };
1069
- var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1070
- // If the importer is in node compatibility mode or this is not an ESM
1071
- // file that has been converted to a CommonJS file using a Babel-
1072
- // compatible transform (i.e. "__esModule" has not been set), then set
1073
- // "default" to the CommonJS "module.exports" for node compatibility.
1074
- isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1075
- mod
1076
- ));
1077
- var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1078
- var index_exports = {};
1079
- __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 {
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}` };
1109
890
  }
1110
- const lastSpace = current.lastIndexOf(" ");
1111
- if (lastSpace === -1) {
1112
- const lastSlash = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
1113
- if (lastSlash === -1) {
1114
- break;
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
+ };
1115
898
  }
1116
- current = current.slice(0, lastSlash).trim();
1117
- } else {
1118
- current = current.slice(0, lastSpace).trim();
1119
899
  }
900
+ absolutePaths.push(resolved.absolutePath);
1120
901
  }
1121
- return null;
902
+ return { ok: true, absolutePaths };
1122
903
  }
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);
904
+ function rollback(originalContent, backupPaths) {
905
+ for (const [absolutePath, content] of originalContent) {
906
+ try {
907
+ import_fs3.default.writeFileSync(absolutePath, content, "utf-8");
908
+ } catch {
1131
909
  }
1132
910
  }
1133
- const winAbsRegex = /([a-zA-Z]:\\[^*?"<>|\n\r]+)/g;
1134
- while ((match = winAbsRegex.exec(logs)) !== null) {
1135
- candidates.add(match[1].trim());
1136
- }
1137
- const unixAbsRegex = /(\/[^*?"<>|\n\r\t]+)/g;
1138
- while ((match = unixAbsRegex.exec(logs)) !== null) {
1139
- candidates.add(match[1].trim());
911
+ for (const backupPath of backupPaths) {
912
+ try {
913
+ import_fs3.default.unlinkSync(backupPath);
914
+ } catch {
915
+ }
1140
916
  }
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());
917
+ }
918
+ function applyPatches(cwd, patches, options = {}) {
919
+ if (patches.length === 0) {
920
+ return { success: false, error: "No patches to apply.", applied: [] };
1145
921
  }
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
- }
922
+ const targets = resolvePatchTargets(cwd, patches, options.protection);
923
+ if (!targets.ok) {
924
+ return { success: false, error: targets.error, applied: [] };
1153
925
  }
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]`;
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
+ };
1172
943
  }
1173
- context += `
1174
- --- File: ${relPath} ---
1175
- \`\`\`
1176
- ${content}
1177
- \`\`\`
1178
- `;
1179
- } catch {
1180
944
  }
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 {
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
+ };
1237
958
  }
959
+ applied.push({
960
+ filePath: patch.filePath,
961
+ absolutePath,
962
+ backupPath: result.backupPath,
963
+ matchStrategy: result.matchStrategy
964
+ });
1238
965
  }
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.`;
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);
1256
971
  }
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"
972
+ return { success: true, applied };
1281
973
  }
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.`;
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;
1293
1260
  }
1294
1261
  }
1295
1262
  });
1296
1263
 
1297
- // ../../packages/patcher/dist/index.js
1298
- var require_dist6 = __commonJS({
1299
- "../../packages/patcher/dist/index.js"(exports2, module2) {
1264
+ // ../../packages/analyzers/dist/index.js
1265
+ var require_dist4 = __commonJS({
1266
+ "../../packages/analyzers/dist/index.js"(exports2, module2) {
1300
1267
  "use strict";
1301
1268
  var __create2 = Object.create;
1302
1269
  var __defProp2 = Object.defineProperty;
@@ -1327,454 +1294,604 @@ var require_dist6 = __commonJS({
1327
1294
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1328
1295
  var index_exports = {};
1329
1296
  __export(index_exports, {
1330
- applyPatch: () => applyPatch,
1331
- applyPatches: () => applyPatches,
1332
- findMatch: () => findMatch,
1333
- lineSimilarity: () => lineSimilarity,
1334
- patchContent: () => patchContent,
1335
- previewPatches: () => previewPatches,
1336
- renderChangesFromBackups: () => renderChangesFromBackups2,
1337
- renderUnifiedDiff: () => renderUnifiedDiff,
1338
- resolvePatchTargets: () => resolvePatchTargets
1339
- });
1340
- module2.exports = __toCommonJS(index_exports);
1341
- var import_fs2 = __toESM2(require("fs"));
1342
- var import_path2 = __toESM2(require("path"));
1343
- var SIMILARITY_THRESHOLD = 0.85;
1344
- var AMBIGUITY_MARGIN = 0.05;
1345
- var MAX_LINES_FOR_SIMILARITY_PASS = 2e4;
1346
- function splitLinesWithOffsets(text) {
1347
- const lines = [];
1348
- let start = 0;
1349
- for (let i = 0; i < text.length; i++) {
1350
- if (text[i] === "\n") {
1351
- let end = i;
1352
- if (end > start && text[end - 1] === "\r") end -= 1;
1353
- lines.push({ text: text.slice(start, end), start, end });
1354
- start = i + 1;
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
+ }
1332
+ }
1355
1333
  }
1334
+ } catch {
1356
1335
  }
1357
- lines.push({ text: text.slice(start), start, end: text.length });
1358
- return lines;
1359
- }
1360
- function normalizeLine(line) {
1361
- return line.trim().replace(/\s+/g, " ");
1362
- }
1363
- function levenshtein(a, b) {
1364
- const m = a.length;
1365
- const n = b.length;
1366
- if (m === 0) return n;
1367
- if (n === 0) return m;
1368
- const dp = new Array(n + 1);
1369
- for (let j = 0; j <= n; j++) dp[j] = j;
1370
- for (let i = 1; i <= m; i++) {
1371
- let prev = dp[0];
1372
- dp[0] = i;
1373
- for (let j = 1; j <= n; j++) {
1374
- const temp = dp[j];
1375
- dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j], dp[j - 1]);
1376
- prev = temp;
1377
- }
1336
+ for (const { file, manager } of LOCKFILE_MANAGERS) {
1337
+ if (import_fs3.default.existsSync(import_path4.default.join(cwd, file))) return manager;
1378
1338
  }
1379
- return dp[n];
1339
+ return "npm";
1380
1340
  }
1381
- function lineSimilarity(a, b) {
1382
- const maxLen = Math.max(a.length, b.length);
1383
- if (maxLen === 0) return 1;
1384
- return 1 - levenshtein(a, b) / maxLen;
1341
+ function getRunScriptCommand(manager, script) {
1342
+ return `${manager} run ${script}`;
1385
1343
  }
1386
- function findWhitespaceNormalizedMatch(content, search) {
1387
- const searchLines = search.split(/\r\n|\n/).map(normalizeLine);
1388
- const contentLines = splitLinesWithOffsets(content);
1389
- if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
1390
- const normalizedContentLines = contentLines.map((l) => normalizeLine(l.text));
1391
- for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
1392
- let matches = true;
1393
- for (let j = 0; j < searchLines.length; j++) {
1394
- if (normalizedContentLines[i + j] !== searchLines[j]) {
1395
- matches = false;
1396
- break;
1397
- }
1398
- }
1399
- if (matches) {
1400
- const firstLine = contentLines[i];
1401
- const lastLine = contentLines[i + searchLines.length - 1];
1402
- return { start: firstLine.start, end: lastLine.end, strategy: "whitespace", score: 1 };
1403
- }
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;
1404
1353
  }
1405
- return null;
1354
+ (0, import_tree_kill.default)(pid, "SIGKILL");
1406
1355
  }
1407
- function findSimilarityMatch(content, search) {
1408
- const searchLines = search.split(/\r\n|\n/);
1409
- const contentLines = splitLinesWithOffsets(content);
1410
- if (searchLines.length === 0 || searchLines.length > contentLines.length) return null;
1411
- if (contentLines.length > MAX_LINES_FOR_SIMILARITY_PASS) return null;
1412
- let bestIndex = -1;
1413
- let bestScore = -1;
1414
- let secondBestScore = -1;
1415
- for (let i = 0; i + searchLines.length <= contentLines.length; i++) {
1416
- let total = 0;
1417
- for (let j = 0; j < searchLines.length; j++) {
1418
- total += lineSimilarity(searchLines[j], contentLines[i + j].text);
1419
- }
1420
- const avgScore = total / searchLines.length;
1421
- if (avgScore > bestScore) {
1422
- secondBestScore = bestScore;
1423
- bestScore = avgScore;
1424
- bestIndex = i;
1425
- } else if (avgScore > secondBestScore) {
1426
- secondBestScore = avgScore;
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"
1427
1366
  }
1428
- }
1429
- if (bestIndex === -1 || bestScore < SIMILARITY_THRESHOLD) return null;
1430
- if (secondBestScore >= 0 && bestScore - secondBestScore < AMBIGUITY_MARGIN) return null;
1431
- const firstLine = contentLines[bestIndex];
1432
- const lastLine = contentLines[bestIndex + searchLines.length - 1];
1433
- return { start: firstLine.start, end: lastLine.end, strategy: "similarity", score: bestScore };
1434
- }
1435
- function findMatch(content, search) {
1436
- const exactIndex = content.indexOf(search);
1437
- if (exactIndex !== -1) {
1438
- return { start: exactIndex, end: exactIndex + search.length, strategy: "exact", score: 1 };
1439
- }
1440
- return findWhitespaceNormalizedMatch(content, search) ?? findSimilarityMatch(content, search);
1441
- }
1442
- var CRLF = "\r\n";
1443
- var LF = "\n";
1444
- function countEndings(text) {
1445
- const crlf = text.split(CRLF).length - 1;
1446
- const lf = text.split(LF).length - 1 - crlf;
1447
- return { crlf, lf };
1448
- }
1449
- function detectLineEnding(text, start, end) {
1450
- const inside = countEndings(text.slice(start, end));
1451
- if (inside.crlf !== inside.lf) return inside.crlf > inside.lf ? CRLF : LF;
1452
- const nextBreak = text.indexOf(LF, end);
1453
- if (nextBreak !== -1) return text[nextBreak - 1] === "\r" ? CRLF : LF;
1454
- const previousBreak = start > 0 ? text.lastIndexOf(LF, start - 1) : -1;
1455
- if (previousBreak !== -1) return text[previousBreak - 1] === "\r" ? CRLF : LF;
1456
- const whole = countEndings(text);
1457
- return whole.crlf > whole.lf ? CRLF : LF;
1458
- }
1459
- function withLineEnding(text, ending) {
1460
- return text.replace(/\r\n|\n/g, ending);
1461
- }
1462
- function patchContent(original, search, replace, fileName) {
1463
- const match = findMatch(original, search);
1464
- if (!match) {
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";
1465
1371
  return {
1466
- ok: false,
1467
- error: `Search string not found in ${fileName} (tried exact, whitespace-normalized, and fuzzy matching). The AI's "search" field did not match file content.`
1372
+ success: false,
1373
+ timedOut: true,
1374
+ output: `${output}
1375
+
1376
+ [BugZero] Command timed out after ${seconds}s ${note}: ${command}`
1468
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);
1469
1402
  }
1470
- const replacement = withLineEnding(replace, detectLineEnding(original, match.start, match.end));
1471
- const content = original.slice(0, match.start) + replacement + original.slice(match.end);
1472
- return { ok: true, content, matchStrategy: match.strategy };
1473
1403
  }
1474
- function applyPatch(absoluteFilePath, search, replace, options = {}) {
1404
+ function readScripts(cwd = process.cwd()) {
1475
1405
  try {
1476
- if (!import_fs2.default.existsSync(absoluteFilePath)) {
1477
- return {
1478
- success: false,
1479
- error: `File not found: ${absoluteFilePath}`
1480
- };
1481
- }
1482
- const original = import_fs2.default.readFileSync(absoluteFilePath, "utf-8");
1483
- const patched = patchContent(original, search, replace, import_path2.default.basename(absoluteFilePath));
1484
- if (!patched.ok) return { success: false, error: patched.error };
1485
- const backupPath = absoluteFilePath + ".opspilot.bak";
1486
- if (options.backup !== false) {
1487
- import_fs2.default.writeFileSync(backupPath, original, "utf-8");
1488
- }
1489
- import_fs2.default.writeFileSync(absoluteFilePath, patched.content, "utf-8");
1490
- return { success: true, backupPath, matchStrategy: patched.matchStrategy };
1491
- } catch (err) {
1492
- return { success: false, error: err.message };
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 [];
1493
1413
  }
1494
1414
  }
1495
- var import_fs22 = __toESM2(require("fs"));
1496
- var import_shared3 = require_dist4();
1497
- function resolvePatchTargets(cwd, patches, protection = (0, import_shared3.createProtectedPathRules)()) {
1498
- const absolutePaths = [];
1499
- for (const patch of patches) {
1500
- const resolved = (0, import_shared3.resolveInsideProject)(cwd, patch.filePath);
1501
- if (!resolved.ok) {
1502
- return { ok: false, error: `Failed to patch "${patch.filePath}": ${resolved.error}` };
1503
- }
1504
- for (const relPath of (0, import_shared3.projectRelativePaths)(cwd, resolved.absolutePath)) {
1505
- const pattern = protection.editBlockedBy(relPath);
1506
- if (pattern !== void 0) {
1507
- return {
1508
- ok: false,
1509
- 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.`
1510
- };
1511
- }
1512
- }
1513
- absolutePaths.push(resolved.absolutePath);
1415
+ async function runScript(script, cwd, options) {
1416
+ if (!readScripts(cwd).includes(script)) {
1417
+ return { success: true, output: "", skipped: true };
1514
1418
  }
1515
- return { ok: true, absolutePaths };
1419
+ return runCommand(getRunScriptCommand(detectPackageManager3(cwd), script), cwd, options);
1516
1420
  }
1517
- function rollback(originalContent, backupPaths) {
1518
- for (const [absolutePath, content] of originalContent) {
1519
- try {
1520
- import_fs22.default.writeFileSync(absolutePath, content, "utf-8");
1521
- } catch {
1522
- }
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(rawOutput) {
1429
+ const output = rawOutput.replace(/\r\n/g, "\n");
1430
+ const errors = [];
1431
+ const tsMatches = [...output.matchAll(TS_ERROR_RE)];
1432
+ for (const m of tsMatches) {
1433
+ errors.push({
1434
+ type: "typescript",
1435
+ file: m[1].trim(),
1436
+ line: parseInt(m[2], 10),
1437
+ column: parseInt(m[3], 10),
1438
+ message: m[4].trim(),
1439
+ raw: m[0]
1440
+ });
1523
1441
  }
1524
- for (const backupPath of backupPaths) {
1525
- try {
1526
- import_fs22.default.unlinkSync(backupPath);
1527
- } catch {
1528
- }
1442
+ if (errors.length > 0) return errors;
1443
+ const eslintMatches = [...output.matchAll(ESLINT_ERROR_RE)];
1444
+ for (const m of eslintMatches) {
1445
+ errors.push({
1446
+ type: "eslint",
1447
+ line: parseInt(m[1], 10),
1448
+ column: parseInt(m[2], 10),
1449
+ message: m[3].trim(),
1450
+ raw: m[0]
1451
+ });
1529
1452
  }
1530
- }
1531
- function applyPatches(cwd, patches, options = {}) {
1532
- if (patches.length === 0) {
1533
- return { success: false, error: "No patches to apply.", applied: [] };
1453
+ if (errors.length > 0) return errors;
1454
+ const jestFiles = [...output.matchAll(JEST_FILE_RE)].map((m) => m[1]);
1455
+ const jestFails = [...output.matchAll(JEST_FAIL_RE)];
1456
+ for (const m of jestFails) {
1457
+ errors.push({
1458
+ type: "jest",
1459
+ file: jestFiles[0],
1460
+ message: m[1].trim(),
1461
+ raw: m[0]
1462
+ });
1534
1463
  }
1535
- const targets = resolvePatchTargets(cwd, patches, options.protection);
1536
- if (!targets.ok) {
1537
- return { success: false, error: targets.error, applied: [] };
1464
+ if (errors.length > 0) return errors;
1465
+ if (output.trim()) {
1466
+ errors.push({
1467
+ type: "unknown",
1468
+ message: output.slice(0, 500),
1469
+ raw: output
1470
+ });
1538
1471
  }
1539
- const absolutePaths = targets.absolutePaths;
1540
- const originalContent = /* @__PURE__ */ new Map();
1541
- const backupPaths = /* @__PURE__ */ new Set();
1542
- const applied = [];
1543
- const backedUp = new Set(options.alreadyBackedUp ?? []);
1544
- for (const [index, patch] of patches.entries()) {
1545
- const absolutePath = absolutePaths[index];
1546
- if (!originalContent.has(absolutePath)) {
1547
- try {
1548
- originalContent.set(absolutePath, import_fs22.default.readFileSync(absolutePath, "utf-8"));
1549
- } catch {
1550
- rollback(originalContent, backupPaths);
1551
- return {
1552
- success: false,
1553
- error: `Failed to patch "${patch.filePath}": File not found: ${absolutePath}`,
1554
- applied: []
1555
- };
1556
- }
1557
- }
1558
- const needsBackup = !backedUp.has(absolutePath);
1559
- const result = applyPatch(absolutePath, patch.search, patch.replace, { backup: needsBackup });
1560
- if (result.success && needsBackup) {
1561
- backedUp.add(absolutePath);
1562
- backupPaths.add(result.backupPath);
1472
+ return errors;
1473
+ }
1474
+ var STEPS = [
1475
+ { step: "build", label: "build", run: runBuild },
1476
+ { step: "lint", label: "lint", run: runLint },
1477
+ { step: "test", label: "tests", run: runTests }
1478
+ ];
1479
+ async function runValidationPipeline(cwd, options) {
1480
+ const targetCwd = cwd ?? process.cwd();
1481
+ const scripts = readScripts(targetCwd);
1482
+ let ranAnyStep = false;
1483
+ for (const { step, label, run } of STEPS) {
1484
+ if (!scripts.includes(step)) {
1485
+ console.log(`[BugZero] Skipping ${label}: no "${step}" script in package.json.`);
1486
+ continue;
1563
1487
  }
1488
+ ranAnyStep = true;
1489
+ console.log(`[BugZero] Running ${label}...`);
1490
+ const result = await run(targetCwd, options);
1564
1491
  if (!result.success) {
1565
- rollback(originalContent, backupPaths);
1566
- return {
1567
- success: false,
1568
- error: `Failed to patch "${patch.filePath}": ${result.error}`,
1569
- applied: []
1570
- };
1492
+ return { success: false, step, output: result.output };
1571
1493
  }
1572
- applied.push({
1573
- filePath: patch.filePath,
1574
- absolutePath,
1575
- backupPath: result.backupPath,
1576
- matchStrategy: result.matchStrategy
1577
- });
1578
1494
  }
1579
- return { success: true, applied };
1580
- }
1581
- var import_shared22 = require_dist4();
1582
- var import_fs3 = __toESM2(require("fs"));
1583
- var import_path22 = __toESM2(require("path"));
1584
- var DEFAULT_CONTEXT = 3;
1585
- var DEFAULT_MAX_LINE_LENGTH = 200;
1586
- var MAX_EDIT_DISTANCE = 1500;
1587
- var NO_NEWLINE = "\0no-newline";
1588
- function toLines(text) {
1589
- if (text === "") return [];
1590
- const parts = text.split("\n");
1591
- if (parts[parts.length - 1] === "") parts.pop();
1592
- else parts[parts.length - 1] += NO_NEWLINE;
1593
- return parts;
1594
- }
1595
- function diffLines(a, b) {
1596
- const n = a.length;
1597
- const m = b.length;
1598
- if (n === 0) return b.map(() => ({ kind: "insert" }));
1599
- if (m === 0) return a.map(() => ({ kind: "delete" }));
1600
- const limit = Math.min(n + m, MAX_EDIT_DISTANCE);
1601
- const offset = limit + 1;
1602
- const v = new Int32Array(2 * limit + 3);
1603
- const trace = [];
1604
- for (let d = 0; d <= limit; d++) {
1605
- trace.push(v.slice());
1606
- for (let k = -d; k <= d; k += 2) {
1607
- let x;
1608
- if (k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1]) x = v[offset + k + 1];
1609
- else x = v[offset + k - 1] + 1;
1610
- let y = x - k;
1611
- while (x < n && y < m && a[x] === b[y]) {
1612
- x++;
1613
- y++;
1614
- }
1615
- v[offset + k] = x;
1616
- if (x >= n && y >= m) {
1617
- const ops = [];
1618
- let px = n;
1619
- let py = m;
1620
- for (let step = d; step >= 0; step--) {
1621
- const snapshot = trace[step];
1622
- const diagonal = px - py;
1623
- const prevDiagonal = diagonal === -step || diagonal !== step && snapshot[offset + diagonal - 1] < snapshot[offset + diagonal + 1] ? diagonal + 1 : diagonal - 1;
1624
- const prevX = snapshot[offset + prevDiagonal];
1625
- const prevY = prevX - prevDiagonal;
1626
- while (px > prevX && py > prevY) {
1627
- ops.push({ kind: "equal" });
1628
- px--;
1629
- py--;
1630
- }
1631
- if (step > 0) {
1632
- ops.push({ kind: px === prevX ? "insert" : "delete" });
1633
- if (px === prevX) py--;
1634
- else px--;
1635
- }
1636
- }
1637
- return ops.reverse();
1638
- }
1639
- }
1495
+ if (!ranAnyStep) {
1496
+ console.warn(`[BugZero] No build, lint, or test scripts found in package.json \u2014 nothing to validate.`);
1640
1497
  }
1641
- return null;
1498
+ return { success: true, step: "none", output: "" };
1642
1499
  }
1643
- function computeOps(oldLines, newLines) {
1644
- let prefix = 0;
1645
- while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) prefix++;
1646
- let suffix = 0;
1647
- while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix && oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]) {
1648
- suffix++;
1500
+ }
1501
+ });
1502
+
1503
+ // ../../packages/ai-provider/dist/index.js
1504
+ var require_dist5 = __commonJS({
1505
+ "../../packages/ai-provider/dist/index.js"(exports2, module2) {
1506
+ "use strict";
1507
+ var __create2 = Object.create;
1508
+ var __defProp2 = Object.defineProperty;
1509
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1510
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1511
+ var __getProtoOf2 = Object.getPrototypeOf;
1512
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1513
+ var __export = (target, all) => {
1514
+ for (var name in all)
1515
+ __defProp2(target, name, { get: all[name], enumerable: true });
1516
+ };
1517
+ var __copyProps2 = (to, from, except, desc) => {
1518
+ if (from && typeof from === "object" || typeof from === "function") {
1519
+ for (let key of __getOwnPropNames2(from))
1520
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1521
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1649
1522
  }
1650
- const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);
1651
- const newMiddle = newLines.slice(prefix, newLines.length - suffix);
1652
- const middle = diffLines(oldMiddle, newMiddle) ?? [...oldMiddle.map(() => ({ kind: "delete" })), ...newMiddle.map(() => ({ kind: "insert" }))];
1653
- return [
1654
- ...Array.from({ length: prefix }, () => ({ kind: "equal" })),
1655
- ...middle,
1656
- ...Array.from({ length: suffix }, () => ({ kind: "equal" }))
1657
- ];
1658
- }
1659
- function formatRange(start, count) {
1660
- return count === 1 ? String(start) : `${start},${count}`;
1661
- }
1662
- function renderLine(prefix, raw, maxLineLength) {
1663
- const missingNewline = raw.endsWith(NO_NEWLINE);
1664
- let text = (missingNewline ? raw.slice(0, -NO_NEWLINE.length) : raw).replace(/\r$/, "");
1665
- if (text.length > maxLineLength) {
1666
- text = `${text.slice(0, maxLineLength)}\u2026 [${text.length - maxLineLength} more characters]`;
1523
+ return to;
1524
+ };
1525
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1526
+ // If the importer is in node compatibility mode or this is not an ESM
1527
+ // file that has been converted to a CommonJS file using a Babel-
1528
+ // compatible transform (i.e. "__esModule" has not been set), then set
1529
+ // "default" to the CommonJS "module.exports" for node compatibility.
1530
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1531
+ mod
1532
+ ));
1533
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1534
+ var index_exports = {};
1535
+ __export(index_exports, {
1536
+ OpenRouterProvider: () => OpenRouterProvider,
1537
+ getErrorHints: () => getErrorHints
1538
+ });
1539
+ module2.exports = __toCommonJS(index_exports);
1540
+ var import_axios = __toESM2(require("axios"));
1541
+ var import_fs2 = __toESM2(require("fs"));
1542
+ var import_path3 = __toESM2(require("path"));
1543
+ var CREDITS_PATTERN = /insufficient credits|credit balance|add more credits|requires more credits|token_limit_exceeded/i;
1544
+ var CONTEXT_PATTERN = /context length|context window|maximum context|context_length_exceeded|string_too_long|too many tokens|reduce the length/i;
1545
+ var MODEL_PATTERN = /not a valid model|no endpoints found|model.{0,40}(not found|does not exist|unavailable)/i;
1546
+ function getErrorHints({ status, message, model }) {
1547
+ if (status === 401) {
1548
+ return ["\u{1F449} Please check if your OPENROUTER_API_KEY is correct and active."];
1667
1549
  }
1668
- const rendered = [`${prefix}${text}`];
1669
- if (missingNewline) rendered.push("\");
1670
- return rendered;
1671
- }
1672
- function renderOne(change, context, maxLineLength) {
1673
- if (change.before === change.after) return [];
1674
- const oldLines = toLines(change.before);
1675
- const newLines = toLines(change.after);
1676
- const ops = computeOps(oldLines, newLines);
1677
- const oldBefore = [];
1678
- const newBefore = [];
1679
- let oldCount = 0;
1680
- let newCount = 0;
1681
- for (const op of ops) {
1682
- oldBefore.push(oldCount);
1683
- newBefore.push(newCount);
1684
- if (op.kind !== "insert") oldCount++;
1685
- if (op.kind !== "delete") newCount++;
1550
+ if (status === 402 || CREDITS_PATTERN.test(message)) {
1551
+ return [
1552
+ "\u{1F449} Your OpenRouter credit balance is too low for this request.",
1553
+ " Add credits at https://openrouter.ai/settings/credits, or run 'bugzero vibe' to switch to a cheaper model",
1554
+ " (models that cost nothing are listed at https://openrouter.ai/models?max_price=0)."
1555
+ ];
1686
1556
  }
1687
- const changed = [];
1688
- ops.forEach((op, index) => {
1689
- if (op.kind !== "equal") changed.push(index);
1690
- });
1691
- if (changed.length === 0) return [];
1692
- const groups = [];
1693
- for (const index of changed) {
1694
- const current = groups[groups.length - 1];
1695
- if (current && index - current.last - 1 <= 2 * context) current.last = index;
1696
- else groups.push({ first: index, last: index });
1557
+ if (status === 429) {
1558
+ return [
1559
+ "\u{1F449} OpenRouter is rate limiting these requests. Wait a moment and try again.",
1560
+ " Free models have stricter limits; run 'bugzero vibe' to switch models, or add credits to raise them."
1561
+ ];
1697
1562
  }
1698
- const output = [`--- a/${change.filePath}`, `+++ b/${change.filePath}`];
1699
- for (const group of groups) {
1700
- const from = Math.max(0, group.first - context);
1701
- const to = Math.min(ops.length - 1, group.last + context);
1702
- let oldInHunk = 0;
1703
- let newInHunk = 0;
1704
- for (let i = from; i <= to; i++) {
1705
- if (ops[i].kind !== "insert") oldInHunk++;
1706
- if (ops[i].kind !== "delete") newInHunk++;
1707
- }
1708
- const oldStart = oldInHunk === 0 ? oldBefore[from] : oldBefore[from] + 1;
1709
- const newStart = newInHunk === 0 ? newBefore[from] : newBefore[from] + 1;
1710
- output.push(`@@ -${formatRange(oldStart, oldInHunk)} +${formatRange(newStart, newInHunk)} @@`);
1711
- for (let i = from; i <= to; i++) {
1712
- const op = ops[i];
1713
- if (op.kind === "equal") output.push(...renderLine(" ", oldLines[oldBefore[i]], maxLineLength));
1714
- else if (op.kind === "delete") output.push(...renderLine("-", oldLines[oldBefore[i]], maxLineLength));
1715
- else output.push(...renderLine("+", newLines[newBefore[i]], maxLineLength));
1563
+ if (CONTEXT_PATTERN.test(message)) {
1564
+ return [
1565
+ `\u{1F449} The prompt was too large for the context window of "${model}".`,
1566
+ " Run 'bugzero vibe' to pick a model with a larger context window, or try again on a smaller failing scope."
1567
+ ];
1568
+ }
1569
+ if (status === 404 || MODEL_PATTERN.test(message)) {
1570
+ return [
1571
+ `\u{1F449} The model "${model}" isn't available on OpenRouter (it wasn't found, or no provider currently serves it).`,
1572
+ " Run 'bugzero vibe' to choose a different model."
1573
+ ];
1574
+ }
1575
+ return [];
1576
+ }
1577
+ function resolveModel(cwd) {
1578
+ try {
1579
+ const configPath = import_path3.default.resolve(cwd ?? process.cwd(), ".bugzerorc");
1580
+ if (import_fs2.default.existsSync(configPath)) {
1581
+ const config = JSON.parse(import_fs2.default.readFileSync(configPath, "utf-8"));
1582
+ if (config.model) return config.model;
1716
1583
  }
1584
+ } catch {
1717
1585
  }
1718
- return output;
1586
+ return "deepseek/deepseek-chat";
1719
1587
  }
1720
- function renderUnifiedDiff(changes, options = {}) {
1721
- const context = Math.max(0, options.context ?? DEFAULT_CONTEXT);
1722
- const maxLineLength = Math.max(1, options.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH);
1723
- const list = Array.isArray(changes) ? changes : [changes];
1724
- return list.flatMap(
1725
- (change) => renderOne({ ...change, filePath: change.filePath.replace(/\\/g, "/") }, context, maxLineLength)
1726
- ).join("\n");
1588
+ var OpenRouterProvider = class {
1589
+ async invoke(prompt, options) {
1590
+ const model = resolveModel(options?.cwd);
1591
+ const apiKey = process.env.OPENROUTER_API_KEY;
1592
+ if (!apiKey) {
1593
+ console.error(`
1594
+ \u274C [BugZero] Error: OPENROUTER_API_KEY environment variable is not set.`);
1595
+ console.error(`\u{1F449} Please configure it using one of the following methods:`);
1596
+ console.error(` - On macOS/Linux: export OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1597
+ console.error(` - On Windows (PowerShell): $env:OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1598
+ console.error(` - Or add it to a .env file at the root of the project you are fixing:`);
1599
+ console.error(` OPENROUTER_API_KEY=your_openrouter_api_key_here
1600
+ `);
1601
+ throw new Error("Missing OPENROUTER_API_KEY environment variable.");
1602
+ }
1603
+ try {
1604
+ const response = await import_axios.default.post(
1605
+ "https://openrouter.ai/api/v1/chat/completions",
1606
+ {
1607
+ model,
1608
+ messages: [
1609
+ {
1610
+ role: "user",
1611
+ content: prompt
1612
+ }
1613
+ ]
1614
+ },
1615
+ {
1616
+ headers: {
1617
+ Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
1618
+ "Content-Type": "application/json"
1619
+ }
1620
+ }
1621
+ );
1622
+ if (response.data?.error) {
1623
+ throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1624
+ }
1625
+ return {
1626
+ content: response.data.choices[0].message.content,
1627
+ model,
1628
+ usage: response.data.usage
1629
+ };
1630
+ } catch (error) {
1631
+ let msg = error.message;
1632
+ if (error.response?.data?.error?.message) {
1633
+ msg = error.response.data.error.message;
1634
+ } else if (error.response?.data?.message) {
1635
+ msg = error.response.data.message;
1636
+ }
1637
+ console.error(`
1638
+ \u274C [BugZero] OpenRouter API Error: ${msg}`);
1639
+ const hints = getErrorHints({ status: error.response?.status, message: msg, model });
1640
+ for (const line of hints) console.error(line);
1641
+ if (hints.length > 0) console.error();
1642
+ throw new Error(`OpenRouter API failed: ${msg}`);
1643
+ }
1644
+ }
1645
+ };
1646
+ }
1647
+ });
1648
+
1649
+ // ../../packages/prompts/dist/index.js
1650
+ var require_dist6 = __commonJS({
1651
+ "../../packages/prompts/dist/index.js"(exports2, module2) {
1652
+ "use strict";
1653
+ var __create2 = Object.create;
1654
+ var __defProp2 = Object.defineProperty;
1655
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1656
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1657
+ var __getProtoOf2 = Object.getPrototypeOf;
1658
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1659
+ var __export = (target, all) => {
1660
+ for (var name in all)
1661
+ __defProp2(target, name, { get: all[name], enumerable: true });
1662
+ };
1663
+ var __copyProps2 = (to, from, except, desc) => {
1664
+ if (from && typeof from === "object" || typeof from === "function") {
1665
+ for (let key of __getOwnPropNames2(from))
1666
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1667
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1668
+ }
1669
+ return to;
1670
+ };
1671
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1672
+ // If the importer is in node compatibility mode or this is not an ESM
1673
+ // file that has been converted to a CommonJS file using a Babel-
1674
+ // compatible transform (i.e. "__esModule" has not been set), then set
1675
+ // "default" to the CommonJS "module.exports" for node compatibility.
1676
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1677
+ mod
1678
+ ));
1679
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1680
+ var index_exports = {};
1681
+ __export(index_exports, {
1682
+ buildAnalysisPrompt: () => buildAnalysisPrompt,
1683
+ truncateLogs: () => truncateLogs
1684
+ });
1685
+ module2.exports = __toCommonJS(index_exports);
1686
+ var import_shared4 = require_dist2();
1687
+ var import_fs2 = __toESM2(require("fs"));
1688
+ var import_path3 = __toESM2(require("path"));
1689
+ var MAX_LOG_CHARS = 2e4;
1690
+ var MAX_FILE_CHARS = 2e4;
1691
+ var MAX_CONTEXT_CHARS = 6e4;
1692
+ function truncateLogs(logs, maxChars = MAX_LOG_CHARS) {
1693
+ if (logs.length <= maxChars) return logs;
1694
+ const head = logs.slice(0, Math.floor(maxChars * 0.6));
1695
+ const tail = logs.slice(logs.length - Math.floor(maxChars * 0.4));
1696
+ const omitted = logs.length - head.length - tail.length;
1697
+ return `${head}
1698
+
1699
+ ... [${omitted} characters of log output omitted to fit the model's context] ...
1700
+
1701
+ ${tail}`;
1727
1702
  }
1728
- function renderChangesFromBackups2(cwd, filePaths, options = {}) {
1729
- const changes = [];
1730
- for (const filePath of filePaths) {
1731
- const resolved = (0, import_shared22.resolveInsideProject)(cwd, filePath);
1732
- if (!resolved.ok) continue;
1703
+ function resolveExistingPathPrefix(candidate) {
1704
+ let current = candidate.replace(/(?::\d+)+$/, "").replace(/['"()\[\]`]+$/, "").trim();
1705
+ while (current.length > 0) {
1733
1706
  try {
1734
- changes.push({
1735
- filePath: import_path22.default.relative(import_path22.default.resolve(cwd), resolved.absolutePath),
1736
- before: import_fs3.default.readFileSync(`${resolved.absolutePath}.opspilot.bak`, "utf-8"),
1737
- after: import_fs3.default.readFileSync(resolved.absolutePath, "utf-8")
1738
- });
1707
+ if (import_fs2.default.existsSync(current)) {
1708
+ return current;
1709
+ }
1739
1710
  } catch {
1740
1711
  }
1712
+ const lastSpace = current.lastIndexOf(" ");
1713
+ if (lastSpace === -1) {
1714
+ const lastSlash = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
1715
+ if (lastSlash === -1) {
1716
+ break;
1717
+ }
1718
+ current = current.slice(0, lastSlash).trim();
1719
+ } else {
1720
+ current = current.slice(0, lastSpace).trim();
1721
+ }
1741
1722
  }
1742
- return renderUnifiedDiff(changes, options);
1723
+ return null;
1743
1724
  }
1744
- var import_fs4 = __toESM2(require("fs"));
1745
- var import_path3 = __toESM2(require("path"));
1746
- function previewPatches(cwd, patches, options = {}) {
1747
- if (patches.length === 0) {
1748
- return { success: false, error: "No patches to apply." };
1725
+ function getContextFiles(logs, cwd, rules) {
1726
+ const candidates = /* @__PURE__ */ new Set();
1727
+ const quotedRegex = /['"`]([^'"`\n]+)['"`]/g;
1728
+ let match;
1729
+ while ((match = quotedRegex.exec(logs)) !== null) {
1730
+ const p = match[1].trim();
1731
+ if (p.includes("/") || p.includes("\\") || p === "." || p.startsWith(".")) {
1732
+ candidates.add(p);
1733
+ }
1749
1734
  }
1750
- const targets = resolvePatchTargets(cwd, patches, options.protection);
1751
- if (!targets.ok) return { success: false, error: targets.error };
1752
- const originals = /* @__PURE__ */ new Map();
1753
- const current = /* @__PURE__ */ new Map();
1754
- for (const [index, patch] of patches.entries()) {
1755
- const absolutePath = targets.absolutePaths[index];
1756
- if (!current.has(absolutePath)) {
1757
- try {
1758
- const content = import_fs4.default.readFileSync(absolutePath, "utf-8");
1759
- originals.set(absolutePath, content);
1760
- current.set(absolutePath, content);
1761
- } catch {
1762
- return { success: false, error: `Failed to patch "${patch.filePath}": File not found: ${absolutePath}` };
1735
+ const winAbsRegex = /([a-zA-Z]:\\[^*?"<>|\n\r]+)/g;
1736
+ while ((match = winAbsRegex.exec(logs)) !== null) {
1737
+ candidates.add(match[1].trim());
1738
+ }
1739
+ const unixAbsRegex = /(\/[^*?"<>|\n\r\t]+)/g;
1740
+ while ((match = unixAbsRegex.exec(logs)) !== null) {
1741
+ candidates.add(match[1].trim());
1742
+ }
1743
+ const fallbackRegex = /(?:[a-zA-Z]:)?[a-zA-Z0-9_\-\/\\.]+\.(?:tsx?|jsx?|json|css|html|js|jsx)/g;
1744
+ const fallbackMatches = logs.match(fallbackRegex) || [];
1745
+ for (const m of fallbackMatches) {
1746
+ candidates.add(m.trim());
1747
+ }
1748
+ const resolvedPaths = /* @__PURE__ */ new Set();
1749
+ for (const candidate of candidates) {
1750
+ const absPathCandidate = import_path3.default.isAbsolute(candidate) ? candidate : import_path3.default.resolve(cwd, candidate);
1751
+ const resolved = resolveExistingPathPrefix(absPathCandidate);
1752
+ if (resolved && (0, import_shared4.isInsideDirectory)(cwd, resolved)) {
1753
+ resolvedPaths.add(import_path3.default.resolve(resolved));
1754
+ }
1755
+ }
1756
+ if (resolvedPaths.size === 0) return "";
1757
+ let context = "\n\n### \u{1F4C1} Codebase Context:\n";
1758
+ const processedFiles = /* @__PURE__ */ new Set();
1759
+ const addFileToContext = (filePath) => {
1760
+ const relPath = import_path3.default.relative(cwd, filePath);
1761
+ if (relPath.includes("node_modules") || relPath.startsWith("build") || relPath.startsWith("dist") || relPath.startsWith(".git")) {
1762
+ return;
1763
+ }
1764
+ if ((0, import_shared4.projectRelativePaths)(cwd, filePath).some((rel) => rules.secretBlockedBy(rel) !== void 0)) return;
1765
+ if (processedFiles.has(filePath)) return;
1766
+ if (context.length >= MAX_CONTEXT_CHARS) return;
1767
+ processedFiles.add(filePath);
1768
+ try {
1769
+ let content = import_fs2.default.readFileSync(filePath, "utf-8");
1770
+ if (content.length > MAX_FILE_CHARS) {
1771
+ const omitted = content.length - MAX_FILE_CHARS;
1772
+ content = `${content.slice(0, MAX_FILE_CHARS)}
1773
+ ... [file truncated: ${omitted} more characters not shown]`;
1763
1774
  }
1775
+ context += `
1776
+ --- File: ${relPath} ---
1777
+ \`\`\`
1778
+ ${content}
1779
+ \`\`\`
1780
+ `;
1781
+ } catch {
1764
1782
  }
1765
- const patched = patchContent(current.get(absolutePath), patch.search, patch.replace, import_path3.default.basename(absolutePath));
1766
- if (!patched.ok) {
1767
- return { success: false, error: `Failed to patch "${patch.filePath}": ${patched.error}` };
1783
+ };
1784
+ for (const absPath of resolvedPaths) {
1785
+ try {
1786
+ const stats = import_fs2.default.statSync(absPath);
1787
+ if (stats.isFile()) {
1788
+ addFileToContext(absPath);
1789
+ const parentDir = import_path3.default.dirname(absPath);
1790
+ const filesInDir = import_fs2.default.readdirSync(parentDir);
1791
+ const relParentDir = import_path3.default.relative(cwd, parentDir) || ".";
1792
+ context += `
1793
+ --- Directory files in "${relParentDir}": ---
1794
+ `;
1795
+ for (const file of filesInDir) {
1796
+ try {
1797
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(parentDir, file));
1798
+ const marker = fileStats.isDirectory() ? "/" : "";
1799
+ context += `- ${file}${marker}
1800
+ `;
1801
+ } catch {
1802
+ context += `- ${file}
1803
+ `;
1804
+ }
1805
+ }
1806
+ } else if (stats.isDirectory()) {
1807
+ const relParentDir = import_path3.default.relative(cwd, absPath) || ".";
1808
+ if (relParentDir !== ".") {
1809
+ const filesInDir = import_fs2.default.readdirSync(absPath);
1810
+ context += `
1811
+ --- Directory files in "${relParentDir}": ---
1812
+ `;
1813
+ for (const file of filesInDir) {
1814
+ try {
1815
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(absPath, file));
1816
+ const marker = fileStats.isDirectory() ? "/" : "";
1817
+ context += `- ${file}${marker}
1818
+ `;
1819
+ } catch {
1820
+ context += `- ${file}
1821
+ `;
1822
+ }
1823
+ }
1824
+ if (filesInDir.length <= 15) {
1825
+ for (const file of filesInDir) {
1826
+ const filePathFull = import_path3.default.join(absPath, file);
1827
+ const fileExt = import_path3.default.extname(file).toLowerCase();
1828
+ try {
1829
+ if (import_fs2.default.statSync(filePathFull).isFile() && [".js", ".jsx", ".ts", ".tsx", ".json", ".css"].includes(fileExt)) {
1830
+ addFileToContext(filePathFull);
1831
+ }
1832
+ } catch {
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+ }
1838
+ } catch {
1768
1839
  }
1769
- current.set(absolutePath, patched.content);
1770
1840
  }
1771
- const root = import_path3.default.resolve(cwd);
1772
- const changes = [...originals.keys()].map((absolutePath) => ({
1773
- filePath: import_path3.default.relative(root, absolutePath).split(import_path3.default.sep).join("/"),
1774
- before: originals.get(absolutePath),
1775
- after: current.get(absolutePath)
1776
- }));
1777
- return { success: true, changes };
1841
+ return context;
1842
+ }
1843
+ function buildAnalysisPrompt(errorOutput, cwd, options = {}) {
1844
+ const warningMarker = "\u26A0\uFE0F [BugZero System Warning]";
1845
+ let compilerLogs = errorOutput;
1846
+ let historySection = "";
1847
+ if (errorOutput.includes(warningMarker)) {
1848
+ const parts = errorOutput.split(warningMarker);
1849
+ compilerLogs = parts[0].trim();
1850
+ const warnings = parts.slice(1).map((w) => w.trim());
1851
+ historySection = `
1852
+
1853
+ ### \u26A0\uFE0F Previous Failed Attempts:
1854
+ ${warnings.map((w, idx) => `Failed Attempt ${idx + 1}:
1855
+ ${w}`).join("\n\n")}
1856
+
1857
+ **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.`;
1858
+ }
1859
+ compilerLogs = truncateLogs(compilerLogs);
1860
+ const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
1861
+ return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1862
+
1863
+ A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
1864
+
1865
+ \`\`\`
1866
+ ${compilerLogs}
1867
+ \`\`\`${historySection}${contextSection}
1868
+
1869
+ Your task:
1870
+ 1. Root Cause: Identify the root cause of the build failure.
1871
+ 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.
1872
+ 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.
1873
+
1874
+ Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fences, no extra text:
1875
+ {
1876
+ "rootCause": "One-sentence explanation of the error",
1877
+ "explanation": "short explanation of what you changed and why",
1878
+ "patches": [
1879
+ {
1880
+ "filePath": "relative/path/from/project/root/to/file.ts",
1881
+ "search": "exact code that currently exists in the file and must be replaced",
1882
+ "replace": "the corrected code that replaces the search string"
1883
+ }
1884
+ ]
1885
+ }
1886
+
1887
+ Critical rules:
1888
+ - "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.
1889
+ - Each "filePath" must be a relative path from the project root (no leading /).
1890
+ - 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.
1891
+ - Each "search" must be an EXACT character-for-character substring of that file's current content.
1892
+ - Each "replace" must be syntactically valid code.
1893
+ - 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.
1894
+ - Do NOT add backticks, markdown, or any text outside the JSON object.`;
1778
1895
  }
1779
1896
  }
1780
1897
  });
@@ -1902,21 +2019,71 @@ var require_dist7 = __commonJS({
1902
2019
  reducer: (total, added) => total + added,
1903
2020
  default: () => 0
1904
2021
  }),
2022
+ /** How many attempts in a row may make no progress before the run stops early (0 = never stop early) */
2023
+ patience: (0, import_langgraph.Annotation)({
2024
+ reducer: (_, value) => value,
2025
+ default: () => 0
2026
+ }),
2027
+ /** The best result so far and how many attempts in a row did not beat it (null until there is one to compare to) */
2028
+ progress: (0, import_langgraph.Annotation)({
2029
+ reducer: (_, value) => value,
2030
+ default: () => null
2031
+ }),
2032
+ /** True when the run stopped before max attempts because attempts were not making progress */
2033
+ stoppedForNoProgress: (0, import_langgraph.Annotation)({
2034
+ reducer: (_, value) => value,
2035
+ default: () => false
2036
+ }),
1905
2037
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
1906
2038
  timeoutMs: (0, import_langgraph.Annotation)({
1907
2039
  reducer: (_, value) => value,
1908
2040
  default: () => void 0
1909
2041
  })
1910
2042
  });
1911
- var import_ai_provider = require_dist3();
1912
- var import_prompts = require_dist5();
2043
+ var import_ai_provider = require_dist5();
2044
+ var import_prompts = require_dist6();
1913
2045
  var import_config2 = require_dist();
1914
- var import_patcher2 = require_dist6();
1915
- var import_analyzers = require_dist2();
1916
- var import_shared3 = require_dist4();
2046
+ var import_patcher3 = require_dist3();
2047
+ var import_analyzers2 = require_dist4();
2048
+ var import_analyzers = require_dist4();
2049
+ var STEP_ORDER = { build: 0, lint: 1, test: 2, none: 3 };
2050
+ var ANSI_RE = /\u001b\[[0-9;]*[A-Za-z]/g;
2051
+ function snapshotOf(step, output) {
2052
+ const errors = (0, import_analyzers.parseErrors)(output);
2053
+ const countable = errors.length > 0 && errors[0].type !== "unknown";
2054
+ return {
2055
+ step,
2056
+ errorCount: countable ? errors.length : null,
2057
+ fingerprint: output.replace(ANSI_RE, "").replace(/\r\n/g, "\n").trim()
2058
+ };
2059
+ }
2060
+ function isProgress(best, last, current) {
2061
+ const stepDifference = STEP_ORDER[current.step] - STEP_ORDER[best.step];
2062
+ if (stepDifference !== 0) return stepDifference > 0;
2063
+ if (best.errorCount !== null && current.errorCount !== null) {
2064
+ return current.errorCount < best.errorCount;
2065
+ }
2066
+ return current.fingerprint !== best.fingerprint && current.fingerprint !== last.fingerprint;
2067
+ }
2068
+ function startTracking(initial) {
2069
+ return { best: initial, last: initial, stagnantAttempts: 0 };
2070
+ }
2071
+ function recordAttempt(tracker, current) {
2072
+ if (tracker === null) return startTracking(current);
2073
+ if (isProgress(tracker.best, tracker.last, current)) {
2074
+ return { best: current, last: current, stagnantAttempts: 0 };
2075
+ }
2076
+ return { best: tracker.best, last: current, stagnantAttempts: tracker.stagnantAttempts + 1 };
2077
+ }
2078
+ function describeSnapshot(snapshot) {
2079
+ const where = snapshot.step === "none" ? "" : ` in ${snapshot.step}`;
2080
+ if (snapshot.errorCount === null) return `output it cannot count${where}`;
2081
+ return `${snapshot.errorCount} error${snapshot.errorCount === 1 ? "" : "s"}${where}`;
2082
+ }
2083
+ var import_shared4 = require_dist2();
1917
2084
  var provider = new import_ai_provider.OpenRouterProvider();
1918
2085
  function protectionFor(cwd) {
1919
- return (0, import_shared3.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
2086
+ return (0, import_shared4.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
1920
2087
  }
1921
2088
  function previewAnalysisPrompt(cwd, logs) {
1922
2089
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
@@ -1978,7 +2145,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1978
2145
  console.log(`[BugZero] Patching ${patches.length} file${patches.length === 1 ? "" : "s"}: ${fileList}`);
1979
2146
  console.log(`[BugZero] Reason: ${explanation}`);
1980
2147
  if (state.approve) {
1981
- const preview = (0, import_patcher2.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
2148
+ const preview = (0, import_patcher3.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
1982
2149
  if (!preview.success) return patchFailure(state, preview.error);
1983
2150
  const files = preview.changes.map((change) => change.filePath);
1984
2151
  const decision = await state.approve({
@@ -1987,7 +2154,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1987
2154
  rootCause: state.fixSuggestion.rootCause,
1988
2155
  explanation,
1989
2156
  files,
1990
- diff: (0, import_patcher2.renderUnifiedDiff)(preview.changes)
2157
+ diff: (0, import_patcher3.renderUnifiedDiff)(preview.changes)
1991
2158
  });
1992
2159
  if (!decision.approved) {
1993
2160
  console.log("[BugZero] Fix declined \u2014 nothing was changed.");
@@ -1999,7 +2166,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1999
2166
  return { logs: declinedLogs, patchFailed: true, declinedFixes: 1 };
2000
2167
  }
2001
2168
  }
2002
- const result = (0, import_patcher2.applyPatches)(state.cwd, patches, {
2169
+ const result = (0, import_patcher3.applyPatches)(state.cwd, patches, {
2003
2170
  alreadyBackedUp: state.backedUpFiles,
2004
2171
  protection: protectionFor(state.cwd)
2005
2172
  });
@@ -2025,19 +2192,25 @@ Any other files from that same suggestion were rolled back to keep the change at
2025
2192
  };
2026
2193
  }
2027
2194
  console.log("[BugZero] Re-running validation pipeline to verify fix\u2026");
2028
- const result = await (0, import_analyzers.runValidationPipeline)(state.cwd, { timeoutMs: state.timeoutMs });
2195
+ const result = await (0, import_analyzers2.runValidationPipeline)(state.cwd, { timeoutMs: state.timeoutMs });
2029
2196
  if (result.success) {
2030
2197
  console.log("[BugZero] \u2705 Validation succeeded!");
2031
2198
  } else {
2032
2199
  console.log(`[BugZero] \u274C Validation failed at step "${result.step}". New error output captured.`);
2033
2200
  }
2034
- return {
2035
- success: result.success,
2036
- logs: result.success ? "" : result.output
2037
- };
2201
+ if (result.success) return { success: true, logs: "" };
2202
+ const progress = recordAttempt(state.progress, snapshotOf(result.step, result.output));
2203
+ const stuck = state.patience > 0 && progress.stagnantAttempts >= state.patience && state.attempts < state.maxAttempts;
2204
+ if (stuck) {
2205
+ console.log(
2206
+ `[BugZero] No progress in ${progress.stagnantAttempts} attempt(s) in a row (best so far: ${describeSnapshot(progress.best)}; now: ${describeSnapshot(progress.last)}) \u2014 stopping early instead of using the remaining attempt(s).`
2207
+ );
2208
+ }
2209
+ return { success: false, logs: result.output, progress, stoppedForNoProgress: stuck };
2038
2210
  }
2039
2211
  function shouldRetry(state) {
2040
2212
  if (state.success) return import_langgraph2.END;
2213
+ if (state.stoppedForNoProgress) return import_langgraph2.END;
2041
2214
  if (state.attempts >= state.maxAttempts) {
2042
2215
  console.log(
2043
2216
  `[BugZero] Max attempts (${state.maxAttempts}) reached \u2014 giving up.`
@@ -2048,8 +2221,14 @@ Any other files from that same suggestion were rolled back to keep the change at
2048
2221
  }
2049
2222
  var workflow = new import_langgraph2.StateGraph(GraphState).addNode("analyze", analyzeNode).addNode("apply_fix", applyFixNode).addNode("verify", verifyNode).addEdge(import_langgraph2.START, "analyze").addEdge("analyze", "apply_fix").addEdge("apply_fix", "verify").addConditionalEdges("verify", shouldRetry).compile();
2050
2223
  function runRepairWorkflow(input) {
2224
+ const { initialStep, ...rest } = input;
2051
2225
  return workflow.invoke(
2052
- { ...input, attempts: 0, success: false },
2226
+ {
2227
+ ...rest,
2228
+ attempts: 0,
2229
+ success: false,
2230
+ progress: initialStep ? startTracking(snapshotOf(initialStep, input.logs)) : null
2231
+ },
2053
2232
  { recursionLimit: input.maxAttempts * 3 + 5 }
2054
2233
  );
2055
2234
  }
@@ -2090,19 +2269,21 @@ var require_dist8 = __commonJS({
2090
2269
  var index_exports = {};
2091
2270
  __export(index_exports, {
2092
2271
  DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
2272
+ DEFAULT_PATIENCE: () => DEFAULT_PATIENCE,
2093
2273
  REPORT_FILENAME: () => REPORT_FILENAME2,
2094
2274
  detectFramework: () => detectFramework2,
2095
2275
  detectPackageManager: () => import_analyzers2.detectPackageManager,
2096
2276
  orchestrate: () => orchestrate2,
2097
2277
  orchestrateAndFix: () => orchestrateAndFix2,
2098
2278
  resolveMaxAttempts: () => resolveMaxAttempts2,
2279
+ resolvePatience: () => resolvePatience2,
2099
2280
  resolveTimeoutMs: () => resolveTimeoutMs2
2100
2281
  });
2101
2282
  module2.exports = __toCommonJS(index_exports);
2102
2283
  var import_fs2 = __toESM2(require("fs"));
2103
- var import_path2 = __toESM2(require("path"));
2284
+ var import_path3 = __toESM2(require("path"));
2104
2285
  function detectFramework2(cwd = process.cwd()) {
2105
- const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path2.default.join(cwd, f)));
2286
+ const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path3.default.join(cwd, f)));
2106
2287
  if (has("next.config.js", "next.config.ts", "next.config.mjs")) return "nextjs";
2107
2288
  if (has("nest-cli.json")) return "nestjs";
2108
2289
  if (has("vite.config.ts", "vite.config.js", "vite.config.mts")) return "vite";
@@ -2110,7 +2291,7 @@ var require_dist8 = __commonJS({
2110
2291
  if (has("astro.config.mjs", "astro.config.ts", "astro.config.js")) return "astro";
2111
2292
  if (has("svelte.config.js", "svelte.config.ts")) return "sveltekit";
2112
2293
  if (has("nuxt.config.ts", "nuxt.config.js")) return "nuxt";
2113
- const pkgPath = import_path2.default.join(cwd, "package.json");
2294
+ const pkgPath = import_path3.default.join(cwd, "package.json");
2114
2295
  if (import_fs2.default.existsSync(pkgPath)) {
2115
2296
  try {
2116
2297
  const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
@@ -2126,14 +2307,14 @@ var require_dist8 = __commonJS({
2126
2307
  if (has("tsconfig.json")) return "typescript";
2127
2308
  return "unknown";
2128
2309
  }
2129
- var import_analyzers = require_dist2();
2310
+ var import_analyzers = require_dist4();
2130
2311
  var import_agents = require_dist7();
2131
- var import_shared22 = require_dist4();
2312
+ var import_shared22 = require_dist2();
2132
2313
  var import_fs3 = __toESM2(require("fs"));
2133
- var import_path3 = __toESM2(require("path"));
2314
+ var import_path32 = __toESM2(require("path"));
2134
2315
  var import_url = require("url");
2135
- var import_prompts = require_dist5();
2136
- var import_shared3 = require_dist4();
2316
+ var import_prompts = require_dist6();
2317
+ var import_shared4 = require_dist2();
2137
2318
  var MAX_REPORT_LOG_CHARS = 2e4;
2138
2319
  function capReportLogs(logs, maxChars = MAX_REPORT_LOG_CHARS) {
2139
2320
  return (0, import_prompts.truncateLogs)(logs, maxChars);
@@ -2171,7 +2352,7 @@ ${p.replace}`
2171
2352
  }
2172
2353
  function buildRescueSuccessPrompt(params) {
2173
2354
  const { cwd, attempts, appliedFix } = params;
2174
- const patchedFiles = (0, import_shared3.uniqueFilePaths)(appliedFix.patches).join(", ");
2355
+ const patchedFiles = (0, import_shared4.uniqueFilePaths)(appliedFix.patches).join(", ");
2175
2356
  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}.
2176
2357
  Here is the patch details:
2177
2358
  - Root Cause: ${appliedFix.rootCause}
@@ -2243,6 +2424,7 @@ ${params.rawOutput}
2243
2424
  Re-run without \`--dry-run\` to let BugZero attempt a fix.
2244
2425
  `;
2245
2426
  }
2427
+ var import_config2 = require_dist();
2246
2428
  var DEFAULT_MAX_ATTEMPTS = 3;
2247
2429
  function resolveTimeoutMs2(seconds) {
2248
2430
  if (seconds === void 0) return void 0;
@@ -2258,6 +2440,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2258
2440
  }
2259
2441
  return attempts;
2260
2442
  }
2443
+ var DEFAULT_PATIENCE = 2;
2444
+ function resolvePatience2(flag, configured) {
2445
+ const source = flag !== void 0 ? "--patience" : "patience in .bugzerorc";
2446
+ const value = flag !== void 0 ? flag : configured;
2447
+ if (value === void 0) return DEFAULT_PATIENCE;
2448
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
2449
+ throw new Error(`${source} must be a whole number of 0 or more, where 0 turns it off (received ${JSON.stringify(value) ?? String(value)}).`);
2450
+ }
2451
+ return value;
2452
+ }
2261
2453
  var import_fs22 = __toESM2(require("fs"));
2262
2454
  var import_path22 = __toESM2(require("path"));
2263
2455
  function assertNodeProject(cwd) {
@@ -2265,14 +2457,14 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2265
2457
  throw new Error(`No package.json found in ${cwd}. Point --path at a Node.js project.`);
2266
2458
  }
2267
2459
  }
2268
- var import_ai_provider = require_dist3();
2460
+ var import_ai_provider = require_dist5();
2269
2461
  var REPORT_FILENAME2 = "bugzero-report.md";
2270
- function failureMessage(maxAttempts, declined, appliedAnything) {
2462
+ function failureMessage(maxAttempts, declined, appliedAnything, stoppedAfter) {
2271
2463
  const plural = declined === 1 ? "fix" : "fixes";
2272
2464
  if (declined > 0 && !appliedAnything) {
2273
2465
  return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2274
2466
  }
2275
- const base = `Max attempts (${maxAttempts}) reached without a successful build.`;
2467
+ const base = stoppedAfter !== void 0 ? `Stopped early: ${stoppedAfter} attempt${stoppedAfter === 1 ? "" : "s"} in a row made no progress (the errors did not get fewer and no later step was reached), so the remaining attempts were not used. Try a different model with 'bugzero vibe', or use --patience 0 to keep going regardless.` : `Max attempts (${maxAttempts}) reached without a successful build.`;
2276
2468
  return declined > 0 ? `${base} You declined ${declined} proposed ${plural}.` : base;
2277
2469
  }
2278
2470
  function statusLabel(result) {
@@ -2302,6 +2494,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2302
2494
  assertNodeProject(cwd);
2303
2495
  const maxAttempts = resolveMaxAttempts2(options.maxAttempts);
2304
2496
  const timeoutMs = resolveTimeoutMs2(options.timeoutSeconds);
2497
+ const patience = resolvePatience2(options.patience, (0, import_config2.getLocalConfig)(cwd).patience);
2305
2498
  console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
2306
2499
  const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
2307
2500
  if (pipelineResult.success) {
@@ -2352,14 +2545,22 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2352
2545
  logs: pipelineResult.output,
2353
2546
  maxAttempts,
2354
2547
  timeoutMs,
2355
- approve: options.approve
2548
+ approve: options.approve,
2549
+ patience,
2550
+ initialStep: pipelineResult.step
2356
2551
  });
2357
2552
  const result = {
2358
2553
  success: finalState.success,
2359
2554
  attempts: finalState.attempts,
2360
2555
  finalOutput: finalState.logs || pipelineResult.output,
2361
2556
  appliedFix: finalState.appliedFix ?? void 0,
2362
- error: finalState.success ? void 0 : failureMessage(maxAttempts, finalState.declinedFixes ?? 0, Boolean(finalState.appliedFix)),
2557
+ error: finalState.success ? void 0 : failureMessage(
2558
+ maxAttempts,
2559
+ finalState.declinedFixes ?? 0,
2560
+ Boolean(finalState.appliedFix),
2561
+ finalState.stoppedForNoProgress ? patience : void 0
2562
+ ),
2563
+ stoppedEarly: finalState.stoppedForNoProgress ? "no-progress" : void 0,
2363
2564
  declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2364
2565
  modelUsed: finalState.modelUsed,
2365
2566
  promptTokens: finalState.promptTokens,
@@ -2569,7 +2770,7 @@ ${rawOutput}
2569
2770
 
2570
2771
  ---
2571
2772
  *Report generated by **BugZero** on ${(/* @__PURE__ */ new Date()).toLocaleString()}*`;
2572
- const reportPath = import_path3.default.resolve(cwd, REPORT_FILENAME2);
2773
+ const reportPath = import_path32.default.resolve(cwd, REPORT_FILENAME2);
2573
2774
  try {
2574
2775
  import_fs3.default.writeFileSync(reportPath, content, "utf-8");
2575
2776
  const clickableUrl = (0, import_url.pathToFileURL)(reportPath).toString();
@@ -2587,19 +2788,21 @@ ${rawOutput}
2587
2788
  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");
2588
2789
  }
2589
2790
  }
2590
- var import_analyzers2 = require_dist2();
2791
+ var import_analyzers2 = require_dist4();
2591
2792
  }
2592
2793
  });
2593
2794
 
2594
2795
  // src/index.ts
2595
2796
  var import_config = __toESM(require_dist());
2797
+ var import_patcher2 = __toESM(require_dist3());
2798
+ var import_shared3 = __toESM(require_dist2());
2596
2799
  var import_commander = require("commander");
2597
2800
  var import_fs = __toESM(require("fs"));
2598
- var import_path = __toESM(require("path"));
2801
+ var import_path2 = __toESM(require("path"));
2599
2802
  var import_core = __toESM(require_dist8());
2600
2803
 
2601
2804
  // src/json-output.ts
2602
- var import_shared = __toESM(require_dist4());
2805
+ var import_shared = __toESM(require_dist2());
2603
2806
  function stepStatus(step) {
2604
2807
  if (step.skipped) return "skipped";
2605
2808
  return step.success ? "passed" : "failed";
@@ -2711,8 +2914,9 @@ function createApprovalHandler(io) {
2711
2914
  }
2712
2915
 
2713
2916
  // src/summary.ts
2714
- var import_patcher = __toESM(require_dist6());
2715
- var import_shared2 = __toESM(require_dist4());
2917
+ var import_patcher = __toESM(require_dist3());
2918
+ var import_path = __toESM(require("path"));
2919
+ var import_shared2 = __toESM(require_dist2());
2716
2920
  function tokenLines(result) {
2717
2921
  if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
2718
2922
  const total = result.promptTokens + result.completionTokens;
@@ -2768,10 +2972,35 @@ function buildChangeDiffLines(cwd, result) {
2768
2972
  if (diff === "") return [];
2769
2973
  return ["", "Changes (the original of each file is kept next to it as <file>.opspilot.bak):", "", ...diff.split("\n")];
2770
2974
  }
2975
+ function buildUndoHintLines(cwd, result, options) {
2976
+ if (options.dryRun || !result.appliedFix) return [];
2977
+ const command = import_path.default.resolve(cwd) === import_path.default.resolve(process.cwd()) ? "bugzero undo" : `bugzero undo --path "${import_path.default.resolve(cwd)}"`;
2978
+ 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:";
2979
+ return ["", `${lead} ${command}`];
2980
+ }
2981
+ function buildUndoSummary(entries, options) {
2982
+ if (entries.length === 0) {
2983
+ return { exitCode: 0, lines: ["Nothing to undo \u2014 no BugZero backups (*.opspilot.bak) were found."] };
2984
+ }
2985
+ const lines = [];
2986
+ for (const entry of entries) {
2987
+ if (entry.status === "restored") lines.push(`\u21A9\uFE0F Restored ${entry.filePath}`);
2988
+ else if (entry.status === "would-restore") lines.push(`\u21A9\uFE0F Would restore ${entry.filePath}`);
2989
+ else lines.push(`\u23ED\uFE0F Skipped ${entry.filePath}: ${entry.detail ?? entry.status}`);
2990
+ }
2991
+ const done = entries.filter((entry) => entry.status === "restored" || entry.status === "would-restore").length;
2992
+ const left = entries.length - done;
2993
+ lines.push("");
2994
+ lines.push(
2995
+ options.dryRun ? `Dry run: ${done} file(s) would be restored. Nothing was changed.` : `Restored ${done} file(s).`
2996
+ );
2997
+ if (left > 0) lines.push(`${left} file(s) were left as they are, with their backups kept.`);
2998
+ return { exitCode: left > 0 ? 1 : 0, lines };
2999
+ }
2771
3000
 
2772
3001
  // src/index.ts
2773
3002
  (0, import_config.loadProjectEnv)(process.cwd());
2774
- var { version } = JSON.parse(import_fs.default.readFileSync(import_path.default.join(__dirname, "..", "package.json"), "utf-8"));
3003
+ var { version } = JSON.parse(import_fs.default.readFileSync(import_path2.default.join(__dirname, "..", "package.json"), "utf-8"));
2775
3004
  var TIMEOUT_DESCRIPTION = "Stop any build/lint/test command that runs longer than this many seconds";
2776
3005
  function parseTimeout(raw) {
2777
3006
  if (raw === void 0) return void 0;
@@ -2797,7 +3026,7 @@ program.command("hunt").description("Run build, lint, and tests \u2014 report is
2797
3026
  const json = opts.json === true;
2798
3027
  if (json) routeLogsToStderr();
2799
3028
  try {
2800
- const cwd = import_path.default.resolve(opts.path);
3029
+ const cwd = import_path2.default.resolve(opts.path);
2801
3030
  (0, import_config.loadProjectEnv)(cwd);
2802
3031
  const timeoutSeconds = parseTimeout(opts.timeout);
2803
3032
  const framework = (0, import_core.detectFramework)(cwd);
@@ -2823,7 +3052,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2823
3052
  finish(
2824
3053
  allPassed ? 0 : 1,
2825
3054
  json ? buildHuntJson(
2826
- { path: cwd, framework, packageManager, reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME) },
3055
+ { path: cwd, framework, packageManager, reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME) },
2827
3056
  { build, lint, test }
2828
3057
  ) : void 0
2829
3058
  );
@@ -2833,15 +3062,17 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2833
3062
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2834
3063
  }
2835
3064
  });
2836
- 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) => {
3065
+ program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--patience <n>", "Stop early after this many attempts in a row make no progress (default 2, 0 turns it off)").option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
2837
3066
  const json = opts.json === true;
2838
3067
  const printPrompt = opts.printPrompt === true;
2839
3068
  if (json || printPrompt) routeLogsToStderr();
2840
3069
  try {
2841
- const cwd = import_path.default.resolve(opts.path);
3070
+ const cwd = import_path2.default.resolve(opts.path);
2842
3071
  (0, import_config.loadProjectEnv)(cwd);
2843
3072
  const maxAttempts = (0, import_core.resolveMaxAttempts)(Number(opts.maxAttempts));
2844
3073
  const timeoutSeconds = parseTimeout(opts.timeout);
3074
+ const patience = opts.patience === void 0 ? void 0 : Number(opts.patience);
3075
+ (0, import_core.resolvePatience)(patience, void 0);
2845
3076
  const dryRun = opts.dryRun;
2846
3077
  let approve;
2847
3078
  if (opts.approve === true && !dryRun && !printPrompt) {
@@ -2861,9 +3092,10 @@ program.command("rescue").description("Detect build failures and automatically a
2861
3092
  console.log(` Package manager: ${packageManager}`);
2862
3093
  console.log(` Max attempts: ${maxAttempts}`);
2863
3094
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
3095
+ if (patience !== void 0) console.log(` Patience: ${patience === 0 ? "off" : `${patience} attempt(s) without progress`}`);
2864
3096
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
2865
3097
  console.log();
2866
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve });
3098
+ const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve, patience });
2867
3099
  if (result.promptPreview !== void 0) {
2868
3100
  if (json) {
2869
3101
  finish(
@@ -2873,7 +3105,7 @@ program.command("rescue").description("Detect build failures and automatically a
2873
3105
  framework,
2874
3106
  packageManager,
2875
3107
  dryRun,
2876
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3108
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2877
3109
  })
2878
3110
  );
2879
3111
  } else {
@@ -2886,6 +3118,7 @@ program.command("rescue").description("Detect build failures and automatically a
2886
3118
  const summary = buildRescueSummary(result, { dryRun });
2887
3119
  for (const line of summary.lines) console.log(line);
2888
3120
  for (const line of buildChangeDiffLines(cwd, result)) console.log(line);
3121
+ for (const line of buildUndoHintLines(cwd, result, { dryRun })) console.log(line);
2889
3122
  console.log();
2890
3123
  finish(
2891
3124
  summary.exitCode,
@@ -2894,7 +3127,7 @@ program.command("rescue").description("Detect build failures and automatically a
2894
3127
  framework,
2895
3128
  packageManager,
2896
3129
  dryRun,
2897
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3130
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2898
3131
  }) : void 0
2899
3132
  );
2900
3133
  } catch (error) {
@@ -2903,6 +3136,25 @@ program.command("rescue").description("Detect build failures and automatically a
2903
3136
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2904
3137
  }
2905
3138
  });
3139
+ 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) => {
3140
+ try {
3141
+ const cwd = import_path2.default.resolve(opts.path);
3142
+ const entries = (0, import_patcher2.undoChanges)(cwd, {
3143
+ dryRun: opts.dryRun === true,
3144
+ force: opts.force === true,
3145
+ protection: (0, import_shared3.createProtectedPathRules)((0, import_config.getProtectionSettings)(cwd))
3146
+ });
3147
+ const summary = buildUndoSummary(entries, { dryRun: opts.dryRun === true });
3148
+ console.log();
3149
+ for (const line of summary.lines) console.log(line);
3150
+ console.log();
3151
+ finish(summary.exitCode);
3152
+ } catch (error) {
3153
+ console.error(`
3154
+ \u274C [BugZero] Execution failed: ${error.message || error}`);
3155
+ finish(1);
3156
+ }
3157
+ });
2906
3158
  program.command("protect").description("[Deprecated] Use 'hunt' instead").action(async () => {
2907
3159
  console.warn("\u26A0\uFE0F 'protect' is deprecated \u2014 use 'bugzero hunt' instead.\n");
2908
3160
  const result = await (0, import_core.orchestrate)();