bugzero 0.0.55 → 0.0.57

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 +11 -0
  2. package/dist/index.js +378 -56
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -212,10 +212,20 @@ bugzero hunt --no-ai-report
212
212
  ### `bugzero rescue`
213
213
  Run the full AI-powered repair loop. Detects build failures, generates precise code patches, applies them, and verifies the result.
214
214
 
215
+ When it fixes your project, `rescue` prints a diff of exactly what changed in each file, so you can review it at once. The original of every edited file is kept next to it as `<file>.opspilot.bak`.
216
+
215
217
  ```bash
216
218
  bugzero rescue --path /path/to/your/project
217
219
  ```
218
220
 
221
+ **Review each fix first with `--approve`.** BugZero shows the AI's proposed change as a diff and asks before it writes anything:
222
+
223
+ ```text
224
+ Apply this change? [y] yes [n] no [m] no, and leave a note for the AI (Enter = no):
225
+ ```
226
+
227
+ The whole proposed fix is shown at once, because a fix that spans several files is applied together or not at all. Answer `y` to apply it. Answer `n` (or just press Enter) to decline: nothing is changed, and the AI is told you declined and asked for a different fix, which uses up one attempt. Answer `m` to decline and type a short note that is sent to the AI, such as "leave the config file alone". `--approve` needs an interactive terminal; without one (in CI, or with piped input) it stops immediately, before running anything. It has no effect with `--dry-run` or `--print-prompt`, which never write.
228
+
219
229
  <details>
220
230
  <summary><strong>Options for <code>rescue</code></strong></summary>
221
231
 
@@ -225,6 +235,7 @@ bugzero rescue --path /path/to/your/project
225
235
  | `--max-attempts <n>` | `-n` | `3` | Maximum AI fix iterations before giving up |
226
236
  | `--timeout <seconds>` | `-t` | none | Stop any build, lint, or test command that runs longer than this many seconds |
227
237
  | `--dry-run` | | `false` | Analyze only — no files will be written |
238
+ | `--approve` | | `false` | Show each proposed fix as a diff and ask before writing it. Needs an interactive terminal |
228
239
  | `--print-prompt` | | `false` | Print the exact prompt that would be sent to the AI model, then stop. Nothing is sent and no files are written |
229
240
  | `--json` | | `false` | Print the result as one JSON document on stdout (logs go to stderr) |
230
241
 
package/dist/index.js CHANGED
@@ -1330,7 +1330,12 @@ var require_dist6 = __commonJS({
1330
1330
  applyPatch: () => applyPatch,
1331
1331
  applyPatches: () => applyPatches,
1332
1332
  findMatch: () => findMatch,
1333
- lineSimilarity: () => lineSimilarity
1333
+ lineSimilarity: () => lineSimilarity,
1334
+ patchContent: () => patchContent,
1335
+ previewPatches: () => previewPatches,
1336
+ renderChangesFromBackups: () => renderChangesFromBackups2,
1337
+ renderUnifiedDiff: () => renderUnifiedDiff,
1338
+ resolvePatchTargets: () => resolvePatchTargets
1334
1339
  });
1335
1340
  module2.exports = __toCommonJS(index_exports);
1336
1341
  var import_fs2 = __toESM2(require("fs"));
@@ -1454,6 +1459,18 @@ var require_dist6 = __commonJS({
1454
1459
  function withLineEnding(text, ending) {
1455
1460
  return text.replace(/\r\n|\n/g, ending);
1456
1461
  }
1462
+ function patchContent(original, search, replace, fileName) {
1463
+ const match = findMatch(original, search);
1464
+ if (!match) {
1465
+ 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.`
1468
+ };
1469
+ }
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
+ }
1457
1474
  function applyPatch(absoluteFilePath, search, replace, options = {}) {
1458
1475
  try {
1459
1476
  if (!import_fs2.default.existsSync(absoluteFilePath)) {
@@ -1463,27 +1480,40 @@ var require_dist6 = __commonJS({
1463
1480
  };
1464
1481
  }
1465
1482
  const original = import_fs2.default.readFileSync(absoluteFilePath, "utf-8");
1466
- const match = findMatch(original, search);
1467
- if (!match) {
1468
- return {
1469
- success: false,
1470
- error: `Search string not found in ${import_path2.default.basename(absoluteFilePath)} (tried exact, whitespace-normalized, and fuzzy matching). The AI's "search" field did not match file content.`
1471
- };
1472
- }
1483
+ const patched = patchContent(original, search, replace, import_path2.default.basename(absoluteFilePath));
1484
+ if (!patched.ok) return { success: false, error: patched.error };
1473
1485
  const backupPath = absoluteFilePath + ".opspilot.bak";
1474
1486
  if (options.backup !== false) {
1475
1487
  import_fs2.default.writeFileSync(backupPath, original, "utf-8");
1476
1488
  }
1477
- const replacement = withLineEnding(replace, detectLineEnding(original, match.start, match.end));
1478
- const fixed = original.slice(0, match.start) + replacement + original.slice(match.end);
1479
- import_fs2.default.writeFileSync(absoluteFilePath, fixed, "utf-8");
1480
- return { success: true, backupPath, matchStrategy: match.strategy };
1489
+ import_fs2.default.writeFileSync(absoluteFilePath, patched.content, "utf-8");
1490
+ return { success: true, backupPath, matchStrategy: patched.matchStrategy };
1481
1491
  } catch (err) {
1482
1492
  return { success: false, error: err.message };
1483
1493
  }
1484
1494
  }
1485
- var import_shared3 = require_dist4();
1486
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);
1514
+ }
1515
+ return { ok: true, absolutePaths };
1516
+ }
1487
1517
  function rollback(originalContent, backupPaths) {
1488
1518
  for (const [absolutePath, content] of originalContent) {
1489
1519
  try {
@@ -1502,29 +1532,11 @@ var require_dist6 = __commonJS({
1502
1532
  if (patches.length === 0) {
1503
1533
  return { success: false, error: "No patches to apply.", applied: [] };
1504
1534
  }
1505
- const protection = options.protection ?? (0, import_shared3.createProtectedPathRules)();
1506
- const absolutePaths = [];
1507
- for (const patch of patches) {
1508
- const resolved = (0, import_shared3.resolveInsideProject)(cwd, patch.filePath);
1509
- if (!resolved.ok) {
1510
- return {
1511
- success: false,
1512
- error: `Failed to patch "${patch.filePath}": ${resolved.error}`,
1513
- applied: []
1514
- };
1515
- }
1516
- for (const relPath of (0, import_shared3.projectRelativePaths)(cwd, resolved.absolutePath)) {
1517
- const pattern = protection.editBlockedBy(relPath);
1518
- if (pattern !== void 0) {
1519
- return {
1520
- success: false,
1521
- error: `Failed to patch "${patch.filePath}": this file is protected (it matches "${pattern}"), so BugZero never edits it. Fix the problem in a different file.`,
1522
- applied: []
1523
- };
1524
- }
1525
- }
1526
- absolutePaths.push(resolved.absolutePath);
1535
+ const targets = resolvePatchTargets(cwd, patches, options.protection);
1536
+ if (!targets.ok) {
1537
+ return { success: false, error: targets.error, applied: [] };
1527
1538
  }
1539
+ const absolutePaths = targets.absolutePaths;
1528
1540
  const originalContent = /* @__PURE__ */ new Map();
1529
1541
  const backupPaths = /* @__PURE__ */ new Set();
1530
1542
  const applied = [];
@@ -1566,6 +1578,204 @@ var require_dist6 = __commonJS({
1566
1578
  }
1567
1579
  return { success: true, applied };
1568
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
+ }
1640
+ }
1641
+ return null;
1642
+ }
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++;
1649
+ }
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]`;
1667
+ }
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++;
1686
+ }
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 });
1697
+ }
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));
1716
+ }
1717
+ }
1718
+ return output;
1719
+ }
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");
1727
+ }
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;
1733
+ 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
+ });
1739
+ } catch {
1740
+ }
1741
+ }
1742
+ return renderUnifiedDiff(changes, options);
1743
+ }
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." };
1749
+ }
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}` };
1763
+ }
1764
+ }
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}` };
1768
+ }
1769
+ current.set(absolutePath, patched.content);
1770
+ }
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 };
1778
+ }
1569
1779
  }
1570
1780
  });
1571
1781
 
@@ -1682,6 +1892,16 @@ var require_dist7 = __commonJS({
1682
1892
  reducer: (old, value) => old + value,
1683
1893
  default: () => 0
1684
1894
  }),
1895
+ /** When set, each proposed fix is shown to this handler and only written if it approves */
1896
+ approve: (0, import_langgraph.Annotation)({
1897
+ reducer: (_, value) => value,
1898
+ default: () => void 0
1899
+ }),
1900
+ /** How many proposed fixes the person declined */
1901
+ declinedFixes: (0, import_langgraph.Annotation)({
1902
+ reducer: (total, added) => total + added,
1903
+ default: () => 0
1904
+ }),
1685
1905
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
1686
1906
  timeoutMs: (0, import_langgraph.Annotation)({
1687
1907
  reducer: (_, value) => value,
@@ -1691,7 +1911,7 @@ var require_dist7 = __commonJS({
1691
1911
  var import_ai_provider = require_dist3();
1692
1912
  var import_prompts = require_dist5();
1693
1913
  var import_config2 = require_dist();
1694
- var import_patcher = require_dist6();
1914
+ var import_patcher2 = require_dist6();
1695
1915
  var import_analyzers = require_dist2();
1696
1916
  var import_shared3 = require_dist4();
1697
1917
  var provider = new import_ai_provider.OpenRouterProvider();
@@ -1735,6 +1955,19 @@ var require_dist7 = __commonJS({
1735
1955
  completionTokens: result.usage?.completion_tokens ?? 0
1736
1956
  };
1737
1957
  }
1958
+ function patchFailure(state, error) {
1959
+ console.error(`[BugZero] Patch failed: ${error}`);
1960
+ const updatedLogs = `${state.logs}
1961
+
1962
+ \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion failed with the following error:
1963
+ - ${error}
1964
+
1965
+ Any other files from that same suggestion were rolled back to keep the change atomic. Please check if the file path(s) are correct relative to the project root and make sure you target the correct file(s) that contain the build error.`;
1966
+ return {
1967
+ logs: updatedLogs,
1968
+ patchFailed: true
1969
+ };
1970
+ }
1738
1971
  async function applyFixNode(state) {
1739
1972
  if (!state.fixSuggestion) {
1740
1973
  console.warn("[BugZero] No fix suggestion available \u2014 skipping patch.");
@@ -1744,23 +1977,33 @@ var require_dist7 = __commonJS({
1744
1977
  const fileList = patches.map((p) => p.filePath).join(", ");
1745
1978
  console.log(`[BugZero] Patching ${patches.length} file${patches.length === 1 ? "" : "s"}: ${fileList}`);
1746
1979
  console.log(`[BugZero] Reason: ${explanation}`);
1747
- const result = (0, import_patcher.applyPatches)(state.cwd, patches, {
1980
+ if (state.approve) {
1981
+ const preview = (0, import_patcher2.previewPatches)(state.cwd, patches, { protection: protectionFor(state.cwd) });
1982
+ if (!preview.success) return patchFailure(state, preview.error);
1983
+ const files = preview.changes.map((change) => change.filePath);
1984
+ const decision = await state.approve({
1985
+ attempt: state.attempts,
1986
+ maxAttempts: state.maxAttempts,
1987
+ rootCause: state.fixSuggestion.rootCause,
1988
+ explanation,
1989
+ files,
1990
+ diff: (0, import_patcher2.renderUnifiedDiff)(preview.changes)
1991
+ });
1992
+ if (!decision.approved) {
1993
+ console.log("[BugZero] Fix declined \u2014 nothing was changed.");
1994
+ const note = decision.note?.trim();
1995
+ const userNote = note ? ` The user's note: "${note}".` : "";
1996
+ const declinedLogs = `${state.logs}
1997
+
1998
+ \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion was declined by the user, so nothing was changed. The files it would have changed were: ${files.join(", ")}.${userNote} Propose a different fix.`;
1999
+ return { logs: declinedLogs, patchFailed: true, declinedFixes: 1 };
2000
+ }
2001
+ }
2002
+ const result = (0, import_patcher2.applyPatches)(state.cwd, patches, {
1748
2003
  alreadyBackedUp: state.backedUpFiles,
1749
2004
  protection: protectionFor(state.cwd)
1750
2005
  });
1751
- if (!result.success) {
1752
- console.error(`[BugZero] Patch failed: ${result.error}`);
1753
- const updatedLogs = `${state.logs}
1754
-
1755
- \u26A0\uFE0F [BugZero System Warning] Your previous patch suggestion failed with the following error:
1756
- - ${result.error}
1757
-
1758
- Any other files from that same suggestion were rolled back to keep the change atomic. Please check if the file path(s) are correct relative to the project root and make sure you target the correct file(s) that contain the build error.`;
1759
- return {
1760
- logs: updatedLogs,
1761
- patchFailed: true
1762
- };
1763
- }
2006
+ if (!result.success) return patchFailure(state, result.error);
1764
2007
  for (const applied of result.applied) {
1765
2008
  console.log(`[BugZero] Backup saved to: ${applied.backupPath}`);
1766
2009
  if (applied.matchStrategy !== "exact") {
@@ -2024,6 +2267,14 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2024
2267
  }
2025
2268
  var import_ai_provider = require_dist3();
2026
2269
  var REPORT_FILENAME2 = "bugzero-report.md";
2270
+ function failureMessage(maxAttempts, declined, appliedAnything) {
2271
+ const plural = declined === 1 ? "fix" : "fixes";
2272
+ if (declined > 0 && !appliedAnything) {
2273
+ return `You declined ${declined} proposed ${plural}, so nothing was changed.`;
2274
+ }
2275
+ const base = `Max attempts (${maxAttempts}) reached without a successful build.`;
2276
+ return declined > 0 ? `${base} You declined ${declined} proposed ${plural}.` : base;
2277
+ }
2027
2278
  function statusLabel(result) {
2028
2279
  if (result.skipped) return "\u23ED\uFE0F Skipped (no script defined)";
2029
2280
  return result.success ? "\u2705 Passed" : "\u274C Failed";
@@ -2100,14 +2351,16 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2100
2351
  cwd,
2101
2352
  logs: pipelineResult.output,
2102
2353
  maxAttempts,
2103
- timeoutMs
2354
+ timeoutMs,
2355
+ approve: options.approve
2104
2356
  });
2105
2357
  const result = {
2106
2358
  success: finalState.success,
2107
2359
  attempts: finalState.attempts,
2108
2360
  finalOutput: finalState.logs || pipelineResult.output,
2109
2361
  appliedFix: finalState.appliedFix ?? void 0,
2110
- error: finalState.success ? void 0 : `Max attempts (${maxAttempts}) reached without a successful build.`,
2362
+ error: finalState.success ? void 0 : failureMessage(maxAttempts, finalState.declinedFixes ?? 0, Boolean(finalState.appliedFix)),
2363
+ declinedFixes: finalState.declinedFixes ? finalState.declinedFixes : void 0,
2111
2364
  modelUsed: finalState.modelUsed,
2112
2365
  promptTokens: finalState.promptTokens,
2113
2366
  completionTokens: finalState.completionTokens
@@ -2405,7 +2658,60 @@ function buildErrorJson(message) {
2405
2658
  return { success: false, error: message };
2406
2659
  }
2407
2660
 
2661
+ // src/approval.ts
2662
+ var import_readline = __toESM(require("readline"));
2663
+ var MAX_INVALID_ANSWERS = 5;
2664
+ function parseApprovalAnswer(raw) {
2665
+ const answer = raw.trim().toLowerCase();
2666
+ if (answer === "y" || answer === "yes") return "yes";
2667
+ if (answer === "" || answer === "n" || answer === "no") return "no";
2668
+ if (answer === "m" || answer === "note") return "note";
2669
+ return "invalid";
2670
+ }
2671
+ function createApprovalHandler(io) {
2672
+ const lines = import_readline.default.createInterface({ input: io.input, terminal: false })[Symbol.asyncIterator]();
2673
+ const ask = async (question) => {
2674
+ io.output.write(question);
2675
+ const next = await lines.next();
2676
+ return next.done ? void 0 : next.value;
2677
+ };
2678
+ return async (request) => {
2679
+ io.output.write(
2680
+ [
2681
+ "",
2682
+ `Proposed fix (attempt ${request.attempt}/${request.maxAttempts})`,
2683
+ ` Root cause: ${request.rootCause}`,
2684
+ ` Explanation: ${request.explanation}`,
2685
+ ` Files: ${request.files.join(", ")}`,
2686
+ "",
2687
+ request.diff,
2688
+ "",
2689
+ ""
2690
+ ].join("\n")
2691
+ );
2692
+ for (let invalid = 0; invalid < MAX_INVALID_ANSWERS; ) {
2693
+ const raw = await ask("Apply this change? [y] yes [n] no [m] no, and leave a note for the AI (Enter = no): ");
2694
+ if (raw === void 0) {
2695
+ io.output.write("\nNo answer, so the change was not applied.\n");
2696
+ return { approved: false };
2697
+ }
2698
+ const answer = parseApprovalAnswer(raw);
2699
+ if (answer === "yes") return { approved: true };
2700
+ if (answer === "no") return { approved: false };
2701
+ if (answer === "note") {
2702
+ const note = (await ask("Note for the AI: "))?.trim();
2703
+ return note ? { approved: false, note } : { approved: false };
2704
+ }
2705
+ invalid++;
2706
+ io.output.write("Please answer y, n or m.\n");
2707
+ }
2708
+ io.output.write("Too many unclear answers, so the change was not applied.\n");
2709
+ return { approved: false };
2710
+ };
2711
+ }
2712
+
2408
2713
  // src/summary.ts
2714
+ var import_patcher = __toESM(require_dist6());
2409
2715
  var import_shared2 = __toESM(require_dist4());
2410
2716
  function tokenLines(result) {
2411
2717
  if (result.promptTokens === void 0 || result.completionTokens === void 0) return [];
@@ -2456,6 +2762,12 @@ function buildRescueSummary(result, options) {
2456
2762
  lines.push("", "\u{1F449} Full unresolved error logs have been listed in the generated report.");
2457
2763
  return { exitCode: 1, lines };
2458
2764
  }
2765
+ function buildChangeDiffLines(cwd, result) {
2766
+ if (!result.success || !result.appliedFix) return [];
2767
+ const diff = (0, import_patcher.renderChangesFromBackups)(cwd, (0, import_shared2.uniqueFilePaths)(result.appliedFix.patches));
2768
+ if (diff === "") return [];
2769
+ return ["", "Changes (the original of each file is kept next to it as <file>.opspilot.bak):", "", ...diff.split("\n")];
2770
+ }
2459
2771
 
2460
2772
  // src/index.ts
2461
2773
  (0, import_config.loadProjectEnv)(process.cwd());
@@ -2521,7 +2833,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
2521
2833
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
2522
2834
  }
2523
2835
  });
2524
- program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
2836
+ program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
2525
2837
  const json = opts.json === true;
2526
2838
  const printPrompt = opts.printPrompt === true;
2527
2839
  if (json || printPrompt) routeLogsToStderr();
@@ -2531,6 +2843,15 @@ program.command("rescue").description("Detect build failures and automatically a
2531
2843
  const maxAttempts = (0, import_core.resolveMaxAttempts)(Number(opts.maxAttempts));
2532
2844
  const timeoutSeconds = parseTimeout(opts.timeout);
2533
2845
  const dryRun = opts.dryRun;
2846
+ let approve;
2847
+ if (opts.approve === true && !dryRun && !printPrompt) {
2848
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
2849
+ throw new Error(
2850
+ "--approve asks you to confirm each fix, which needs an interactive terminal, and there is none here (for example in CI, or when input is piped). Run it in a terminal, or leave out --approve."
2851
+ );
2852
+ }
2853
+ approve = createApprovalHandler({ input: process.stdin, output: process.stderr });
2854
+ }
2534
2855
  const framework = (0, import_core.detectFramework)(cwd);
2535
2856
  const packageManager = (0, import_core.detectPackageManager)(cwd);
2536
2857
  console.log(`
@@ -2542,7 +2863,7 @@ program.command("rescue").description("Detect build failures and automatically a
2542
2863
  if (timeoutSeconds !== void 0) console.log(` Timeout: ${timeoutSeconds}s per command`);
2543
2864
  if (dryRun) console.log(` Mode: DRY RUN (no files will be modified)`);
2544
2865
  console.log();
2545
- const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt });
2866
+ const result = await (0, import_core.orchestrateAndFix)({ cwd, maxAttempts, dryRun, timeoutSeconds, printPrompt, approve });
2546
2867
  if (result.promptPreview !== void 0) {
2547
2868
  if (json) {
2548
2869
  finish(
@@ -2564,6 +2885,7 @@ program.command("rescue").description("Detect build failures and automatically a
2564
2885
  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");
2565
2886
  const summary = buildRescueSummary(result, { dryRun });
2566
2887
  for (const line of summary.lines) console.log(line);
2888
+ for (const line of buildChangeDiffLines(cwd, result)) console.log(line);
2567
2889
  console.log();
2568
2890
  finish(
2569
2891
  summary.exitCode,
@@ -2588,7 +2910,7 @@ program.command("protect").description("[Deprecated] Use 'hunt' instead").action
2588
2910
  });
2589
2911
  program.command("vibe").description("Select which AI model (brain) to use for resolving bugs").action(async () => {
2590
2912
  const { getLocalConfig, saveLocalConfig } = await Promise.resolve().then(() => __toESM(require_dist()));
2591
- const readline = await import("readline");
2913
+ const readline2 = await import("readline");
2592
2914
  const axios = (await import("axios")).default;
2593
2915
  console.log(`
2594
2916
  \u{1F9E0} BugZero Brain Selector`);
@@ -2631,7 +2953,7 @@ Current active model: \x1B[36m${currentModel}\x1B[0m
2631
2953
  });
2632
2954
  console.log(` [${popularModels.length + 1}] \u{1F58B}\uFE0F Custom Model (Type manually)`);
2633
2955
  console.log();
2634
- const rl = readline.createInterface({
2956
+ const rl = readline2.createInterface({
2635
2957
  input: process.stdin,
2636
2958
  output: process.stdout
2637
2959
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.55",
3
+ "version": "0.0.57",
4
4
  "description": "Autonomous AI-powered CLI and GitHub Action that detects build, lint, and test failures, generates multi-file patches, applies them atomically with fuzzy matching, and re-verifies until your project is green.",
5
5
  "license": "MIT",
6
6
  "author": "Saksham Agarwal (https://github.com/Saksham1800t)",
@@ -55,6 +55,7 @@
55
55
  "@opspilot/agents": "workspace:*",
56
56
  "@opspilot/config": "workspace:*",
57
57
  "@opspilot/core": "workspace:*",
58
+ "@opspilot/patcher": "workspace:*",
58
59
  "@opspilot/shared": "workspace:*"
59
60
  },
60
61
  "main": "./dist/index.js",