wolverine-ai 1.5.1 → 1.5.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wolverine-ai",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
4
4
  "description": "Self-healing Node.js server framework powered by AI. Catches crashes, diagnoses errors, generates fixes, verifies, and restarts — automatically.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -47,6 +47,12 @@
47
47
  "startDelayMs": 10000
48
48
  },
49
49
 
50
+ "errorMonitor": {
51
+ "defaultThreshold": 3,
52
+ "windowMs": 30000,
53
+ "cooldownMs": 60000
54
+ },
55
+
50
56
  "dashboard": {},
51
57
 
52
58
  "cors": {
@@ -335,7 +335,7 @@ async function _chatCallWithHistory(openai, { model, messages, tools, maxTokens
335
335
  * Send an error context to OpenAI and get a repair patch back.
336
336
  * Uses CODING_MODEL — routes to correct API automatically.
337
337
  */
338
- async function requestRepair({ filePath, sourceCode, errorMessage, stackTrace }) {
338
+ async function requestRepair({ filePath, sourceCode, backupSourceCode, errorMessage, stackTrace }) {
339
339
  const model = getModel("coding");
340
340
 
341
341
  const systemPrompt = "You are a Node.js debugging expert. Respond with ONLY valid JSON, no markdown fences.";
@@ -357,7 +357,7 @@ ${errorMessage}
357
357
  ${stackTrace}
358
358
  \`\`\`
359
359
 
360
- ## Instructions
360
+ ${backupSourceCode ? `## Last Known Working Version\n\`\`\`javascript\n${backupSourceCode}\n\`\`\`\n\nCompare the current broken code with this working version. If the broken code added something that doesn't work, REVERT that addition rather than patching around it.\n` : ""}## Instructions
361
361
  1. Identify the root cause of the error.
362
362
  2. Not all errors are code bugs. Choose the correct fix type:
363
363
  - "Cannot find module 'X'" (not starting with ./ or ../) = missing npm package → use "commands" to npm install
@@ -139,6 +139,7 @@ class WolverineRunner {
139
139
  this._stabilityTimer = null;
140
140
  this._stderrBuffer = "";
141
141
  this._healInProgress = false;
142
+ this._healStatus = null; // { active, file, error, phase, startedAt, iteration }
142
143
  }
143
144
 
144
145
  async start() {
@@ -410,6 +411,7 @@ class WolverineRunner {
410
411
  async _healAndRestart() {
411
412
  if (this._healInProgress) return;
412
413
  this._healInProgress = true;
414
+ this._healStatus = { active: true, error: this._stderrBuffer.slice(0, 200), phase: "diagnosing", startedAt: Date.now() };
413
415
 
414
416
  try {
415
417
  const result = await heal({
@@ -429,14 +431,23 @@ class WolverineRunner {
429
431
 
430
432
  if (result.healed) {
431
433
  this._lastBackupId = result.backupId;
432
- const mode = result.mode === "agent" ? "multi-file agent" : "fast path";
434
+ this.retryCount = 0; // Fresh start after successful heal
435
+ const mode = result.mode === "agent" ? "multi-file agent" : result.mode || "fast path";
433
436
  console.log(chalk.green(`\n🐺 Wolverine healed the error via ${mode}! Restarting...\n`));
434
437
 
435
438
  if (result.agentStats) {
436
439
  console.log(chalk.gray(` Agent stats: ${result.agentStats.turns} turns, ${result.agentStats.tokens} tokens, ${result.agentStats.filesModified.length} files modified`));
437
440
  }
438
441
 
442
+ // Broadcast heal success to dashboard SSE
443
+ if (this.logger) {
444
+ this.logger.info("heal.success", `Healed via ${mode}: ${result.explanation?.slice(0, 100)}`, {
445
+ mode, file: result.agentStats?.filesModified?.[0], duration: Date.now() - (this._healStatus?.startedAt || Date.now()),
446
+ });
447
+ }
448
+
439
449
  this._healInProgress = false;
450
+ this._healStatus = null;
440
451
  this._spawn();
441
452
  } else {
442
453
  console.log(chalk.red(`\n🐺 Wolverine could not heal: ${result.explanation}`));
@@ -479,6 +490,7 @@ class WolverineRunner {
479
490
  this._healInProgress = true;
480
491
 
481
492
  console.log(chalk.yellow(`\n🐺 Wolverine healing caught error on ${routePath}...`));
493
+ this._healStatus = { active: true, route: routePath, error: errorDetails?.message?.slice(0, 200), phase: "diagnosing", startedAt: Date.now() };
482
494
  this.logger.info("heal.error_monitor", `Healing caught 500 on ${routePath}`, { route: routePath });
483
495
 
484
496
  // Build a synthetic stderr from the error details
@@ -506,16 +518,28 @@ class WolverineRunner {
506
518
 
507
519
  if (result.healed) {
508
520
  console.log(chalk.green(`\n🐺 Wolverine healed ${routePath} via ${result.mode}! Restarting...\n`));
521
+ this.retryCount = 0; // Fresh start after successful heal
509
522
  this.errorMonitor.clearRoute(routePath);
523
+
524
+ // Broadcast heal success to dashboard SSE
525
+ if (this.logger) {
526
+ this.logger.info("heal.success", `Healed ${routePath} via ${result.mode}: ${result.explanation?.slice(0, 100)}`, {
527
+ mode: result.mode, route: routePath, duration: Date.now() - (this._healStatus?.startedAt || Date.now()),
528
+ });
529
+ }
530
+
510
531
  this._healInProgress = false;
532
+ this._healStatus = null;
511
533
  this.restart();
512
534
  } else {
513
535
  console.log(chalk.red(`\n🐺 Could not heal ${routePath}: ${result.explanation}`));
514
536
  this._healInProgress = false;
537
+ this._healStatus = null;
515
538
  }
516
539
  } catch (err) {
517
540
  console.log(chalk.red(`\n🐺 Error during heal: ${err.message}`));
518
541
  this._healInProgress = false;
542
+ this._healStatus = null;
519
543
  }
520
544
  }
521
545
 
@@ -83,16 +83,22 @@ async function heal({ stderr, cwd, sandbox, notifier, rateLimiter, backupManager
83
83
  let openaiClient = null;
84
84
  try { openaiClient = getClient(); } catch { /* will fail later */ }
85
85
 
86
- const injectionResult = await detectInjection(parsed.errorMessage, parsed.stackTrace, { openaiClient });
87
-
88
- if (logger) logger.info(EVENT_TYPES.HEAL_INJECTION_SCAN, `Injection scan: ${injectionResult.safe ? "clean" : "BLOCKED"}`, injectionResult);
89
-
90
- if (!injectionResult.safe) {
91
- console.log(chalk.red(" 🚨 BLOCKED: Potential prompt injection detected."));
92
- if (logger) logger.critical(EVENT_TYPES.SECURITY_INJECTION_DETECTED, "Injection detected — repair blocked", injectionResult);
93
- return { healed: false, explanation: "Prompt injection detected repair blocked" };
86
+ // Skip injection scan on empty/trivial stderr (prevents false positives on clean restarts)
87
+ const stderrContent = (parsed.errorMessage || "").trim() + (parsed.stackTrace || "").trim();
88
+ if (stderrContent.length < 20) {
89
+ console.log(chalk.gray(" 🛡️ Stderr too short for injection scan — skipping"));
90
+ } else {
91
+ const injectionResult = await detectInjection(parsed.errorMessage, parsed.stackTrace, { openaiClient });
92
+
93
+ if (logger) logger.info(EVENT_TYPES.HEAL_INJECTION_SCAN, `Injection scan: ${injectionResult.safe ? "clean" : "BLOCKED"}`, injectionResult);
94
+
95
+ if (!injectionResult.safe) {
96
+ console.log(chalk.red(" 🚨 BLOCKED: Potential prompt injection detected."));
97
+ if (logger) logger.critical(EVENT_TYPES.SECURITY_INJECTION_DETECTED, "Injection detected — repair blocked", injectionResult);
98
+ return { healed: false, explanation: "Prompt injection detected — repair blocked" };
99
+ }
100
+ console.log(chalk.green(" ✅ Clean — no injection detected."));
94
101
  }
95
- console.log(chalk.green(" ✅ Clean — no injection detected."));
96
102
 
97
103
  // 4b. Check if this is a human-required issue (expired keys, billing, etc.)
98
104
  if (notifier) {
@@ -128,6 +134,26 @@ async function heal({ stderr, cwd, sandbox, notifier, rateLimiter, backupManager
128
134
  // 5. Read the source file (if available) + get brain context
129
135
  const sourceCode = hasFile ? sandbox.readFile(parsed.filePath) : "";
130
136
 
137
+ // 5b. Get last known good version from backup (helps AI revert vs patch)
138
+ let backupSourceCode = "";
139
+ if (hasFile && backupManager) {
140
+ try {
141
+ const fs = require("fs");
142
+ const path = require("path");
143
+ const stableBackups = backupManager.getAll().filter(b => b.status === "stable" || b.status === "verified");
144
+ if (stableBackups.length > 0) {
145
+ const latest = stableBackups[stableBackups.length - 1];
146
+ const relPath = path.relative(cwd, parsed.filePath).replace(/[/\\]/g, "__");
147
+ const backupFile = path.join(cwd, ".wolverine", "backups", latest.id, relPath);
148
+ if (fs.existsSync(backupFile)) {
149
+ backupSourceCode = fs.readFileSync(backupFile, "utf-8");
150
+ if (backupSourceCode === sourceCode) backupSourceCode = ""; // Same — no useful diff
151
+ else console.log(chalk.gray(` 📋 Found last known good version (backup ${latest.id})`));
152
+ }
153
+ }
154
+ } catch { /* non-fatal */ }
155
+ }
156
+
131
157
  let brainContext = "";
132
158
  // Inject relevant skill context (claw-code: pre-enrich prompt with matched tools)
133
159
  if (skills) {
@@ -183,7 +209,7 @@ async function heal({ stderr, cwd, sandbox, notifier, rateLimiter, backupManager
183
209
  console.log(chalk.yellow(` 🧠 Fast path (${getModel("coding")})...`));
184
210
  try {
185
211
  const repair = await requestRepair({
186
- filePath: parsed.filePath, sourceCode,
212
+ filePath: parsed.filePath, sourceCode, backupSourceCode,
187
213
  errorMessage: parsed.errorMessage, stackTrace: parsed.stackTrace,
188
214
  });
189
215
  rateLimiter.record(errorSignature);
@@ -243,7 +269,7 @@ async function heal({ stderr, cwd, sandbox, notifier, rateLimiter, backupManager
243
269
  const agentResult = await agent.run({
244
270
  errorMessage: parsed.errorMessage, stackTrace: parsed.stackTrace,
245
271
  primaryFile: parsed.filePath, sourceCode,
246
- brainContext: fullContext,
272
+ brainContext: fullContext + (backupSourceCode ? `\n\nLAST KNOWN WORKING VERSION of ${parsed.filePath}:\n${backupSourceCode}\nIf the broken code added something that doesn't work, revert it rather than patching around it.` : ""),
247
273
  });
248
274
  rateLimiter.record(errorSignature, agentResult.totalTokens);
249
275
 
@@ -871,6 +871,7 @@ ${context ? "\nBrain:\n" + context : ""}`,
871
871
  backups: this.backupManager ? this.backupManager.getStats() : {},
872
872
  health: this.healthMonitor ? this.healthMonitor.getStats() : {},
873
873
  errorMonitor: this.errorMonitor ? this.errorMonitor.getStats() : {},
874
+ heal: this.runner ? this.runner._healStatus : null,
874
875
  }));
875
876
  }
876
877