{"record":{"id":"bcd4d22f40ff31e8","repo":"ruvnet/ruflo","slug":"aidefence-failed-to-load-error-message","errorCode":null,"errorMessage":"AIDefence failed to load: ${error.message}","messagePattern":"AIDefence failed to load: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"v3/@claude-flow/cli/src/mcp-tools/security-tools.ts","lineNumber":69,"sourceCode":"  }\n\n  const packageName = '@claude-flow/aidefence';\n\n  // First attempt - try to load via dynamic import (ESM)\n  try {\n    const aidefence = await import(packageName);\n    const instance = aidefence.createAIDefence({ enableLearning: true });\n    if (!instance) {\n      throw new Error('createAIDefence returned null');\n    }\n    aidefenceInstance = instance;\n    return instance;\n  } catch (e) {\n    // Package not found or failed to load\n    const error = e as Error;\n    if (!error.message?.includes('Cannot find package') && !error.message?.includes('ERR_MODULE_NOT_FOUND')) {\n      // Different error - might be a real issue\n      throw new Error(`AIDefence failed to load: ${error.message}`);\n    }\n  }\n\n  // Don't attempt install more than once per session\n  if (installAttempted) {\n    throw new Error('AIDefence package not available. Install with: npm install @claude-flow/aidefence');\n  }\n  installAttempted = true;\n\n  // Second attempt - auto-install and retry\n  console.error(`[claude-flow] ${packageName} not found, attempting auto-install...`);\n  const installed = await autoInstallPackage(packageName);\n\n  if (!installed) {\n    throw new Error('AIDefence package not available. Install with: npm install @claude-flow/aidefence');\n  }\n\n  // #1807 — auto-install lands the package somewhere Node's standard","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/ruvnet/ruflo/blob/fa13ee4ad60ac2090b1480656eb233521790d640/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts#L51-L87","documentation":"getAIDefence() dynamically imports the optional package @claude-flow/aidefence. If the import fails with an error that is NOT 'Cannot find package' / ERR_MODULE_NOT_FOUND, the loader concludes the package IS present but broken and rethrows wrapped as 'AIDefence failed to load: <original message>'. Causes live in the embedded message: the package's own dependencies missing, an ESM/CJS or Node-version mismatch, a corrupted install, or createAIDefence returning null.","triggerScenarios":"Calling security_tools that need AIDefence (security scan / has_pii / is_safe style tools) when @claude-flow/aidefence is installed but throws on import — e.g. its own 'Cannot find module <transitive dep>' (different message than the top-level resolution failure), an unsupported Node version, or a half-written node_modules from an interrupted install.","commonSituations":"Partial npm installs (killed mid-install); installing @claude-flow/aidefence at a version incompatible with the installed @claude-flow/security; native bindings inside aidefence built for a different Node ABI; running under a bundler that broke the dynamic import target.","solutions":["Read the text after 'AIDefence failed to load:' — it names the real cause (missing transitive dep, syntax error, ABI mismatch).","Reinstall cleanly: rm -rf node_modules/@claude-flow/aidefence && npm install @claude-flow/aidefence (or a full npm ci).","Align versions: install the aidefence version matching your @claude-flow/cli release instead of a floating latest.","Verify with node -e \"import('@claude-flow/aidefence').then(m => m.createAIDefence({enableLearning:true}))\" in the same working directory.","If it reproduces on a clean install, report it — the package itself is broken for your Node/platform."],"exampleFix":"# before\nnpm install @claude-flow/aidefence@next   # mismatched with CLI version -> broken import\n\n# after\nnpm install @claude-flow/aidefence@<version matching your @claude-flow/cli release>\nnode -e \"import('@claude-flow/aidefence').then(m => console.log(!!m.createAIDefence({enableLearning:true})))\"","handlingStrategy":"try-catch","validationCode":"// Probe once at startup so a broken package fails loudly before work begins:\nasync function probeAIDefence(): Promise<boolean> {\n  try {\n    const m = await import('@claude-flow/aidefence');\n    return typeof m.createAIDefence === 'function' && !!m.createAIDefence({ enableLearning: true });\n  } catch { return false; }\n}","typeGuard":null,"tryCatchPattern":"try {\n  return await scanForThreats(text); // AIDefence-backed tool\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('AIDefence failed to load:')) {\n    logger.error('security scanner unavailable', { cause: e.message });\n    return { degraded: true, reason: 'aidefence-broken-install' }; // fail closed & visible\n  }\n  throw e;\n}","preventionTips":["Pin @claude-flow/aidefence to the version matching your @claude-flow/cli release in package.json.","Add a CI smoke step that imports the package and calls createAIDefence({enableLearning:true}).","Use npm ci (not incremental installs) in deploy images to avoid half-installed module trees."],"tags":["security","aidefence","module-load","dependency","dynamic-import"],"backgroundTag":"dynamic-import-failed","analyzedSha":"fa13ee4ad60ac2090b1480656eb233521790d640","analyzedAt":"2026-08-18T21:34:22.708Z","contentChangedAt":"2026-08-18T21:34:22.708Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}