bugzero 0.0.57 → 0.0.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -1
  2. package/dist/index.js +1329 -1165
  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
- ];
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
+ }
770
726
  }
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
- ];
727
+ lines.push({ text: text.slice(start), start, end: text.length });
728
+ return lines;
729
+ }
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;
747
+ }
776
748
  }
777
- return [];
749
+ return dp[n];
778
750
  }
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;
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;
767
+ }
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 };
785
773
  }
786
- } catch {
787
774
  }
788
- return "deepseek/deepseek-chat";
775
+ return null;
789
776
  }
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.");
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);
804
789
  }
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;
838
- }
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}`);
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;
845
797
  }
846
798
  }
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 });
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 };
804
+ }
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 };
870
809
  }
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))];
810
+ return findWhitespaceNormalizedMatch(content, search) ?? findSimilarityMatch(content, search);
896
811
  }
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;
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 };
903
818
  }
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;
913
- }
914
- return isLexicallyInside(import_fs2.default.realpathSync.native(root), import_fs2.default.realpathSync.native(probe));
915
- } catch {
916
- return false;
917
- }
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;
918
828
  }
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.` };
929
- }
930
- if (!isInsideDirectory(cwd, absolutePath)) {
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,603 @@ 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);
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);
1341
1309
  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;
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(output) {
1429
+ const errors = [];
1430
+ const tsMatches = [...output.matchAll(TS_ERROR_RE)];
1431
+ for (const m of tsMatches) {
1432
+ errors.push({
1433
+ type: "typescript",
1434
+ file: m[1].trim(),
1435
+ line: parseInt(m[2], 10),
1436
+ column: parseInt(m[3], 10),
1437
+ message: m[4].trim(),
1438
+ raw: m[0]
1439
+ });
1523
1440
  }
1524
- for (const backupPath of backupPaths) {
1525
- try {
1526
- import_fs22.default.unlinkSync(backupPath);
1527
- } catch {
1528
- }
1441
+ if (errors.length > 0) return errors;
1442
+ const eslintMatches = [...output.matchAll(ESLINT_ERROR_RE)];
1443
+ for (const m of eslintMatches) {
1444
+ errors.push({
1445
+ type: "eslint",
1446
+ line: parseInt(m[1], 10),
1447
+ column: parseInt(m[2], 10),
1448
+ message: m[3].trim(),
1449
+ raw: m[0]
1450
+ });
1529
1451
  }
1530
- }
1531
- function applyPatches(cwd, patches, options = {}) {
1532
- if (patches.length === 0) {
1533
- return { success: false, error: "No patches to apply.", applied: [] };
1452
+ if (errors.length > 0) return errors;
1453
+ const jestFiles = [...output.matchAll(JEST_FILE_RE)].map((m) => m[1]);
1454
+ const jestFails = [...output.matchAll(JEST_FAIL_RE)];
1455
+ for (const m of jestFails) {
1456
+ errors.push({
1457
+ type: "jest",
1458
+ file: jestFiles[0],
1459
+ message: m[1].trim(),
1460
+ raw: m[0]
1461
+ });
1534
1462
  }
1535
- const targets = resolvePatchTargets(cwd, patches, options.protection);
1536
- if (!targets.ok) {
1537
- return { success: false, error: targets.error, applied: [] };
1463
+ if (errors.length > 0) return errors;
1464
+ if (output.trim()) {
1465
+ errors.push({
1466
+ type: "unknown",
1467
+ message: output.slice(0, 500),
1468
+ raw: output
1469
+ });
1538
1470
  }
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);
1471
+ return errors;
1472
+ }
1473
+ var STEPS = [
1474
+ { step: "build", label: "build", run: runBuild },
1475
+ { step: "lint", label: "lint", run: runLint },
1476
+ { step: "test", label: "tests", run: runTests }
1477
+ ];
1478
+ async function runValidationPipeline(cwd, options) {
1479
+ const targetCwd = cwd ?? process.cwd();
1480
+ const scripts = readScripts(targetCwd);
1481
+ let ranAnyStep = false;
1482
+ for (const { step, label, run } of STEPS) {
1483
+ if (!scripts.includes(step)) {
1484
+ console.log(`[BugZero] Skipping ${label}: no "${step}" script in package.json.`);
1485
+ continue;
1563
1486
  }
1487
+ ranAnyStep = true;
1488
+ console.log(`[BugZero] Running ${label}...`);
1489
+ const result = await run(targetCwd, options);
1564
1490
  if (!result.success) {
1565
- rollback(originalContent, backupPaths);
1566
- return {
1567
- success: false,
1568
- error: `Failed to patch "${patch.filePath}": ${result.error}`,
1569
- applied: []
1570
- };
1491
+ return { success: false, step, output: result.output };
1571
1492
  }
1572
- applied.push({
1573
- filePath: patch.filePath,
1574
- absolutePath,
1575
- backupPath: result.backupPath,
1576
- matchStrategy: result.matchStrategy
1577
- });
1578
1493
  }
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
- }
1494
+ if (!ranAnyStep) {
1495
+ console.warn(`[BugZero] No build, lint, or test scripts found in package.json \u2014 nothing to validate.`);
1640
1496
  }
1641
- return null;
1497
+ return { success: true, step: "none", output: "" };
1642
1498
  }
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++;
1499
+ }
1500
+ });
1501
+
1502
+ // ../../packages/ai-provider/dist/index.js
1503
+ var require_dist5 = __commonJS({
1504
+ "../../packages/ai-provider/dist/index.js"(exports2, module2) {
1505
+ "use strict";
1506
+ var __create2 = Object.create;
1507
+ var __defProp2 = Object.defineProperty;
1508
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1509
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1510
+ var __getProtoOf2 = Object.getPrototypeOf;
1511
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1512
+ var __export = (target, all) => {
1513
+ for (var name in all)
1514
+ __defProp2(target, name, { get: all[name], enumerable: true });
1515
+ };
1516
+ var __copyProps2 = (to, from, except, desc) => {
1517
+ if (from && typeof from === "object" || typeof from === "function") {
1518
+ for (let key of __getOwnPropNames2(from))
1519
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1520
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1649
1521
  }
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]`;
1522
+ return to;
1523
+ };
1524
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1525
+ // If the importer is in node compatibility mode or this is not an ESM
1526
+ // file that has been converted to a CommonJS file using a Babel-
1527
+ // compatible transform (i.e. "__esModule" has not been set), then set
1528
+ // "default" to the CommonJS "module.exports" for node compatibility.
1529
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1530
+ mod
1531
+ ));
1532
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1533
+ var index_exports = {};
1534
+ __export(index_exports, {
1535
+ OpenRouterProvider: () => OpenRouterProvider,
1536
+ getErrorHints: () => getErrorHints
1537
+ });
1538
+ module2.exports = __toCommonJS(index_exports);
1539
+ var import_axios = __toESM2(require("axios"));
1540
+ var import_fs2 = __toESM2(require("fs"));
1541
+ var import_path3 = __toESM2(require("path"));
1542
+ var CREDITS_PATTERN = /insufficient credits|credit balance|add more credits|requires more credits|token_limit_exceeded/i;
1543
+ var CONTEXT_PATTERN = /context length|context window|maximum context|context_length_exceeded|string_too_long|too many tokens|reduce the length/i;
1544
+ var MODEL_PATTERN = /not a valid model|no endpoints found|model.{0,40}(not found|does not exist|unavailable)/i;
1545
+ function getErrorHints({ status, message, model }) {
1546
+ if (status === 401) {
1547
+ return ["\u{1F449} Please check if your OPENROUTER_API_KEY is correct and active."];
1667
1548
  }
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++;
1549
+ if (status === 402 || CREDITS_PATTERN.test(message)) {
1550
+ return [
1551
+ "\u{1F449} Your OpenRouter credit balance is too low for this request.",
1552
+ " Add credits at https://openrouter.ai/settings/credits, or run 'bugzero vibe' to switch to a cheaper model",
1553
+ " (models that cost nothing are listed at https://openrouter.ai/models?max_price=0)."
1554
+ ];
1686
1555
  }
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 });
1556
+ if (status === 429) {
1557
+ return [
1558
+ "\u{1F449} OpenRouter is rate limiting these requests. Wait a moment and try again.",
1559
+ " Free models have stricter limits; run 'bugzero vibe' to switch models, or add credits to raise them."
1560
+ ];
1697
1561
  }
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));
1562
+ if (CONTEXT_PATTERN.test(message)) {
1563
+ return [
1564
+ `\u{1F449} The prompt was too large for the context window of "${model}".`,
1565
+ " Run 'bugzero vibe' to pick a model with a larger context window, or try again on a smaller failing scope."
1566
+ ];
1567
+ }
1568
+ if (status === 404 || MODEL_PATTERN.test(message)) {
1569
+ return [
1570
+ `\u{1F449} The model "${model}" isn't available on OpenRouter (it wasn't found, or no provider currently serves it).`,
1571
+ " Run 'bugzero vibe' to choose a different model."
1572
+ ];
1573
+ }
1574
+ return [];
1575
+ }
1576
+ function resolveModel(cwd) {
1577
+ try {
1578
+ const configPath = import_path3.default.resolve(cwd ?? process.cwd(), ".bugzerorc");
1579
+ if (import_fs2.default.existsSync(configPath)) {
1580
+ const config = JSON.parse(import_fs2.default.readFileSync(configPath, "utf-8"));
1581
+ if (config.model) return config.model;
1716
1582
  }
1583
+ } catch {
1717
1584
  }
1718
- return output;
1585
+ return "deepseek/deepseek-chat";
1719
1586
  }
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");
1587
+ var OpenRouterProvider = class {
1588
+ async invoke(prompt, options) {
1589
+ const model = resolveModel(options?.cwd);
1590
+ const apiKey = process.env.OPENROUTER_API_KEY;
1591
+ if (!apiKey) {
1592
+ console.error(`
1593
+ \u274C [BugZero] Error: OPENROUTER_API_KEY environment variable is not set.`);
1594
+ console.error(`\u{1F449} Please configure it using one of the following methods:`);
1595
+ console.error(` - On macOS/Linux: export OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1596
+ console.error(` - On Windows (PowerShell): $env:OPENROUTER_API_KEY="your_openrouter_api_key_here"`);
1597
+ console.error(` - Or add it to a .env file at the root of the project you are fixing:`);
1598
+ console.error(` OPENROUTER_API_KEY=your_openrouter_api_key_here
1599
+ `);
1600
+ throw new Error("Missing OPENROUTER_API_KEY environment variable.");
1601
+ }
1602
+ try {
1603
+ const response = await import_axios.default.post(
1604
+ "https://openrouter.ai/api/v1/chat/completions",
1605
+ {
1606
+ model,
1607
+ messages: [
1608
+ {
1609
+ role: "user",
1610
+ content: prompt
1611
+ }
1612
+ ]
1613
+ },
1614
+ {
1615
+ headers: {
1616
+ Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
1617
+ "Content-Type": "application/json"
1618
+ }
1619
+ }
1620
+ );
1621
+ if (response.data?.error) {
1622
+ throw new Error(response.data.error.message || JSON.stringify(response.data.error));
1623
+ }
1624
+ return {
1625
+ content: response.data.choices[0].message.content,
1626
+ model,
1627
+ usage: response.data.usage
1628
+ };
1629
+ } catch (error) {
1630
+ let msg = error.message;
1631
+ if (error.response?.data?.error?.message) {
1632
+ msg = error.response.data.error.message;
1633
+ } else if (error.response?.data?.message) {
1634
+ msg = error.response.data.message;
1635
+ }
1636
+ console.error(`
1637
+ \u274C [BugZero] OpenRouter API Error: ${msg}`);
1638
+ const hints = getErrorHints({ status: error.response?.status, message: msg, model });
1639
+ for (const line of hints) console.error(line);
1640
+ if (hints.length > 0) console.error();
1641
+ throw new Error(`OpenRouter API failed: ${msg}`);
1642
+ }
1643
+ }
1644
+ };
1645
+ }
1646
+ });
1647
+
1648
+ // ../../packages/prompts/dist/index.js
1649
+ var require_dist6 = __commonJS({
1650
+ "../../packages/prompts/dist/index.js"(exports2, module2) {
1651
+ "use strict";
1652
+ var __create2 = Object.create;
1653
+ var __defProp2 = Object.defineProperty;
1654
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1655
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1656
+ var __getProtoOf2 = Object.getPrototypeOf;
1657
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1658
+ var __export = (target, all) => {
1659
+ for (var name in all)
1660
+ __defProp2(target, name, { get: all[name], enumerable: true });
1661
+ };
1662
+ var __copyProps2 = (to, from, except, desc) => {
1663
+ if (from && typeof from === "object" || typeof from === "function") {
1664
+ for (let key of __getOwnPropNames2(from))
1665
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1666
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1667
+ }
1668
+ return to;
1669
+ };
1670
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
1671
+ // If the importer is in node compatibility mode or this is not an ESM
1672
+ // file that has been converted to a CommonJS file using a Babel-
1673
+ // compatible transform (i.e. "__esModule" has not been set), then set
1674
+ // "default" to the CommonJS "module.exports" for node compatibility.
1675
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
1676
+ mod
1677
+ ));
1678
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1679
+ var index_exports = {};
1680
+ __export(index_exports, {
1681
+ buildAnalysisPrompt: () => buildAnalysisPrompt,
1682
+ truncateLogs: () => truncateLogs
1683
+ });
1684
+ module2.exports = __toCommonJS(index_exports);
1685
+ var import_shared4 = require_dist2();
1686
+ var import_fs2 = __toESM2(require("fs"));
1687
+ var import_path3 = __toESM2(require("path"));
1688
+ var MAX_LOG_CHARS = 2e4;
1689
+ var MAX_FILE_CHARS = 2e4;
1690
+ var MAX_CONTEXT_CHARS = 6e4;
1691
+ function truncateLogs(logs, maxChars = MAX_LOG_CHARS) {
1692
+ if (logs.length <= maxChars) return logs;
1693
+ const head = logs.slice(0, Math.floor(maxChars * 0.6));
1694
+ const tail = logs.slice(logs.length - Math.floor(maxChars * 0.4));
1695
+ const omitted = logs.length - head.length - tail.length;
1696
+ return `${head}
1697
+
1698
+ ... [${omitted} characters of log output omitted to fit the model's context] ...
1699
+
1700
+ ${tail}`;
1727
1701
  }
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;
1702
+ function resolveExistingPathPrefix(candidate) {
1703
+ let current = candidate.replace(/(?::\d+)+$/, "").replace(/['"()\[\]`]+$/, "").trim();
1704
+ while (current.length > 0) {
1733
1705
  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
- });
1706
+ if (import_fs2.default.existsSync(current)) {
1707
+ return current;
1708
+ }
1739
1709
  } catch {
1740
1710
  }
1711
+ const lastSpace = current.lastIndexOf(" ");
1712
+ if (lastSpace === -1) {
1713
+ const lastSlash = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\"));
1714
+ if (lastSlash === -1) {
1715
+ break;
1716
+ }
1717
+ current = current.slice(0, lastSlash).trim();
1718
+ } else {
1719
+ current = current.slice(0, lastSpace).trim();
1720
+ }
1741
1721
  }
1742
- return renderUnifiedDiff(changes, options);
1722
+ return null;
1743
1723
  }
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." };
1724
+ function getContextFiles(logs, cwd, rules) {
1725
+ const candidates = /* @__PURE__ */ new Set();
1726
+ const quotedRegex = /['"`]([^'"`\n]+)['"`]/g;
1727
+ let match;
1728
+ while ((match = quotedRegex.exec(logs)) !== null) {
1729
+ const p = match[1].trim();
1730
+ if (p.includes("/") || p.includes("\\") || p === "." || p.startsWith(".")) {
1731
+ candidates.add(p);
1732
+ }
1749
1733
  }
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}` };
1734
+ const winAbsRegex = /([a-zA-Z]:\\[^*?"<>|\n\r]+)/g;
1735
+ while ((match = winAbsRegex.exec(logs)) !== null) {
1736
+ candidates.add(match[1].trim());
1737
+ }
1738
+ const unixAbsRegex = /(\/[^*?"<>|\n\r\t]+)/g;
1739
+ while ((match = unixAbsRegex.exec(logs)) !== null) {
1740
+ candidates.add(match[1].trim());
1741
+ }
1742
+ const fallbackRegex = /(?:[a-zA-Z]:)?[a-zA-Z0-9_\-\/\\.]+\.(?:tsx?|jsx?|json|css|html|js|jsx)/g;
1743
+ const fallbackMatches = logs.match(fallbackRegex) || [];
1744
+ for (const m of fallbackMatches) {
1745
+ candidates.add(m.trim());
1746
+ }
1747
+ const resolvedPaths = /* @__PURE__ */ new Set();
1748
+ for (const candidate of candidates) {
1749
+ const absPathCandidate = import_path3.default.isAbsolute(candidate) ? candidate : import_path3.default.resolve(cwd, candidate);
1750
+ const resolved = resolveExistingPathPrefix(absPathCandidate);
1751
+ if (resolved && (0, import_shared4.isInsideDirectory)(cwd, resolved)) {
1752
+ resolvedPaths.add(import_path3.default.resolve(resolved));
1753
+ }
1754
+ }
1755
+ if (resolvedPaths.size === 0) return "";
1756
+ let context = "\n\n### \u{1F4C1} Codebase Context:\n";
1757
+ const processedFiles = /* @__PURE__ */ new Set();
1758
+ const addFileToContext = (filePath) => {
1759
+ const relPath = import_path3.default.relative(cwd, filePath);
1760
+ if (relPath.includes("node_modules") || relPath.startsWith("build") || relPath.startsWith("dist") || relPath.startsWith(".git")) {
1761
+ return;
1762
+ }
1763
+ if ((0, import_shared4.projectRelativePaths)(cwd, filePath).some((rel) => rules.secretBlockedBy(rel) !== void 0)) return;
1764
+ if (processedFiles.has(filePath)) return;
1765
+ if (context.length >= MAX_CONTEXT_CHARS) return;
1766
+ processedFiles.add(filePath);
1767
+ try {
1768
+ let content = import_fs2.default.readFileSync(filePath, "utf-8");
1769
+ if (content.length > MAX_FILE_CHARS) {
1770
+ const omitted = content.length - MAX_FILE_CHARS;
1771
+ content = `${content.slice(0, MAX_FILE_CHARS)}
1772
+ ... [file truncated: ${omitted} more characters not shown]`;
1763
1773
  }
1774
+ context += `
1775
+ --- File: ${relPath} ---
1776
+ \`\`\`
1777
+ ${content}
1778
+ \`\`\`
1779
+ `;
1780
+ } catch {
1764
1781
  }
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}` };
1782
+ };
1783
+ for (const absPath of resolvedPaths) {
1784
+ try {
1785
+ const stats = import_fs2.default.statSync(absPath);
1786
+ if (stats.isFile()) {
1787
+ addFileToContext(absPath);
1788
+ const parentDir = import_path3.default.dirname(absPath);
1789
+ const filesInDir = import_fs2.default.readdirSync(parentDir);
1790
+ const relParentDir = import_path3.default.relative(cwd, parentDir) || ".";
1791
+ context += `
1792
+ --- Directory files in "${relParentDir}": ---
1793
+ `;
1794
+ for (const file of filesInDir) {
1795
+ try {
1796
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(parentDir, file));
1797
+ const marker = fileStats.isDirectory() ? "/" : "";
1798
+ context += `- ${file}${marker}
1799
+ `;
1800
+ } catch {
1801
+ context += `- ${file}
1802
+ `;
1803
+ }
1804
+ }
1805
+ } else if (stats.isDirectory()) {
1806
+ const relParentDir = import_path3.default.relative(cwd, absPath) || ".";
1807
+ if (relParentDir !== ".") {
1808
+ const filesInDir = import_fs2.default.readdirSync(absPath);
1809
+ context += `
1810
+ --- Directory files in "${relParentDir}": ---
1811
+ `;
1812
+ for (const file of filesInDir) {
1813
+ try {
1814
+ const fileStats = import_fs2.default.statSync(import_path3.default.join(absPath, file));
1815
+ const marker = fileStats.isDirectory() ? "/" : "";
1816
+ context += `- ${file}${marker}
1817
+ `;
1818
+ } catch {
1819
+ context += `- ${file}
1820
+ `;
1821
+ }
1822
+ }
1823
+ if (filesInDir.length <= 15) {
1824
+ for (const file of filesInDir) {
1825
+ const filePathFull = import_path3.default.join(absPath, file);
1826
+ const fileExt = import_path3.default.extname(file).toLowerCase();
1827
+ try {
1828
+ if (import_fs2.default.statSync(filePathFull).isFile() && [".js", ".jsx", ".ts", ".tsx", ".json", ".css"].includes(fileExt)) {
1829
+ addFileToContext(filePathFull);
1830
+ }
1831
+ } catch {
1832
+ }
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+ } catch {
1768
1838
  }
1769
- current.set(absolutePath, patched.content);
1770
1839
  }
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 };
1840
+ return context;
1841
+ }
1842
+ function buildAnalysisPrompt(errorOutput, cwd, options = {}) {
1843
+ const warningMarker = "\u26A0\uFE0F [BugZero System Warning]";
1844
+ let compilerLogs = errorOutput;
1845
+ let historySection = "";
1846
+ if (errorOutput.includes(warningMarker)) {
1847
+ const parts = errorOutput.split(warningMarker);
1848
+ compilerLogs = parts[0].trim();
1849
+ const warnings = parts.slice(1).map((w) => w.trim());
1850
+ historySection = `
1851
+
1852
+ ### \u26A0\uFE0F Previous Failed Attempts:
1853
+ ${warnings.map((w, idx) => `Failed Attempt ${idx + 1}:
1854
+ ${w}`).join("\n\n")}
1855
+
1856
+ **CRITICAL RULE:** Do NOT suggest modifying or creating the files listed under "Previous Failed Attempts" if they failed with a "File not found" or "Search string not found" error. You must inspect the compiler error logs below to find the actual file that exists and contains the error.`;
1857
+ }
1858
+ compilerLogs = truncateLogs(compilerLogs);
1859
+ const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
1860
+ return `You are an expert software engineer specialising in fixing build, lint, and test failures.
1861
+
1862
+ A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
1863
+
1864
+ \`\`\`
1865
+ ${compilerLogs}
1866
+ \`\`\`${historySection}${contextSection}
1867
+
1868
+ Your task:
1869
+ 1. Root Cause: Identify the root cause of the build failure.
1870
+ 2. Codebase Context: Read the provided file contents and directory listings under "\u{1F4C1} Codebase Context" to locate the correct files, imports, and file paths. Do not guess filenames or contents that are not in the context.
1871
+ 3. Patch: Provide the minimal, precise fix. If the fix genuinely requires changes in more than one file (for example, a renamed export and every place that imports it), include one patch entry per file \u2014 all patches in your response are applied together, atomically.
1872
+
1873
+ Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fences, no extra text:
1874
+ {
1875
+ "rootCause": "One-sentence explanation of the error",
1876
+ "explanation": "short explanation of what you changed and why",
1877
+ "patches": [
1878
+ {
1879
+ "filePath": "relative/path/from/project/root/to/file.ts",
1880
+ "search": "exact code that currently exists in the file and must be replaced",
1881
+ "replace": "the corrected code that replaces the search string"
1882
+ }
1883
+ ]
1884
+ }
1885
+
1886
+ Critical rules:
1887
+ - "patches" must contain at least one entry. Only include more than one when the fix truly requires editing multiple files \u2014 most fixes need just one.
1888
+ - Each "filePath" must be a relative path from the project root (no leading /).
1889
+ - Never change secret files (.env and key files), lockfiles, CI workflow files, .git or node_modules. Patches to them are rejected, so fix the problem in another file.
1890
+ - Each "search" must be an EXACT character-for-character substring of that file's current content.
1891
+ - Each "replace" must be syntactically valid code.
1892
+ - If two patches target the same file, list them in the order they should be applied, and make sure each "search" reflects the file's content *after* the previous patch in this list has been applied to it.
1893
+ - Do NOT add backticks, markdown, or any text outside the JSON object.`;
1778
1894
  }
1779
1895
  }
1780
1896
  });
@@ -1908,15 +2024,15 @@ var require_dist7 = __commonJS({
1908
2024
  default: () => void 0
1909
2025
  })
1910
2026
  });
1911
- var import_ai_provider = require_dist3();
1912
- var import_prompts = require_dist5();
2027
+ var import_ai_provider = require_dist5();
2028
+ var import_prompts = require_dist6();
1913
2029
  var import_config2 = require_dist();
1914
- var import_patcher2 = require_dist6();
1915
- var import_analyzers = require_dist2();
1916
- var import_shared3 = require_dist4();
2030
+ var import_patcher3 = require_dist3();
2031
+ var import_analyzers = require_dist4();
2032
+ var import_shared4 = require_dist2();
1917
2033
  var provider = new import_ai_provider.OpenRouterProvider();
1918
2034
  function protectionFor(cwd) {
1919
- return (0, import_shared3.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
2035
+ return (0, import_shared4.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
1920
2036
  }
1921
2037
  function previewAnalysisPrompt(cwd, logs) {
1922
2038
  return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
@@ -1978,7 +2094,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1978
2094
  console.log(`[BugZero] Patching ${patches.length} file${patches.length === 1 ? "" : "s"}: ${fileList}`);
1979
2095
  console.log(`[BugZero] Reason: ${explanation}`);
1980
2096
  if (state.approve) {
1981
- const preview = (0, import_patcher2.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
2097
+ const preview = (0, import_patcher3.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
1982
2098
  if (!preview.success) return patchFailure(state, preview.error);
1983
2099
  const files = preview.changes.map((change) => change.filePath);
1984
2100
  const decision = await state.approve({
@@ -1987,7 +2103,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1987
2103
  rootCause: state.fixSuggestion.rootCause,
1988
2104
  explanation,
1989
2105
  files,
1990
- diff: (0, import_patcher2.renderUnifiedDiff)(preview.changes)
2106
+ diff: (0, import_patcher3.renderUnifiedDiff)(preview.changes)
1991
2107
  });
1992
2108
  if (!decision.approved) {
1993
2109
  console.log("[BugZero] Fix declined \u2014 nothing was changed.");
@@ -1999,7 +2115,7 @@ Any other files from that same suggestion were rolled back to keep the change at
1999
2115
  return { logs: declinedLogs, patchFailed: true, declinedFixes: 1 };
2000
2116
  }
2001
2117
  }
2002
- const result = (0, import_patcher2.applyPatches)(state.cwd, patches, {
2118
+ const result = (0, import_patcher3.applyPatches)(state.cwd, patches, {
2003
2119
  alreadyBackedUp: state.backedUpFiles,
2004
2120
  protection: protectionFor(state.cwd)
2005
2121
  });
@@ -2100,9 +2216,9 @@ var require_dist8 = __commonJS({
2100
2216
  });
2101
2217
  module2.exports = __toCommonJS(index_exports);
2102
2218
  var import_fs2 = __toESM2(require("fs"));
2103
- var import_path2 = __toESM2(require("path"));
2219
+ var import_path3 = __toESM2(require("path"));
2104
2220
  function detectFramework2(cwd = process.cwd()) {
2105
- const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path2.default.join(cwd, f)));
2221
+ const has = (...files) => files.some((f) => import_fs2.default.existsSync(import_path3.default.join(cwd, f)));
2106
2222
  if (has("next.config.js", "next.config.ts", "next.config.mjs")) return "nextjs";
2107
2223
  if (has("nest-cli.json")) return "nestjs";
2108
2224
  if (has("vite.config.ts", "vite.config.js", "vite.config.mts")) return "vite";
@@ -2110,7 +2226,7 @@ var require_dist8 = __commonJS({
2110
2226
  if (has("astro.config.mjs", "astro.config.ts", "astro.config.js")) return "astro";
2111
2227
  if (has("svelte.config.js", "svelte.config.ts")) return "sveltekit";
2112
2228
  if (has("nuxt.config.ts", "nuxt.config.js")) return "nuxt";
2113
- const pkgPath = import_path2.default.join(cwd, "package.json");
2229
+ const pkgPath = import_path3.default.join(cwd, "package.json");
2114
2230
  if (import_fs2.default.existsSync(pkgPath)) {
2115
2231
  try {
2116
2232
  const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
@@ -2126,14 +2242,14 @@ var require_dist8 = __commonJS({
2126
2242
  if (has("tsconfig.json")) return "typescript";
2127
2243
  return "unknown";
2128
2244
  }
2129
- var import_analyzers = require_dist2();
2245
+ var import_analyzers = require_dist4();
2130
2246
  var import_agents = require_dist7();
2131
- var import_shared22 = require_dist4();
2247
+ var import_shared22 = require_dist2();
2132
2248
  var import_fs3 = __toESM2(require("fs"));
2133
- var import_path3 = __toESM2(require("path"));
2249
+ var import_path32 = __toESM2(require("path"));
2134
2250
  var import_url = require("url");
2135
- var import_prompts = require_dist5();
2136
- var import_shared3 = require_dist4();
2251
+ var import_prompts = require_dist6();
2252
+ var import_shared4 = require_dist2();
2137
2253
  var MAX_REPORT_LOG_CHARS = 2e4;
2138
2254
  function capReportLogs(logs, maxChars = MAX_REPORT_LOG_CHARS) {
2139
2255
  return (0, import_prompts.truncateLogs)(logs, maxChars);
@@ -2171,7 +2287,7 @@ ${p.replace}`
2171
2287
  }
2172
2288
  function buildRescueSuccessPrompt(params) {
2173
2289
  const { cwd, attempts, appliedFix } = params;
2174
- const patchedFiles = (0, import_shared3.uniqueFilePaths)(appliedFix.patches).join(", ");
2290
+ const patchedFiles = (0, import_shared4.uniqueFilePaths)(appliedFix.patches).join(", ");
2175
2291
  return `You are an expert software engineer assistant. An automated AI agent successfully resolved a build/lint/test failure in a project located at "${cwd}" after ${attempts} attempts by applying a patch to: ${patchedFiles}.
2176
2292
  Here is the patch details:
2177
2293
  - Root Cause: ${appliedFix.rootCause}
@@ -2265,7 +2381,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2265
2381
  throw new Error(`No package.json found in ${cwd}. Point --path at a Node.js project.`);
2266
2382
  }
2267
2383
  }
2268
- var import_ai_provider = require_dist3();
2384
+ var import_ai_provider = require_dist5();
2269
2385
  var REPORT_FILENAME2 = "bugzero-report.md";
2270
2386
  function failureMessage(maxAttempts, declined, appliedAnything) {
2271
2387
  const plural = declined === 1 ? "fix" : "fixes";
@@ -2569,7 +2685,7 @@ ${rawOutput}
2569
2685
 
2570
2686
  ---
2571
2687
  *Report generated by **BugZero** on ${(/* @__PURE__ */ new Date()).toLocaleString()}*`;
2572
- const reportPath = import_path3.default.resolve(cwd, REPORT_FILENAME2);
2688
+ const reportPath = import_path32.default.resolve(cwd, REPORT_FILENAME2);
2573
2689
  try {
2574
2690
  import_fs3.default.writeFileSync(reportPath, content, "utf-8");
2575
2691
  const clickableUrl = (0, import_url.pathToFileURL)(reportPath).toString();
@@ -2587,19 +2703,21 @@ ${rawOutput}
2587
2703
  console.log("\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
2588
2704
  }
2589
2705
  }
2590
- var import_analyzers2 = require_dist2();
2706
+ var import_analyzers2 = require_dist4();
2591
2707
  }
2592
2708
  });
2593
2709
 
2594
2710
  // src/index.ts
2595
2711
  var import_config = __toESM(require_dist());
2712
+ var import_patcher2 = __toESM(require_dist3());
2713
+ var import_shared3 = __toESM(require_dist2());
2596
2714
  var import_commander = require("commander");
2597
2715
  var import_fs = __toESM(require("fs"));
2598
- var import_path = __toESM(require("path"));
2716
+ var import_path2 = __toESM(require("path"));
2599
2717
  var import_core = __toESM(require_dist8());
2600
2718
 
2601
2719
  // src/json-output.ts
2602
- var import_shared = __toESM(require_dist4());
2720
+ var import_shared = __toESM(require_dist2());
2603
2721
  function stepStatus(step) {
2604
2722
  if (step.skipped) return "skipped";
2605
2723
  return step.success ? "passed" : "failed";
@@ -2711,8 +2829,9 @@ function createApprovalHandler(io) {
2711
2829
  }
2712
2830
 
2713
2831
  // src/summary.ts
2714
- var import_patcher = __toESM(require_dist6());
2715
- var import_shared2 = __toESM(require_dist4());
2832
+ var import_patcher = __toESM(require_dist3());
2833
+ var import_path = __toESM(require("path"));
2834
+ var import_shared2 = __toESM(require_dist2());
2716
2835
  function tokenLines(result) {
2717
2836
  if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
2718
2837
  const total = result.promptTokens + result.completionTokens;
@@ -2768,10 +2887,35 @@ function buildChangeDiffLines(cwd, result) {
2768
2887
  if (diff === "") return [];
2769
2888
  return ["", "Changes (the original of each file is kept next to it as <file>.opspilot.bak):", "", ...diff.split("\n")];
2770
2889
  }
2890
+ function buildUndoHintLines(cwd, result, options) {
2891
+ if (options.dryRun || !result.appliedFix) return [];
2892
+ const command = import_path.default.resolve(cwd) === import_path.default.resolve(process.cwd()) ? "bugzero undo" : `bugzero undo --path "${import_path.default.resolve(cwd)}"`;
2893
+ const lead = result.success ? "To put the files back as they were:" : "BugZero changed files before giving up. To put them back as they were:";
2894
+ return ["", `${lead} ${command}`];
2895
+ }
2896
+ function buildUndoSummary(entries, options) {
2897
+ if (entries.length === 0) {
2898
+ return { exitCode: 0, lines: ["Nothing to undo \u2014 no BugZero backups (*.opspilot.bak) were found."] };
2899
+ }
2900
+ const lines = [];
2901
+ for (const entry of entries) {
2902
+ if (entry.status === "restored") lines.push(`\u21A9\uFE0F Restored ${entry.filePath}`);
2903
+ else if (entry.status === "would-restore") lines.push(`\u21A9\uFE0F Would restore ${entry.filePath}`);
2904
+ else lines.push(`\u23ED\uFE0F Skipped ${entry.filePath}: ${entry.detail ?? entry.status}`);
2905
+ }
2906
+ const done = entries.filter((entry) => entry.status === "restored" || entry.status === "would-restore").length;
2907
+ const left = entries.length - done;
2908
+ lines.push("");
2909
+ lines.push(
2910
+ options.dryRun ? `Dry run: ${done} file(s) would be restored. Nothing was changed.` : `Restored ${done} file(s).`
2911
+ );
2912
+ if (left > 0) lines.push(`${left} file(s) were left as they are, with their backups kept.`);
2913
+ return { exitCode: left > 0 ? 1 : 0, lines };
2914
+ }
2771
2915
 
2772
2916
  // src/index.ts
2773
2917
  (0, import_config.loadProjectEnv)(process.cwd());
2774
- var { version } = JSON.parse(import_fs.default.readFileSync(import_path.default.join(__dirname, "..", "package.json"), "utf-8"));
2918
+ var { version } = JSON.parse(import_fs.default.readFileSync(import_path2.default.join(__dirname, "..", "package.json"), "utf-8"));
2775
2919
  var TIMEOUT_DESCRIPTION = "Stop any build/lint/test command that runs longer than this many seconds";
2776
2920
  function parseTimeout(raw) {
2777
2921
  if (raw === void 0) return void 0;
@@ -2797,7 +2941,7 @@ program.command("hunt").description("Run build, lint, and tests \u2014 report is
2797
2941
  const json = opts.json === true;
2798
2942
  if (json) routeLogsToStderr();
2799
2943
  try {
2800
- const cwd = import_path.default.resolve(opts.path);
2944
+ const cwd = import_path2.default.resolve(opts.path);
2801
2945
  (0, import_config.loadProjectEnv)(cwd);
2802
2946
  const timeoutSeconds = parseTimeout(opts.timeout);
2803
2947
  const framework = (0, import_core.detectFramework)(cwd);
@@ -2823,7 +2967,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2823
2967
  finish(
2824
2968
  allPassed ? 0 : 1,
2825
2969
  json ? buildHuntJson(
2826
- { path: cwd, framework, packageManager, reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME) },
2970
+ { path: cwd, framework, packageManager, reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME) },
2827
2971
  { build, lint, test }
2828
2972
  ) : void 0
2829
2973
  );
@@ -2838,7 +2982,7 @@ program.command("rescue").description("Detect build failures and automatically a
2838
2982
  const printPrompt = opts.printPrompt === true;
2839
2983
  if (json || printPrompt) routeLogsToStderr();
2840
2984
  try {
2841
- const cwd = import_path.default.resolve(opts.path);
2985
+ const cwd = import_path2.default.resolve(opts.path);
2842
2986
  (0, import_config.loadProjectEnv)(cwd);
2843
2987
  const maxAttempts = (0, import_core.resolveMaxAttempts)(Number(opts.maxAttempts));
2844
2988
  const timeoutSeconds = parseTimeout(opts.timeout);
@@ -2873,7 +3017,7 @@ program.command("rescue").description("Detect build failures and automatically a
2873
3017
  framework,
2874
3018
  packageManager,
2875
3019
  dryRun,
2876
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3020
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2877
3021
  })
2878
3022
  );
2879
3023
  } else {
@@ -2886,6 +3030,7 @@ program.command("rescue").description("Detect build failures and automatically a
2886
3030
  const summary = buildRescueSummary(result, { dryRun });
2887
3031
  for (const line of summary.lines) console.log(line);
2888
3032
  for (const line of buildChangeDiffLines(cwd, result)) console.log(line);
3033
+ for (const line of buildUndoHintLines(cwd, result, { dryRun })) console.log(line);
2889
3034
  console.log();
2890
3035
  finish(
2891
3036
  summary.exitCode,
@@ -2894,7 +3039,7 @@ program.command("rescue").description("Detect build failures and automatically a
2894
3039
  framework,
2895
3040
  packageManager,
2896
3041
  dryRun,
2897
- reportPath: import_path.default.resolve(cwd, import_core.REPORT_FILENAME)
3042
+ reportPath: import_path2.default.resolve(cwd, import_core.REPORT_FILENAME)
2898
3043
  }) : void 0
2899
3044
  );
2900
3045
  } catch (error) {
@@ -2903,6 +3048,25 @@ program.command("rescue").description("Detect build failures and automatically a
2903
3048
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2904
3049
  }
2905
3050
  });
3051
+ program.command("undo").description("Put back the files BugZero changed, from the backups saved next to them").option("-p, --path <dir>", "Path to the target project", ".").option("--dry-run", "Show what would be restored without changing anything", false).option("--force", "Also restore files that were edited after BugZero fixed them (those edits are lost)", false).action((opts) => {
3052
+ try {
3053
+ const cwd = import_path2.default.resolve(opts.path);
3054
+ const entries = (0, import_patcher2.undoChanges)(cwd, {
3055
+ dryRun: opts.dryRun === true,
3056
+ force: opts.force === true,
3057
+ protection: (0, import_shared3.createProtectedPathRules)((0, import_config.getProtectionSettings)(cwd))
3058
+ });
3059
+ const summary = buildUndoSummary(entries, { dryRun: opts.dryRun === true });
3060
+ console.log();
3061
+ for (const line of summary.lines) console.log(line);
3062
+ console.log();
3063
+ finish(summary.exitCode);
3064
+ } catch (error) {
3065
+ console.error(`
3066
+ \u274C [BugZero] Execution failed: ${error.message || error}`);
3067
+ finish(1);
3068
+ }
3069
+ });
2906
3070
  program.command("protect").description("[Deprecated] Use 'hunt' instead").action(async () => {
2907
3071
  console.warn("\u26A0\uFE0F 'protect' is deprecated \u2014 use 'bugzero hunt' instead.\n");
2908
3072
  const result = await (0, import_core.orchestrate)();