thuban 0.4.5 → 0.4.7

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 (31) hide show
  1. package/README.md +437 -420
  2. package/dist/README.md +437 -420
  3. package/dist/cli.js +1 -2
  4. package/dist/package.json +7 -4
  5. package/dist/packages/crucible/mutation-engine.js +1 -1
  6. package/dist/packages/crucible/pattern-learner.js +1 -1
  7. package/dist/packages/crucible/rule-loader.js +1 -1
  8. package/dist/packages/crucible/rules/code-scanner-core.json +72 -24
  9. package/dist/packages/crucible/seeding-engine.js +1 -1
  10. package/dist/packages/scanner/ai-confidence-scorer.js +1 -1
  11. package/dist/packages/scanner/code-scanner.js +1 -1
  12. package/dist/packages/scanner/codebase-passport.js +1 -1
  13. package/dist/packages/scanner/copy-paste-detector.js +1 -1
  14. package/dist/packages/scanner/dependency-graph.js +1 -1
  15. package/dist/packages/scanner/drift-detector.js +1 -1
  16. package/dist/packages/scanner/export-verifier.js +1 -1
  17. package/dist/packages/scanner/feedback-client.js +1 -0
  18. package/dist/packages/scanner/file-collector.js +1 -1
  19. package/dist/packages/scanner/ghost-code-detector.js +1 -1
  20. package/dist/packages/scanner/hallucination-detector.js +1 -1
  21. package/dist/packages/scanner/investor-report.js +1 -0
  22. package/dist/packages/scanner/license-manager.js +1 -1
  23. package/dist/packages/scanner/pre-commit-gate.js +1 -1
  24. package/dist/packages/scanner/python_ast_helper.py +426 -0
  25. package/dist/packages/scanner/read-file.js +1 -0
  26. package/dist/packages/scanner/slack-notifier.js +1 -0
  27. package/dist/packages/scanner/support-bot.js +1 -0
  28. package/dist/packages/scanner/support-knowledge.js +1 -0
  29. package/dist/packages/scanner/taint-tracker.js +1 -1
  30. package/dist/packages/scanner/tech-debt-analyzer.js +1 -1
  31. package/package.json +7 -4
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),crypto=require("crypto");class CopyPasteDriftDetector{constructor(t={}){this.rootPath=t.rootPath||process.cwd(),this.minLines=t.minLines||5,this.similarityThreshold=t.similarity||.7}scan(t){const e=[];for(const n of t){let t;try{if(fs.statSync(n).size>524288)continue;t=fs.readFileSync(n,"utf-8")}catch(t){continue}const s=path.relative(this.rootPath,n);if(this._isSkippable(s))continue;const i=this._extractFunctions(t,s);e.push(...i)}const n=this._findClusters(e),s=n.reduce((t,e)=>t+e.members.reduce((t,e)=>t+e.lineCount,0)-e.members[0].lineCount,0);return{clusters:n,totalClusters:n.length,totalDuplicateInstances:n.reduce((t,e)=>t+e.members.length,0),totalDuplicateLines:s,recommendation:n.length>0?`Extract ${n.length} shared utilities to eliminate ${s} duplicate lines.`:"No copy-paste drift detected."}}_extractFunctions(t,e){const n=t.split("\n"),s=[];for(let t=0;t<n.length;t++){const i=this._detectFunction(n[t]);if(!i)continue;const a=this._findFunctionEnd(n,t),r=n.slice(t,a+1).join("\n"),l=a-t+1;if(l<this.minLines)continue;const o=this._normalize(r),c=crypto.createHash("md5").update(o).digest("hex"),h=this._tokenize(o);s.push({file:e,name:i.name,line:t+1,lineCount:l,hash:c,tokens:h,normalized:o}),t=a}return s}_findClusters(t){const e=new Set,n=[];for(let s=0;s<t.length;s++){if(e.has(s))continue;const i=[t[s]];e.add(s);for(let n=s+1;n<t.length;n++){if(e.has(n))continue;if(t[s].hash===t[n].hash){i.push(t[n]),e.add(n);continue}const a=this._tokenSimilarity(t[s].tokens,t[n].tokens);a>=this.similarityThreshold&&(i.push({...t[n],similarity:Math.round(100*a)}),e.add(n))}if(i.length>=2){const t=this._findDiffs(i);n.push({pattern:i[0].name,members:i.map(t=>({file:t.file,name:t.name,line:t.line,lineCount:t.lineCount,similarity:t.similarity||100})),totalInstances:i.length,differences:t,severity:i.length>=4?"high":i.length>=3?"medium":"low",recommendation:`Extract to shared utility. ${i.length} functions → 1.`})}}return n.sort((t,e)=>e.totalInstances-t.totalInstances)}_normalize(t){const e=[],n=[/(?:const|let|var|function)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/(?:([a-zA-Z_][a-zA-Z0-9_]*)\s*:=|var\s+([a-zA-Z_][a-zA-Z0-9_]*)|\bfunc\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*))/g,/(?:let\s+(?:mut\s+)?([a-zA-Z_][a-zA-Z0-9_]*)|\bfn\s+([a-zA-Z_][a-zA-Z0-9_]*))/g,/(?:^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=(?!=)|\bdef\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*))/gm,/(?:^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=(?!=)|\bdef\s+([a-zA-Z_][a-zA-Z0-9_]*))/gm];let s;for(const i of n)for(;null!==(s=i.exec(t));){const t=s[1]||s[2]||s[3];t&&!e.includes(t)&&t.length>1&&e.push(t)}let i=t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/#.*$/gm,"").replace(/'[^']*'/g,"STR").replace(/"[^"]*"/g,"STR").replace(/`[^`]*`/g,"STR").replace(/\b\d+\.?\d*\b/g,"NUM");return e.forEach((t,e)=>{const n=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g");i=i.replace(n,`VAR_${e}`)}),i.replace(/\s+/g," ").trim()}_tokenize(t){return t.split(/[\s{}()\[\];,=+\-*/<>!&|?:.]+/).filter(t=>t.length>0)}_tokenSimilarity(t,e){if(0===t.length&&0===e.length)return 1;if(0===t.length||0===e.length)return 0;const n=new Set(t),s=new Set(e),i=[...n].filter(t=>s.has(t)).length,a=new Set([...t,...e]).size;return.7*(a>0?i/a:0)+Math.min(t.length,e.length)/Math.max(t.length,e.length)*.3}_findDiffs(t){if(t.length<2)return[];const e=[],n=t[0].normalized;for(let s=1;s<t.length;s++){const i=t[s].normalized;if(n!==i){const a=new Set(this._tokenize(n)),r=new Set(this._tokenize(i)),l=[...r].filter(t=>!a.has(t)),o=[...a].filter(t=>!r.has(t));(l.length>0||o.length>0)&&e.push({file:t[s].file,addedTokens:l.slice(0,5),removedTokens:o.slice(0,5)})}}return e}_detectFunction(t){const e=t.trim();let n=e.match(/^(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);return n?{name:n[1]}:(n=e.match(/^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?(?:function|\()/),n?{name:n[1]}:(n=e.match(/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),n?{name:n[1]}:(n=e.match(/^(?:private\s+|public\s+|internal\s+|protected\s+)?(?:suspend\s+)?fun\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),n?{name:n[1]}:(n=e.match(/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),n?{name:n[1]}:(n=e.match(/^(?:(?:public|private|protected|static)\s+)*function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),n?{name:n[1]}:(n=e.match(/^def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*)\s*[(\s]?/),n?{name:n[1]}:null))))))}_findFunctionEnd(t,e){const n=(t[e]||"").trim();if(/^def\s/.test(n)){let n=1;for(let s=e+1;s<t.length&&s<e+200;s++){const e=t[s].trim();if(/^(?:def|class|module|begin|case)\b/.test(e)&&n++,/^(?:if|unless|while|until|for)\b/.test(e)&&!/\bthen\b/.test(e)&&n++,/\bdo\s*(\|[^|]*\|)?\s*$/.test(e)&&n++,/^end\b/.test(e)&&n--,n<=0)return s}return Math.min(e+20,t.length-1)}let s=0,i=!1;for(let n=e;n<t.length&&n<e+200;n++){for(const e of t[n])"{"===e&&(s++,i=!0),"}"===e&&s--;if(i&&s<=0)return n}return Math.min(e+20,t.length-1)}_isSkippable(t){return[/\.test\./i,/\.spec\./i,/test[\/\\]/i,/node_modules/i,/\.min\./i,/\.d\.ts$/,/\.config\./i].some(e=>e.test(t))}}module.exports=CopyPasteDriftDetector;
1
+ const fs=require("fs"),path=require("path"),crypto=require("crypto");class CopyPasteDriftDetector{constructor(t={}){this.rootPath=t.rootPath||process.cwd(),this.minLines=t.minLines||5,this.similarityThreshold=t.similarity||.7}scan(t){const e=[];for(const n of t){let t;try{if(fs.statSync(n).size>524288)continue;t=fs.readFileSync(n,"utf-8").replace(/\r\n/g,"\n")}catch(t){continue}const s=path.relative(this.rootPath,n);if(this._isSkippable(s))continue;const i=this._extractFunctions(t,s);e.push(...i)}const n=this._findClusters(e),s=n.reduce((t,e)=>t+e.members.reduce((t,e)=>t+e.lineCount,0)-e.members[0].lineCount,0);return{clusters:n,totalClusters:n.length,totalDuplicateInstances:n.reduce((t,e)=>t+e.members.length,0),totalDuplicateLines:s,recommendation:n.length>0?`Extract ${n.length} shared utilities to eliminate ${s} duplicate lines.`:"No copy-paste drift detected."}}_extractFunctions(t,e){const n=t.split("\n"),s=[];for(let t=0;t<n.length;t++){const i=this._detectFunction(n[t]);if(!i)continue;const a=this._findFunctionEnd(n,t),r=n.slice(t,a+1).join("\n"),l=a-t+1;if(l<this.minLines)continue;const o=this._normalize(r),c=crypto.createHash("md5").update(o).digest("hex"),h=this._tokenize(o);s.push({file:e,name:i.name,line:t+1,lineCount:l,hash:c,tokens:h,normalized:o}),t=a}return s}_findClusters(t){const e=new Set,n=[];for(let s=0;s<t.length;s++){if(e.has(s))continue;const i=[t[s]];e.add(s);for(let n=s+1;n<t.length;n++){if(e.has(n))continue;if(t[s].hash===t[n].hash){i.push(t[n]),e.add(n);continue}const a=this._tokenSimilarity(t[s].tokens,t[n].tokens);a>=this.similarityThreshold&&(i.push({...t[n],similarity:Math.round(100*a)}),e.add(n))}if(i.length>=2){const t=this._findDiffs(i);n.push({pattern:i[0].name,members:i.map(t=>({file:t.file,name:t.name,line:t.line,lineCount:t.lineCount,similarity:t.similarity||100})),totalInstances:i.length,differences:t,severity:i.length>=4?"high":i.length>=3?"medium":"low",recommendation:`Extract to shared utility. ${i.length} functions → 1.`})}}return n.sort((t,e)=>e.totalInstances-t.totalInstances)}_normalize(t){const e=[],n=[/(?:const|let|var|function)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/(?:([a-zA-Z_][a-zA-Z0-9_]*)\s*:=|var\s+([a-zA-Z_][a-zA-Z0-9_]*)|\bfunc\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*))/g,/(?:let\s+(?:mut\s+)?([a-zA-Z_][a-zA-Z0-9_]*)|\bfn\s+([a-zA-Z_][a-zA-Z0-9_]*))/g,/(?:^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=(?!=)|\bdef\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*))/gm,/(?:^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=(?!=)|\bdef\s+([a-zA-Z_][a-zA-Z0-9_]*))/gm];let s;for(const i of n)for(;null!==(s=i.exec(t));){const t=s[1]||s[2]||s[3];t&&!e.includes(t)&&t.length>1&&e.push(t)}let i=t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/#.*$/gm,"").replace(/'[^']*'/g,"STR").replace(/"[^"]*"/g,"STR").replace(/`[^`]*`/g,"STR").replace(/\b\d+\.?\d*\b/g,"NUM");return e.forEach((t,e)=>{const n=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g");i=i.replace(n,`VAR_${e}`)}),i.replace(/\s+/g," ").trim()}_tokenize(t){return t.split(/[\s{}()\[\];,=+\-*/<>!&|?:.]+/).filter(t=>t.length>0)}_tokenSimilarity(t,e){if(0===t.length&&0===e.length)return 1;if(0===t.length||0===e.length)return 0;const n=new Set(t),s=new Set(e),i=[...n].filter(t=>s.has(t)).length,a=new Set([...t,...e]).size;return.7*(a>0?i/a:0)+Math.min(t.length,e.length)/Math.max(t.length,e.length)*.3}_findDiffs(t){if(t.length<2)return[];const e=[],n=t[0].normalized;for(let s=1;s<t.length;s++){const i=t[s].normalized;if(n!==i){const a=new Set(this._tokenize(n)),r=new Set(this._tokenize(i)),l=[...r].filter(t=>!a.has(t)),o=[...a].filter(t=>!r.has(t));(l.length>0||o.length>0)&&e.push({file:t[s].file,addedTokens:l.slice(0,5),removedTokens:o.slice(0,5)})}}return e}_detectFunction(t){const e=t.trim();let n=e.match(/^(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);return n?{name:n[1]}:(n=e.match(/^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?(?:function|\()/),n?{name:n[1]}:(n=e.match(/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),n?{name:n[1]}:(n=e.match(/^(?:private\s+|public\s+|internal\s+|protected\s+)?(?:suspend\s+)?fun\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),n?{name:n[1]}:(n=e.match(/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),n?{name:n[1]}:(n=e.match(/^(?:(?:public|private|protected|static)\s+)*function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),n?{name:n[1]}:(n=e.match(/^def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*)\s*[(\s]?/),n?{name:n[1]}:null))))))}_findFunctionEnd(t,e){const n=(t[e]||"").trim();if(/^def\s/.test(n)){let n=1;for(let s=e+1;s<t.length&&s<e+200;s++){const e=t[s].trim();if(/^(?:def|class|module|begin|case)\b/.test(e)&&n++,/^(?:if|unless|while|until|for)\b/.test(e)&&!/\bthen\b/.test(e)&&n++,/\bdo\s*(\|[^|]*\|)?\s*$/.test(e)&&n++,/^end\b/.test(e)&&n--,n<=0)return s}return Math.min(e+20,t.length-1)}let s=0,i=!1;for(let n=e;n<t.length&&n<e+200;n++){for(const e of t[n])"{"===e&&(s++,i=!0),"}"===e&&s--;if(i&&s<=0)return n}return Math.min(e+20,t.length-1)}_isSkippable(t){return[/\.test\./i,/\.spec\./i,/test[\/\\]/i,/node_modules/i,/\.min\./i,/\.d\.ts$/,/\.config\./i].some(e=>e.test(t))}}module.exports=CopyPasteDriftDetector;
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),EventEmitter=require("events");class DependencyGraph extends EventEmitter{constructor(e={}){super(),this.config={rootPath:e.rootPath||process.cwd(),ignorePatterns:e.ignorePatterns||["node_modules",".git","dist",".vite",".orion/snapshots"],extensions:e.extensions||[".js",".ts",".jsx",".tsx",".php",".rb"],...e},this.graph=new Map,this.resolveCache=new Map,this.stats={filesAnalyzed:0,totalImports:0,unresolvedImports:0,circularDependencies:[]}}get circularDeps(){return this.stats.circularDependencies}async build(){Date.now();this.graph.clear(),this.resolveCache.clear(),this.stats={filesAnalyzed:0,totalImports:0,unresolvedImports:0,circularDependencies:[]};const e=await this._discoverFiles(this.config.rootPath);for(const t of e)await this._analyzeFile(t);return this._buildReverseDependencies(),this._detectCircularDependencies(),Date.now(),this.getStats()}getDependencies(e){const t=this._normalizePath(e),s=this.graph.get(t);return s?s.imports:[]}getDependents(e){const t=this._normalizePath(e),s=this.graph.get(t);return s?s.importedBy:[]}getFullDependencyChain(e,t=new Set){const s=this._normalizePath(e);if(t.has(s))return[];t.add(s);const i=this.getDependencies(s),r=[...i];for(const e of i)e.resolved&&r.push(...this.getFullDependencyChain(e.resolved,t));return r}getImpactAnalysis(e){const t=this._normalizePath(e),s={file:t,relativePath:path.relative(this.config.rootPath,t),directDependents:[],indirectDependents:[],totalImpact:0,riskLevel:"low",affectedModules:new Set};s.directDependents=this.getDependents(t).map(e=>({file:e,relativePath:path.relative(this.config.rootPath,e)}));const i=new Set([t]),r=[...s.directDependents.map(e=>e.file)];for(;r.length>0;){const e=r.shift();if(i.has(e))continue;i.add(e);const t=this.getDependents(e);for(const o of t)i.has(o)||(s.indirectDependents.push({file:o,relativePath:path.relative(this.config.rootPath,o),via:path.relative(this.config.rootPath,e)}),r.push(o))}s.totalImpact=s.directDependents.length+s.indirectDependents.length,0===s.totalImpact?s.riskLevel="none":s.totalImpact<=3?s.riskLevel="low":s.totalImpact<=10?s.riskLevel="medium":s.totalImpact<=25?s.riskLevel="high":s.riskLevel="critical";for(const e of[...s.directDependents,...s.indirectDependents]){const t=e.relativePath.split(path.sep);t.length>0&&s.affectedModules.add(t[0])}return s.affectedModules=Array.from(s.affectedModules),s}getMostCriticalFiles(e=20){const t=[];for(const[e,s]of this.graph)t.push({file:e,relativePath:path.relative(this.config.rootPath,e),dependentCount:s.importedBy.length,dependencyCount:s.imports.length});return t.sort((e,t)=>t.dependentCount-e.dependentCount).slice(0,e)}getOrphanFiles(){const e=[];for(const[t,s]of this.graph)0===s.imports.length&&0===s.importedBy.length&&e.push({file:t,relativePath:path.relative(this.config.rootPath,t)});return e}getModuleSummary(){const e=new Map;for(const[t,s]of this.graph){const i=path.relative(this.config.rootPath,t),r=i.split(path.sep)[0];e.has(r)||e.set(r,{name:r,files:[],internalDeps:0,externalDeps:0,dependedOnBy:new Set});const o=e.get(r);o.files.push(i);for(const e of s.imports)e.resolved&&(path.relative(this.config.rootPath,e.resolved).split(path.sep)[0]===r?o.internalDeps++:o.externalDeps++);for(const e of s.importedBy){const t=path.relative(this.config.rootPath,e).split(path.sep)[0];t!==r&&o.dependedOnBy.add(t)}}const t=[];for(const[s,i]of e)t.push({name:s,fileCount:i.files.length,internalDeps:i.internalDeps,externalDeps:i.externalDeps,dependedOnByCount:i.dependedOnBy.size,dependedOnBy:Array.from(i.dependedOnBy)});return t.sort((e,t)=>t.fileCount-e.fileCount)}getStats(){return{...this.stats,totalFiles:this.graph.size,circularCount:this.stats.circularDependencies.length}}toJSON(){const e={generated:(new Date).toISOString(),rootPath:this.config.rootPath,stats:this.getStats(),files:{}};for(const[t,s]of this.graph){const i=path.relative(this.config.rootPath,t);e.files[i]={imports:s.imports.map(e=>({module:e.module,resolved:e.resolved?path.relative(this.config.rootPath,e.resolved):null,specifiers:e.specifiers})),importedBy:s.importedBy.map(e=>path.relative(this.config.rootPath,e))}}return e}async _discoverFiles(e,t=[],s=0){if(s>100)return t;try{const i=fs.readdirSync(e,{withFileTypes:!0});for(const r of i){const i=path.join(e,r.name);if(!this._shouldIgnore(r.name))if(r.isDirectory())await this._discoverFiles(i,t,s+1);else if(r.isFile()){const e=path.extname(r.name).toLowerCase();this.config.extensions.includes(e)&&t.push(i)}}}catch(e){}return t}_shouldIgnore(e){return this.config.ignorePatterns.some(t=>e===t||e.startsWith(t))}async _analyzeFile(e){try{const t=fs.readFileSync(e,"utf8"),s=this._extractImports(t,e);this.graph.set(e,{imports:s,importedBy:[]}),this.stats.filesAnalyzed++,this.stats.totalImports+=s.length,this.stats.unresolvedImports+=s.filter(e=>!e.resolved).length}catch(e){}}_extractImports(e,t){const s=[],i=path.dirname(t),r=/(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;let o;for(;null!==(o=r.exec(e));){const e=o[1]?o[1].split(",").map(e=>e.trim().split(":")[0].trim()).filter(Boolean):[o[2]],t=o[3];s.push({module:t,specifiers:e,resolved:this._resolveModule(t,i),type:"require"})}const n=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;null!==(o=n.exec(e));){const e=o[1];s.some(t=>t.module===e)||s.push({module:e,specifiers:[],resolved:this._resolveModule(e,i),type:"require"})}const a=/import\s+(?:(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))(?:\s*,\s*)?)+\s+from\s+['"]([^'"]+)['"]/g;for(;null!==(o=a.exec(e));){const e=[];o[1]&&e.push(...o[1].split(",").map(e=>e.trim().split(" as ")[0].trim()).filter(Boolean)),o[2]&&e.push(o[2]),o[3]&&e.push(o[3]);const t=o[4];s.push({module:t,specifiers:e,resolved:this._resolveModule(t,i),type:"import"})}return s}_resolveModule(e,t){const s=`${t}:${e}`;if(this.resolveCache.has(s))return this.resolveCache.get(s);let i=null;if(!e.startsWith(".")&&!e.startsWith("/"))return this.resolveCache.set(s,null),null;const r=path.resolve(t,e),o=["",".js",".ts",".jsx",".tsx",".php",".rb","/index.js","/index.ts"];for(const e of o){const t=r+e;if(fs.existsSync(t)&&fs.statSync(t).isFile()){i=t;break}}return this.resolveCache.set(s,i),i}_buildReverseDependencies(){for(const[e,t]of this.graph)for(const s of t.imports)if(s.resolved&&this.graph.has(s.resolved)){const t=this.graph.get(s.resolved);t.importedBy.includes(e)||t.importedBy.push(e)}}_detectCircularDependencies(){const e=new Set,t=new Set,s=(i,r=[])=>{if(t.has(i)){const e=r.indexOf(i),t=r.slice(e).map(e=>path.relative(this.config.rootPath,e));t.push(path.relative(this.config.rootPath,i));const s=t.sort().join(" -> ");return void(this.stats.circularDependencies.some(e=>e.sort().join(" -> ")===s)||this.stats.circularDependencies.push(t))}if(e.has(i))return;e.add(i),t.add(i);const o=this.graph.get(i);if(o)for(const e of o.imports)e.resolved&&s(e.resolved,[...r,i]);t.delete(i)};for(const e of this.graph.keys())s(e)}_normalizePath(e){return path.isAbsolute(e)?e:path.resolve(this.config.rootPath,e)}}module.exports=DependencyGraph;
1
+ const fs=require("fs"),path=require("path"),EventEmitter=require("events");class DependencyGraph extends EventEmitter{constructor(e={}){super(),this.config={rootPath:e.rootPath||process.cwd(),ignorePatterns:e.ignorePatterns||["node_modules",".git","dist",".vite",".orion/snapshots"],extensions:e.extensions||[".js",".ts",".jsx",".tsx",".php",".rb"],...e},this.graph=new Map,this.resolveCache=new Map,this.stats={filesAnalyzed:0,totalImports:0,unresolvedImports:0,circularDependencies:[]}}get circularDeps(){return this.stats.circularDependencies}async build(){Date.now();this.graph.clear(),this.resolveCache.clear(),this.stats={filesAnalyzed:0,totalImports:0,unresolvedImports:0,circularDependencies:[]};const e=await this._discoverFiles(this.config.rootPath);for(const t of e)await this._analyzeFile(t);return this._buildReverseDependencies(),this._detectCircularDependencies(),Date.now(),this.getStats()}getDependencies(e){const t=this._normalizePath(e),s=this.graph.get(t);return s?s.imports:[]}getDependents(e){const t=this._normalizePath(e),s=this.graph.get(t);return s?s.importedBy:[]}getFullDependencyChain(e,t=new Set){const s=this._normalizePath(e);if(t.has(s))return[];t.add(s);const i=this.getDependencies(s),r=[...i];for(const e of i)e.resolved&&r.push(...this.getFullDependencyChain(e.resolved,t));return r}getImpactAnalysis(e){const t=this._normalizePath(e),s={file:t,relativePath:path.relative(this.config.rootPath,t),directDependents:[],indirectDependents:[],totalImpact:0,riskLevel:"low",affectedModules:new Set};s.directDependents=this.getDependents(t).map(e=>({file:e,relativePath:path.relative(this.config.rootPath,e)}));const i=new Set([t]),r=[...s.directDependents.map(e=>e.file)];for(;r.length>0;){const e=r.shift();if(i.has(e))continue;i.add(e);const t=this.getDependents(e);for(const o of t)i.has(o)||(s.indirectDependents.push({file:o,relativePath:path.relative(this.config.rootPath,o),via:path.relative(this.config.rootPath,e)}),r.push(o))}s.totalImpact=s.directDependents.length+s.indirectDependents.length,0===s.totalImpact?s.riskLevel="none":s.totalImpact<=3?s.riskLevel="low":s.totalImpact<=10?s.riskLevel="medium":s.totalImpact<=25?s.riskLevel="high":s.riskLevel="critical";for(const e of[...s.directDependents,...s.indirectDependents]){const t=e.relativePath.split(path.sep);t.length>0&&s.affectedModules.add(t[0])}return s.affectedModules=Array.from(s.affectedModules),s}getMostCriticalFiles(e=20){const t=[];for(const[e,s]of this.graph)t.push({file:e,relativePath:path.relative(this.config.rootPath,e),dependentCount:s.importedBy.length,dependencyCount:s.imports.length});return t.sort((e,t)=>t.dependentCount-e.dependentCount).slice(0,e)}getOrphanFiles(){const e=[];for(const[t,s]of this.graph)0===s.imports.length&&0===s.importedBy.length&&e.push({file:t,relativePath:path.relative(this.config.rootPath,t)});return e}getModuleSummary(){const e=new Map;for(const[t,s]of this.graph){const i=path.relative(this.config.rootPath,t),r=i.split(path.sep)[0];e.has(r)||e.set(r,{name:r,files:[],internalDeps:0,externalDeps:0,dependedOnBy:new Set});const o=e.get(r);o.files.push(i);for(const e of s.imports)e.resolved&&(path.relative(this.config.rootPath,e.resolved).split(path.sep)[0]===r?o.internalDeps++:o.externalDeps++);for(const e of s.importedBy){const t=path.relative(this.config.rootPath,e).split(path.sep)[0];t!==r&&o.dependedOnBy.add(t)}}const t=[];for(const[s,i]of e)t.push({name:s,fileCount:i.files.length,internalDeps:i.internalDeps,externalDeps:i.externalDeps,dependedOnByCount:i.dependedOnBy.size,dependedOnBy:Array.from(i.dependedOnBy)});return t.sort((e,t)=>t.fileCount-e.fileCount)}getStats(){return{...this.stats,totalFiles:this.graph.size,circularCount:this.stats.circularDependencies.length}}toJSON(){const e={generated:(new Date).toISOString(),rootPath:this.config.rootPath,stats:this.getStats(),files:{}};for(const[t,s]of this.graph){const i=path.relative(this.config.rootPath,t);e.files[i]={imports:s.imports.map(e=>({module:e.module,resolved:e.resolved?path.relative(this.config.rootPath,e.resolved):null,specifiers:e.specifiers})),importedBy:s.importedBy.map(e=>path.relative(this.config.rootPath,e))}}return e}async _discoverFiles(e,t=[],s=0){if(s>100)return t;try{const i=fs.readdirSync(e,{withFileTypes:!0});for(const r of i){const i=path.join(e,r.name);if(!this._shouldIgnore(r.name))if(r.isDirectory())await this._discoverFiles(i,t,s+1);else if(r.isFile()){const e=path.extname(r.name).toLowerCase();this.config.extensions.includes(e)&&t.push(i)}}}catch(e){}return t}_shouldIgnore(e){return this.config.ignorePatterns.some(t=>e===t||e.startsWith(t))}async _analyzeFile(e){try{const t=fs.readFileSync(e,"utf8"),s=this._extractImports(t,e);this.graph.set(e,{imports:s,importedBy:[]}),this.stats.filesAnalyzed++,this.stats.totalImports+=s.length,this.stats.unresolvedImports+=s.filter(e=>!e.resolved).length}catch(e){}}_extractImports(e,t){const s=[],i=path.dirname(t),r=/(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;let o;for(;null!==(o=r.exec(e));){const e=o[1]?o[1].split(",").map(e=>e.trim().split(":")[0].trim()).filter(Boolean):[o[2]],t=o[3];s.push({module:t,specifiers:e,resolved:this._resolveModule(t,i),type:"require"})}const n=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;null!==(o=n.exec(e));){const e=o[1];s.some(t=>t.module===e)||s.push({module:e,specifiers:[],resolved:this._resolveModule(e,i),type:"require"})}const a=/import\s+(?:(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))(?:\s*,\s*)?)+\s+from\s+['"]([^'"]+)['"]/g;for(;null!==(o=a.exec(e));){const e=[];o[1]&&e.push(...o[1].split(",").map(e=>e.trim().split(" as ")[0].trim()).filter(Boolean)),o[2]&&e.push(o[2]),o[3]&&e.push(o[3]);const t=o[4];s.push({module:t,specifiers:e,resolved:this._resolveModule(t,i),type:"import"})}return s}_resolveModule(e,t){const s=`${t}:${e}`;if(this.resolveCache.has(s))return this.resolveCache.get(s);let i=null;if(!e.startsWith(".")&&!path.isAbsolute(e))return this.resolveCache.set(s,null),null;const r=path.resolve(t,e),o=["",".js",".ts",".jsx",".tsx",".php",".rb",path.sep+"index.js",path.sep+"index.ts"];for(const e of o){const t=r+e;if(fs.existsSync(t)&&fs.statSync(t).isFile()){i=t;break}}return this.resolveCache.set(s,i),i}_buildReverseDependencies(){for(const[e,t]of this.graph)for(const s of t.imports)if(s.resolved&&this.graph.has(s.resolved)){const t=this.graph.get(s.resolved);t.importedBy.includes(e)||t.importedBy.push(e)}}_detectCircularDependencies(){const e=new Set,t=new Set,s=(i,r=[])=>{if(t.has(i)){const e=r.indexOf(i),t=r.slice(e).map(e=>path.relative(this.config.rootPath,e));t.push(path.relative(this.config.rootPath,i));const s=t.sort().join(" -> ");return void(this.stats.circularDependencies.some(e=>e.sort().join(" -> ")===s)||this.stats.circularDependencies.push(t))}if(e.has(i))return;e.add(i),t.add(i);const o=this.graph.get(i);if(o)for(const e of o.imports)e.resolved&&s(e.resolved,[...r,i]);t.delete(i)};for(const e of this.graph.keys())s(e)}_normalizePath(e){return path.isAbsolute(e)?e:path.resolve(this.config.rootPath,e)}}module.exports=DependencyGraph;
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),EventEmitter=require("events");class DriftDetector extends EventEmitter{constructor(t={}){super(),this.config={rootPath:t.rootPath||process.cwd(),widgetPattern:t.widgetPattern||/\/\*\*[\s\S]*?@(purpose|module|layer|imports-from|exports-to|depends-on|critical-for)[\s\S]*?\*\//,ignorePatterns:t.ignorePatterns||["node_modules/**",".git/**","dist/**",".orion/snapshots/**"],...t},this.analysisCache=new Map}async detectAll(){const t=Date.now(),e={filesAnalyzed:0,filesWithWidgets:0,filesWithoutWidgets:0,issues:[],moduleMap:{},duration:0};try{const s=await this._discoverFiles(this.config.rootPath);for(const t of s){const s=await this.analyzeFile(t);e.filesAnalyzed++,s.hasWidget?e.filesWithWidgets++:(e.filesWithoutWidgets++,e.issues.push({file:t,category:"drift",severity:"info",id:"DRIFT001",name:"Missing Widget",message:"File has no widget declaration - add @purpose, @module, @layer etc."})),e.issues.push(...s.issues),s.module&&(e.moduleMap[s.module]||(e.moduleMap[s.module]=[]),e.moduleMap[s.module].push(t))}return e.issues.push(...this._analyzeCrossFile(e.moduleMap)),e.duration=Date.now()-t,e}catch(t){return console.error("[DRIFT-DETECTOR] Detection failed"),e.error="Detection failed",e}}async analyzeFile(t){const e={file:t,hasWidget:!1,widget:null,actualExports:[],actualImports:[],module:null,issues:[]};try{const s=fs.readFileSync(t,"utf8");return e.widget=this._parseWidget(s),e.hasWidget=!!e.widget,e.actualExports=this._extractExports(s),e.actualImports=this._extractImports(s),e.widget&&(e.module=e.widget.module,e.issues.push(...this._compareWidgetToCode(t,e.widget,{exports:e.actualExports,imports:e.actualImports}))),e.drifts=e.issues,this.analysisCache.set(t,e),e}catch(s){const o="ENOENT"===s.code?"File not found":"EACCES"===s.code?"Permission denied":"Analysis error";return e.issues.push({file:t,category:"drift",severity:"error",id:"DRIFT000",message:`Failed to analyze file: ${o}`}),e.drifts=e.issues,e}}async checkFileDrift(t){const e=await this.analyzeFile(t);return{hasDrift:e.issues.length>0,issues:e.issues,widget:e.widget}}async suggestWidget(t){try{const e=fs.readFileSync(t,"utf8"),s=this._extractExports(e),o=this._extractImports(e),i=path.relative(this.config.rootPath,t),r=i.split(path.sep)[0];let n="application";return i.includes("routes")||i.includes("api")?n="presentation":i.includes("core")||i.includes("engine")?n="infrastructure":(i.includes("model")||i.includes("domain"))&&(n="domain"),{purpose:s.length>0?`Provides ${s.join(", ")}`:"Unknown purpose - needs description",module:r,layer:n,importsFrom:o.map(t=>`${t.module} - ${t.specifiers.join(", ")}`),exportsTo:"To be determined",dataFlow:"To be documented",sideEffects:e.includes("fs.")?"File system operations":"None documented",criticalFor:"To be documented"}}catch(t){return{error:t.message}}}async _discoverFiles(t,e=[],s=0){if(s>100)return e;try{const o=fs.readdirSync(t,{withFileTypes:!0});for(const i of o){const o=path.join(t,i.name),r=path.relative(this.config.rootPath,o);this._shouldIgnore(r)||(i.isDirectory()?await this._discoverFiles(o,e,s+1):i.isFile()&&i.name.endsWith(".js")&&e.push(o))}}catch(t){}return e}_shouldIgnore(t){const e=t.replace(/\\/g,"/"),s=["node_modules",".git","dist",".vite"];for(const t of s)if(e.includes("/"+t+"/")||e.startsWith(t+"/")||e===t||e.endsWith("/"+t))return!0;for(const t of this.config.ignorePatterns){const s=t.replace(/\\/g,"/"),o=s.split("/")[0].replace(/\*/g,"");if(o&&(e===o||e.startsWith(o+"/")))return!0;let i=s.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");if(new RegExp("^"+i).test(e))return!0}return!1}_parseWidget(t){const e=t.match(/\/\*\*[\s\S]*?\*\//);if(e){const t=e[0],s=this._extractWidgetFields(t,e=>{const s=t.match(new RegExp(`@${e}\\s+(.+?)(?=\\n\\s*\\*\\s*@|\\n\\s*\\*\\/|$)`,"s"));return s?s[1].trim().replace(/\n\s*\*\s*/g," ").trim():null});if(s)return s}const s=t.match(/"{3}[\s\S]*?@(?:purpose|module|layer)[\s\S]*?"{3}|'{3}[\s\S]*?@(?:purpose|module|layer)[\s\S]*?'{3}/);if(s){const t=s[0],e=this._extractWidgetFields(t,e=>{const s=t.match(new RegExp(`@${e}\\s+(.+?)(?=\\n\\s*@|$)`,"s"));return s?s[1].trim():null});if(e)return e}const o=t.match(/(?:^|\n)((?:\s*#[^\n]*\n)+)/);if(o){const t=o[0];if(/@(?:purpose|module|layer)/.test(t)){const e=this._extractWidgetFields(t,e=>{const s=t.match(new RegExp(`@${e}\\s+(.+?)(?=\\n\\s*#\\s*@|\\n[^#]|$)`));return s?s[1].trim():null});if(e)return e}}const i=t.match(/(?:^|\n)((?:\s*\/\/[^\n]*\n)+)/);if(i){const t=i[0];if(/@(?:purpose|module|layer)/.test(t)){const e=this._extractWidgetFields(t,e=>{const s=t.match(new RegExp(`@${e}\\s+(.+?)(?=\\n\\s*//\\s*@|\\n[^/]|$)`));return s?s[1].trim():null});if(e)return e}}return null}_extractWidgetFields(t,e){const s=["purpose","module","layer","imports-from","exports-to","data-flow","side-effects","depends-on-env","critical-for","known-issues","last-audit","last-modified"],o={};for(const t of s){const s=e(t);s&&(o[t.replace(/-/g,"_")]=s)}return Object.keys(o).length>0?o:null}_extractExports(t){const e=[],s=t.search(/module\.exports\s*=\s*\{/);if(s>=0){const o=t.indexOf("{",s);if(o>=0){let s=0,i=t.length;for(let e=o;e<t.length;e++)if("{"===t[e]&&s++,"}"===t[e]&&(s--,0===s)){i=e;break}const r=t.substring(o+1,i);let n=0,c="";for(const t of r)if("{"!==t&&"["!==t&&"("!==t||n++,"}"!==t&&"]"!==t&&")"!==t||n--,0!==n||","!==t&&"\n"!==t)c+=t;else{const t=c.trim().match(/^(\w+)/);t&&e.push(t[1]),c=""}if(c.trim()){const t=c.trim().match(/^(\w+)/);t&&e.push(t[1])}}}const o=t.match(/module\.exports\s*=\s*(class\s+)?(\w+)/);o&&o[2]&&e.push(o[2]);const i=t.match(/exports\.(\w+)\s*=/g)||[];for(const t of i){const s=t.match(/exports\.(\w+)/);s&&e.push(s[1])}const r=t.match(/^(?:def|class)\s+([a-zA-Z_]\w*)/gm)||[];for(const t of r){const s=t.match(/^(?:def|class)\s+([a-zA-Z_]\w*)/);s&&!s[1].startsWith("_")&&e.push(s[1])}const n=t.match(/^func\s+([A-Z][a-zA-Z0-9]*)/gm)||[];for(const t of n){const s=t.match(/^func\s+([A-Z][a-zA-Z0-9]*)/);s&&e.push(s[1])}const c=t.match(/(?:public\s+function|class)\s+([a-zA-Z_]\w*)/g)||[];for(const t of c){const s=t.match(/(?:public\s+function|class)\s+([a-zA-Z_]\w*)/);s&&e.push(s[1])}const a=t.match(/^export\s+(?:(?:async\s+)?function|class|const|let|var)\s+([a-zA-Z_$]\w*)/gm)||[];for(const t of a){const s=t.match(/^export\s+(?:(?:async\s+)?function|class|const|let|var)\s+([a-zA-Z_$]\w*)/);s&&e.push(s[1])}const l=t.match(/^export\s*\{([^}]+)\}/gm)||[];for(const t of l){const s=t.match(/^export\s*\{([^}]+)\}/);if(s){const t=s[1].split(",").map(t=>{const e=t.trim().split(/\s+as\s+/);return(e[1]||e[0]).trim()}).filter(Boolean);e.push(...t)}}/^export\s+default\b/m.test(t)&&e.push("default");const d=t.match(/^pub(?:\([^)]*\))?\s+(?:(?:async\s+)?fn|struct|enum|type|trait)\s+([a-zA-Z_]\w*)/gm)||[];for(const t of d){const s=t.match(/(?:fn|struct|enum|type|trait)\s+([a-zA-Z_]\w*)/);s&&e.push(s[1])}const u=t.match(/^(?:\s*)def\s+(?:self\.)?([a-zA-Z_]\w*[?!]?)/gm)||[];for(const t of u){const s=t.match(/def\s+(?:self\.)?([a-zA-Z_]\w*[?!]?)/);s&&!s[1].startsWith("_")&&e.push(s[1])}return[...new Set(e)]}_extractImports(t){const e=[],s=t.matchAll(/(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))\s*=\s*require\(['"]([^'"]+)['"]\)/g);for(const t of s){const s=t[1]?t[1].split(",").map(t=>t.trim().split(":")[0].trim()):[t[2]];e.push({module:t[3],specifiers:s.filter(Boolean)})}const o=t.matchAll(/^(?:import\s+(\S+)|from\s+(\S+)\s+import)/gm);for(const t of o)e.push({module:t[1]||t[2],specifiers:[]});const i=t.matchAll(/"([^"]+)"/g);for(const t of i)!t[1].includes("/")&&t[1].includes(" ")||e.push({module:t[1],specifiers:[]});return e}_compareWidgetToCode(t,e,s){const o=[];if(e.exports_to){const i=e.exports_to.split(",").map(t=>t.trim().split(" ")[0]).filter(t=>!s.exports.some(e=>e.toLowerCase().includes(t.toLowerCase())));i.length>0&&o.push({file:t,category:"drift",severity:"warning",id:"DRIFT002",name:"Missing Declared Export",message:`Widget declares exports not found in code: ${i.join(", ")}`})}if(e.imports_from){const i=e.imports_from.split(",").map(t=>t.trim().split(" ")[0]),r=s.imports.map(t=>t.module),n=i.filter(t=>!r.some(e=>e.includes(t)||t.includes(e.split("/").pop())));n.length>0&&o.push({file:t,category:"drift",severity:"warning",id:"DRIFT003",name:"Missing Declared Import",message:`Widget declares imports not found in code: ${n.join(", ")}`})}return!/fs\.(write|append|unlink|mkdir|rmdir)/i.test(fs.readFileSync(t,"utf8"))||e.side_effects&&"None"!==e.side_effects||o.push({file:t,category:"drift",severity:"warning",id:"DRIFT004",name:"Undeclared Side Effects",message:"File has file system operations but widget declares no side effects"}),o}_analyzeCrossFile(t){const e=[];for(const[s,o]of Object.entries(t))1===o.length&&e.push({file:o[0],category:"drift",severity:"info",id:"DRIFT005",name:"Orphaned Module",message:`Module "${s}" only has one file - verify module organization`});return e}}module.exports=DriftDetector;
1
+ const fs=require("fs"),path=require("path"),EventEmitter=require("events");class DriftDetector extends EventEmitter{constructor(e={}){super(),this.config={rootPath:e.rootPath||process.cwd(),widgetPattern:e.widgetPattern||/\/\*\*[\s\S]*?@(purpose|module|layer|imports-from|exports-to|depends-on|critical-for)[\s\S]*?\*\//,ignorePatterns:e.ignorePatterns||["node_modules/**",".git/**","dist/**",".orion/snapshots/**"],...e},this.analysisCache=new Map}async detectAll(){const e=Date.now(),t={filesAnalyzed:0,filesWithWidgets:0,filesWithoutWidgets:0,issues:[],moduleMap:{},duration:0};try{const s=await this._discoverFiles(this.config.rootPath);for(const e of s){const s=await this.analyzeFile(e);t.filesAnalyzed++,s.hasWidget?t.filesWithWidgets++:(t.filesWithoutWidgets++,t.issues.push({file:e,category:"drift",severity:"info",id:"DRIFT001",name:"Missing Widget",message:"File has no widget declaration - add @purpose, @module, @layer etc."})),t.issues.push(...s.issues),s.module&&(t.moduleMap[s.module]||(t.moduleMap[s.module]=[]),t.moduleMap[s.module].push(e))}return t.issues.push(...this._analyzeCrossFile(t.moduleMap)),t.duration=Date.now()-e,t}catch(e){return console.error("[DRIFT-DETECTOR] Detection failed"),t.error="Detection failed",t}}async analyzeFile(e){const t={file:e,hasWidget:!1,widget:null,actualExports:[],actualImports:[],module:null,issues:[]};try{const s=fs.readFileSync(e,"utf8").replace(/\r\n/g,"\n");return t.widget=this._parseWidget(s),t.hasWidget=!!t.widget,t.actualExports=this._extractExports(s),t.actualImports=this._extractImports(s),t.widget&&(t.module=t.widget.module,t.issues.push(...this._compareWidgetToCode(e,t.widget,{exports:t.actualExports,imports:t.actualImports}))),t.drifts=t.issues,this.analysisCache.set(e,t),t}catch(s){const o="ENOENT"===s.code?"File not found":"EACCES"===s.code?"Permission denied":"Analysis error";return t.issues.push({file:e,category:"drift",severity:"error",id:"DRIFT000",message:`Failed to analyze file: ${o}`}),t.drifts=t.issues,t}}async checkFileDrift(e){const t=await this.analyzeFile(e);return{hasDrift:t.issues.length>0,issues:t.issues,widget:t.widget}}async suggestWidget(e){try{const t=fs.readFileSync(e,"utf8").replace(/\r\n/g,"\n"),s=this._extractExports(t),o=this._extractImports(t),r=path.relative(this.config.rootPath,e),i=r.split(path.sep)[0];let n="application";return r.includes("routes")||r.includes("api")?n="presentation":r.includes("core")||r.includes("engine")?n="infrastructure":(r.includes("model")||r.includes("domain"))&&(n="domain"),{purpose:s.length>0?`Provides ${s.join(", ")}`:"Unknown purpose - needs description",module:i,layer:n,importsFrom:o.map(e=>`${e.module} - ${e.specifiers.join(", ")}`),exportsTo:"To be determined",dataFlow:"To be documented",sideEffects:t.includes("fs.")?"File system operations":"None documented",criticalFor:"To be documented"}}catch(e){return{error:e.message}}}async _discoverFiles(e,t=[],s=0){if(s>100)return t;try{const o=fs.readdirSync(e,{withFileTypes:!0});for(const r of o){const o=path.join(e,r.name),i=path.relative(this.config.rootPath,o);this._shouldIgnore(i)||(r.isDirectory()?await this._discoverFiles(o,t,s+1):r.isFile()&&r.name.endsWith(".js")&&t.push(o))}}catch(e){}return t}_shouldIgnore(e){const t=e.replace(/\\/g,"/"),s=["node_modules",".git","dist",".vite"];for(const e of s)if(t.includes("/"+e+"/")||t.startsWith(e+"/")||t===e||t.endsWith("/"+e))return!0;for(const e of this.config.ignorePatterns){const s=e.replace(/\\/g,"/"),o=s.split("/")[0].replace(/\*/g,"");if(o&&(t===o||t.startsWith(o+"/")))return!0;let r=s.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");if(new RegExp("^"+r).test(t))return!0}return!1}_parseWidget(e){const t=e.match(/\/\*\*[\s\S]*?\*\//);if(t){const e=t[0],s=this._extractWidgetFields(e,t=>{const s=e.match(new RegExp(`@${t}\\s+(.+?)(?=\\r?\\n\\s*\\*\\s*@|\\r?\\n\\s*\\*\\/|$)`,"s"));return s?s[1].trim().replace(/\n\s*\*\s*/g," ").trim():null});if(s)return s}const s=e.match(/"{3}[\s\S]*?@(?:purpose|module|layer)[\s\S]*?"{3}|'{3}[\s\S]*?@(?:purpose|module|layer)[\s\S]*?'{3}/);if(s){const e=s[0],t=this._extractWidgetFields(e,t=>{const s=e.match(new RegExp(`@${t}\\s+(.+?)(?=\\r?\\n\\s*@|$)`,"s"));return s?s[1].trim():null});if(t)return t}const o=e.match(/(?:^|\r?\n)((?:\s*#[^\r\n]*\r?\n)+)/);if(o){const e=o[0];if(/@(?:purpose|module|layer)/.test(e)){const t=this._extractWidgetFields(e,t=>{const s=e.match(new RegExp(`@${t}\\s+(.+?)(?=\\r?\\n\\s*#\\s*@|\\r?\\n[^#]|$)`));return s?s[1].trim():null});if(t)return t}}const r=e.match(/(?:^|\r?\n)((?:\s*\/\/[^\r\n]*\r?\n)+)/);if(r){const e=r[0];if(/@(?:purpose|module|layer)/.test(e)){const t=this._extractWidgetFields(e,t=>{const s=e.match(new RegExp(`@${t}\\s+(.+?)(?=\\r?\\n\\s*//\\s*@|\\r?\\n[^/]|$)`));return s?s[1].trim():null});if(t)return t}}return null}_extractWidgetFields(e,t){const s=["purpose","module","layer","imports-from","exports-to","data-flow","side-effects","depends-on-env","critical-for","known-issues","last-audit","last-modified"],o={};for(const e of s){const s=t(e);s&&(o[e.replace(/-/g,"_")]=s)}return Object.keys(o).length>0?o:null}_extractExports(e){const t=[],s=e.search(/module\.exports\s*=\s*\{/);if(s>=0){const o=e.indexOf("{",s);if(o>=0){let s=0,r=e.length;for(let t=o;t<e.length;t++)if("{"===e[t]&&s++,"}"===e[t]&&(s--,0===s)){r=t;break}const i=e.substring(o+1,r);let n=0,c="";for(const e of i)if("{"!==e&&"["!==e&&"("!==e||n++,"}"!==e&&"]"!==e&&")"!==e||n--,0!==n||","!==e&&"\n"!==e)c+=e;else{const e=c.trim().match(/^(\w+)/);e&&t.push(e[1]),c=""}if(c.trim()){const e=c.trim().match(/^(\w+)/);e&&t.push(e[1])}}}const o=e.match(/module\.exports\s*=\s*(class\s+)?(\w+)/);o&&o[2]&&t.push(o[2]);const r=e.match(/exports\.(\w+)\s*=/g)||[];for(const e of r){const s=e.match(/exports\.(\w+)/);s&&t.push(s[1])}const i=e.match(/^(?:def|class)\s+([a-zA-Z_]\w*)/gm)||[];for(const e of i){const s=e.match(/^(?:def|class)\s+([a-zA-Z_]\w*)/);s&&!s[1].startsWith("_")&&t.push(s[1])}const n=e.match(/^func\s+([A-Z][a-zA-Z0-9]*)/gm)||[];for(const e of n){const s=e.match(/^func\s+([A-Z][a-zA-Z0-9]*)/);s&&t.push(s[1])}const c=e.match(/(?:public\s+function|class)\s+([a-zA-Z_]\w*)/g)||[];for(const e of c){const s=e.match(/(?:public\s+function|class)\s+([a-zA-Z_]\w*)/);s&&t.push(s[1])}const a=e.match(/^export\s+(?:(?:async\s+)?function|class|const|let|var)\s+([a-zA-Z_$]\w*)/gm)||[];for(const e of a){const s=e.match(/^export\s+(?:(?:async\s+)?function|class|const|let|var)\s+([a-zA-Z_$]\w*)/);s&&t.push(s[1])}const l=e.match(/^export\s*\{([^}]+)\}/gm)||[];for(const e of l){const s=e.match(/^export\s*\{([^}]+)\}/);if(s){const e=s[1].split(",").map(e=>{const t=e.trim().split(/\s+as\s+/);return(t[1]||t[0]).trim()}).filter(Boolean);t.push(...e)}}/^export\s+default\b/m.test(e)&&t.push("default");const d=e.match(/^pub(?:\([^)]*\))?\s+(?:(?:async\s+)?fn|struct|enum|type|trait)\s+([a-zA-Z_]\w*)/gm)||[];for(const e of d){const s=e.match(/(?:fn|struct|enum|type|trait)\s+([a-zA-Z_]\w*)/);s&&t.push(s[1])}const u=e.match(/^(?:\s*)def\s+(?:self\.)?([a-zA-Z_]\w*[?!]?)/gm)||[];for(const e of u){const s=e.match(/def\s+(?:self\.)?([a-zA-Z_]\w*[?!]?)/);s&&!s[1].startsWith("_")&&t.push(s[1])}return[...new Set(t)]}_extractImports(e){const t=[],s=e.matchAll(/(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))\s*=\s*require\(['"]([^'"]+)['"]\)/g);for(const e of s){const s=e[1]?e[1].split(",").map(e=>e.trim().split(":")[0].trim()):[e[2]];t.push({module:e[3],specifiers:s.filter(Boolean)})}const o=e.matchAll(/^(?:import\s+(\S+)|from\s+(\S+)\s+import)/gm);for(const e of o)t.push({module:e[1]||e[2],specifiers:[]});const r=e.matchAll(/"([^"]+)"/g);for(const e of r)!e[1].includes("/")&&e[1].includes(" ")||t.push({module:e[1],specifiers:[]});return t}_compareWidgetToCode(e,t,s){const o=[];if(t.exports_to){const r=t.exports_to.split(",").map(e=>e.trim().split(" ")[0]).filter(e=>!s.exports.some(t=>t.toLowerCase().includes(e.toLowerCase())));r.length>0&&o.push({file:e,category:"drift",severity:"warning",id:"DRIFT002",name:"Missing Declared Export",message:`Widget declares exports not found in code: ${r.join(", ")}`})}if(t.imports_from){const r=t.imports_from.split(",").map(e=>e.trim().split(" ")[0]),i=s.imports.map(e=>e.module),n=r.filter(e=>!i.some(t=>t.includes(e)||e.includes(t.split("/").pop())));n.length>0&&o.push({file:e,category:"drift",severity:"warning",id:"DRIFT003",name:"Missing Declared Import",message:`Widget declares imports not found in code: ${n.join(", ")}`})}return!/fs\.(write|append|unlink|mkdir|rmdir)/i.test(fs.readFileSync(e,"utf8").replace(/\r\n/g,"\n"))||t.side_effects&&"None"!==t.side_effects||o.push({file:e,category:"drift",severity:"warning",id:"DRIFT004",name:"Undeclared Side Effects",message:"File has file system operations but widget declares no side effects"}),o}_analyzeCrossFile(e){const t=[];for(const[s,o]of Object.entries(e))1===o.length&&t.push({file:o[0],category:"drift",severity:"info",id:"DRIFT005",name:"Orphaned Module",message:`Module "${s}" only has one file - verify module organization`});return t}}module.exports=DriftDetector;
@@ -1 +1 @@
1
- "use strict";const fs=require("fs"),path=require("path"),nodeModule=require("module"),parser=require("@babel/parser"),{_internal:_internal}=require("./ast-analyzer"),{walk:walk}=_internal,BABEL_PLUGINS=["estree","typescript","jsx","classProperties","decorators-legacy"];function parseProgram(e){return parser.parse(e,{sourceType:"unambiguous",plugins:BABEL_PLUGINS,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowAwaitOutsideFunction:!0}).program}function extractNamedImports(e){const t=[];let r;try{r=parseProgram(e)}catch(e){return t}for(const e of r.body)if("ImportDeclaration"===e.type&&e.source){const r=e.source.value;for(const n of e.specifiers||[])if("ImportSpecifier"===n.type){const i=n.imported.name||n.imported.value;t.push({imported:i,local:n.local.name,source:r,line:e.loc?e.loc.start.line:0,kind:"import"})}}return walk(r,e=>{if("VariableDeclarator"===e.type&&e.init&&"CallExpression"===e.init.type&&"Identifier"===e.init.callee.type&&"require"===e.init.callee.name&&e.init.arguments[0]&&("Literal"===e.init.arguments[0].type||"StringLiteral"===e.init.arguments[0].type)&&"ObjectPattern"===e.id.type){const r=e.init.arguments[0].value,n=e.loc?e.loc.start.line:0;for(const i of e.id.properties)if(("RestElement"!==i.type&&("ObjectProperty"===i.type!=0||"Property"===i.type)||"RestElement"!==i.type)&&i.key&&i.value){const e=void 0!==i.key.name?i.key.name:i.key.value,o="Identifier"===i.value.type?i.value.name:e;t.push({imported:e,local:o,source:r,line:n,kind:"require"})}}}),t}const builtinModuleCache=new Map;function getBuiltinExports(e){if(builtinModuleCache.has(e))return builtinModuleCache.get(e);let t;try{const r=require(e);t={names:new Set(Object.keys(r)),uncertain:!1}}catch(e){t={names:null,uncertain:!0}}return builtinModuleCache.set(e,t),t}function isBuiltinSpecifier(e){const t=e.startsWith("node:")?e.slice(5):e;return nodeModule.builtinModules.includes(t)||nodeModule.builtinModules.includes(e)}function collectObjectKeys(e,t,r){for(const n of e.properties||[]){if("SpreadElement"===n.type||"SpreadProperty"===n.type||"ExperimentalSpreadProperty"===n.type){r.value=!0;continue}if(n.computed){r.value=!0;continue}const e=n.key;e&&("Identifier"===e.type?t.add(e.name):"Literal"!==e.type&&"StringLiteral"!==e.type||t.add(String(e.value)))}}const moduleExportsCache=new Map;function getModuleExports(e,t){t=t||new Set;const r=e;if(moduleExportsCache.has(r))return moduleExportsCache.get(r);if(t.has(e))return{names:new Set,uncertain:!0};let n;t.add(e);const i=path.extname(e).toLowerCase();if(".json"===i){try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));n={names:t&&"object"==typeof t?new Set(Object.keys(t)):new Set,uncertain:!1}}catch(e){n={names:null,uncertain:!0}}return moduleExportsCache.set(r,n),n}if(".node"===i||![".js",".jsx",".ts",".tsx",".mjs",".cjs"].includes(i)&&""!==i)return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n;let o,a;try{o=fs.readFileSync(e,"utf-8")}catch(e){return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n}try{a=parseProgram(o)}catch(e){return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n}const s=new Set,l={value:!1},c=path.dirname(e);function u(e,r){const n=function(e){try{return require.resolve(e,{paths:[c]})}catch(e){return null}}(e);if(!n)return void(l.value=!0);let i;try{i=getModuleExports(n,t)}catch(e){return void(l.value=!0)}if(i&&!i.uncertain&&null!==i.names&&"function"==typeof i.names.has)if(r)for(const e of r)i.names.has(e)&&s.add(e);else for(const e of i.names)s.add(e);else l.value=!0}let p=null;for(const e of a.body){if("ExportNamedDeclaration"===e.type)if(e.declaration){const t=e.declaration;if("VariableDeclaration"===t.type)for(const e of t.declarations)e.id&&"Identifier"===e.id.type?s.add(e.id.name):e.id&&"ObjectPattern"===e.id.type&&(l.value=!0);else"FunctionDeclaration"!==t.type&&"ClassDeclaration"!==t.type||!t.id||s.add(t.id.name)}else if(e.source){const t=(e.specifiers||[]).map(e=>e.local.name);u(e.source.value,t);for(const t of e.specifiers||[])s.add(t.exported.name||t.exported.value)}else for(const t of e.specifiers||[])s.add(t.exported.name||t.exported.value);if("ExportAllDeclaration"===e.type&&e.source&&u(e.source.value,null),"ExportDefaultDeclaration"===e.type&&s.add("default"),"ExpressionStatement"===e.type){const t=e.expression;if(t&&"AssignmentExpression"===t.type&&"="===t.operator){const e=t.left;"MemberExpression"===e.type&&"Identifier"===e.object.type&&"module"===e.object.name&&"Identifier"===e.property.type&&"exports"===e.property.name?"ObjectExpression"===t.right.type?collectObjectKeys(t.right,s,l):"CallExpression"!==t.right.type||"Identifier"!==t.right.callee.type||"require"!==t.right.callee.name||!t.right.arguments[0]||"Literal"!==t.right.arguments[0].type&&"StringLiteral"!==t.right.arguments[0].type?("Identifier"===t.right.type||"FunctionExpression"===t.right.type||t.right.type,l.value=!0):p=t.right.arguments[0].value:"MemberExpression"===e.type&&!e.computed&&"Identifier"===e.property.type&&("Identifier"===e.object.type&&"exports"===e.object.name||"MemberExpression"===e.object.type&&"Identifier"===e.object.object.type&&"module"===e.object.object.name&&"Identifier"===e.object.property.type&&"exports"===e.object.property.name)&&s.add(e.property.name)}t&&"CallExpression"===t.type&&"MemberExpression"===t.callee.type&&"Identifier"===t.callee.object.type&&"Object"===t.callee.object.name&&"Identifier"===t.callee.property.type&&"defineProperty"===t.callee.property.name&&t.arguments[0]&&"Identifier"===t.arguments[0].type&&"exports"===t.arguments[0].name&&t.arguments[1]&&("Literal"===t.arguments[1].type||"StringLiteral"===t.arguments[1].type)&&s.add(t.arguments[1].value)}}return p&&u(p,null),0===s.size&&!l.value&&a.body.length>5&&(l.value=!0),n={names:s,uncertain:l.value},moduleExportsCache.set(r,n),n}function verifyFile(e,t){const r=[],n=extractNamedImports(t);if(0===n.length)return r;const i=path.dirname(e);for(const t of n){if(t.source.startsWith(".")||t.source.startsWith("/"))continue;if("default"===t.imported)continue;let n;if(isBuiltinSpecifier(t.source))n=getBuiltinExports(t.source.startsWith("node:")?t.source.slice(5):t.source);else{let e;try{e=require.resolve(t.source,{paths:[i]})}catch(e){continue}try{n=getModuleExports(e,new Set)}catch(e){continue}}n&&null!==n.names&&!n.uncertain&&"function"==typeof n.names.has&&(n.names.has(t.imported)||r.push({file:e,line:t.line,source:t.source,importedName:t.imported,message:`'${t.source}' does not export '${t.imported}' — this import will be undefined at runtime`}))}return r}module.exports={verifyFile:verifyFile,extractNamedImports:extractNamedImports,getModuleExports:getModuleExports,getBuiltinExports:getBuiltinExports,isBuiltinSpecifier:isBuiltinSpecifier,_internal:{parseProgram:parseProgram,collectObjectKeys:collectObjectKeys}};
1
+ "use strict";const fs=require("fs"),path=require("path"),nodeModule=require("module"),parser=require("@babel/parser"),{_internal:_internal}=require("./ast-analyzer"),{walk:walk}=_internal,BABEL_PLUGINS=["estree","typescript","jsx","classProperties","decorators-legacy"];function parseProgram(e){return parser.parse(e,{sourceType:"unambiguous",plugins:BABEL_PLUGINS,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowAwaitOutsideFunction:!0}).program}function extractNamedImports(e){const t=[];let r;try{r=parseProgram(e)}catch(e){return t}for(const e of r.body)if("ImportDeclaration"===e.type&&e.source){const r=e.source.value;for(const n of e.specifiers||[])if("ImportSpecifier"===n.type){const i=n.imported.name||n.imported.value;t.push({imported:i,local:n.local.name,source:r,line:e.loc?e.loc.start.line:0,kind:"import"})}}return walk(r,e=>{if("VariableDeclarator"===e.type&&e.init&&"CallExpression"===e.init.type&&"Identifier"===e.init.callee.type&&"require"===e.init.callee.name&&e.init.arguments[0]&&("Literal"===e.init.arguments[0].type||"StringLiteral"===e.init.arguments[0].type)&&"ObjectPattern"===e.id.type){const r=e.init.arguments[0].value,n=e.loc?e.loc.start.line:0;for(const i of e.id.properties)if(("RestElement"!==i.type&&("ObjectProperty"===i.type!=0||"Property"===i.type)||"RestElement"!==i.type)&&i.key&&i.value){const e=void 0!==i.key.name?i.key.name:i.key.value,o="Identifier"===i.value.type?i.value.name:e;t.push({imported:e,local:o,source:r,line:n,kind:"require"})}}}),t}const builtinModuleCache=new Map;function getBuiltinExports(e){if(builtinModuleCache.has(e))return builtinModuleCache.get(e);let t;try{const r=require(e);t={names:new Set(Object.keys(r)),uncertain:!1}}catch(e){t={names:null,uncertain:!0}}return builtinModuleCache.set(e,t),t}function isBuiltinSpecifier(e){const t=e.startsWith("node:")?e.slice(5):e;return nodeModule.builtinModules.includes(t)||nodeModule.builtinModules.includes(e)}function collectObjectKeys(e,t,r){for(const n of e.properties||[]){if("SpreadElement"===n.type||"SpreadProperty"===n.type||"ExperimentalSpreadProperty"===n.type){r.value=!0;continue}if(n.computed){r.value=!0;continue}const e=n.key;e&&("Identifier"===e.type?t.add(e.name):"Literal"!==e.type&&"StringLiteral"!==e.type||t.add(String(e.value)))}}const moduleExportsCache=new Map;function getModuleExports(e,t){t=t||new Set;const r=e;if(moduleExportsCache.has(r))return moduleExportsCache.get(r);if(t.has(e))return{names:new Set,uncertain:!0};let n;t.add(e);const i=path.extname(e).toLowerCase();if(".json"===i){try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));n={names:t&&"object"==typeof t?new Set(Object.keys(t)):new Set,uncertain:!1}}catch(e){n={names:null,uncertain:!0}}return moduleExportsCache.set(r,n),n}if(".node"===i||![".js",".jsx",".ts",".tsx",".mjs",".cjs"].includes(i)&&""!==i)return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n;let o,a;try{o=fs.readFileSync(e,"utf-8")}catch(e){return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n}try{a=parseProgram(o)}catch(e){return n={names:null,uncertain:!0},moduleExportsCache.set(r,n),n}const s=new Set,l={value:!1},c=path.dirname(e);function p(e,r){const n=function(e){try{return require.resolve(e,{paths:[c]})}catch(e){return null}}(e);if(!n)return void(l.value=!0);let i;try{i=getModuleExports(n,t)}catch(e){return void(l.value=!0)}if(i&&!i.uncertain&&null!==i.names&&"function"==typeof i.names.has)if(r)for(const e of r)i.names.has(e)&&s.add(e);else for(const e of i.names)s.add(e);else l.value=!0}let u=null;for(const e of a.body){if("ExportNamedDeclaration"===e.type)if(e.declaration){const t=e.declaration;if("VariableDeclaration"===t.type)for(const e of t.declarations)e.id&&"Identifier"===e.id.type?s.add(e.id.name):e.id&&"ObjectPattern"===e.id.type&&(l.value=!0);else"FunctionDeclaration"!==t.type&&"ClassDeclaration"!==t.type||!t.id||s.add(t.id.name)}else if(e.source){const t=(e.specifiers||[]).map(e=>e.local.name);p(e.source.value,t);for(const t of e.specifiers||[])s.add(t.exported.name||t.exported.value)}else for(const t of e.specifiers||[])s.add(t.exported.name||t.exported.value);if("ExportAllDeclaration"===e.type&&e.source&&p(e.source.value,null),"ExportDefaultDeclaration"===e.type&&s.add("default"),"ExpressionStatement"===e.type){const t=e.expression;if(t&&"AssignmentExpression"===t.type&&"="===t.operator){const e=t.left;"MemberExpression"===e.type&&"Identifier"===e.object.type&&"module"===e.object.name&&"Identifier"===e.property.type&&"exports"===e.property.name?"ObjectExpression"===t.right.type?collectObjectKeys(t.right,s,l):"CallExpression"!==t.right.type||"Identifier"!==t.right.callee.type||"require"!==t.right.callee.name||!t.right.arguments[0]||"Literal"!==t.right.arguments[0].type&&"StringLiteral"!==t.right.arguments[0].type?("Identifier"===t.right.type||"FunctionExpression"===t.right.type||t.right.type,l.value=!0):u=t.right.arguments[0].value:"MemberExpression"===e.type&&!e.computed&&"Identifier"===e.property.type&&("Identifier"===e.object.type&&"exports"===e.object.name||"MemberExpression"===e.object.type&&"Identifier"===e.object.object.type&&"module"===e.object.object.name&&"Identifier"===e.object.property.type&&"exports"===e.object.property.name)&&s.add(e.property.name)}t&&"CallExpression"===t.type&&"MemberExpression"===t.callee.type&&"Identifier"===t.callee.object.type&&"Object"===t.callee.object.name&&"Identifier"===t.callee.property.type&&"defineProperty"===t.callee.property.name&&t.arguments[0]&&"Identifier"===t.arguments[0].type&&"exports"===t.arguments[0].name&&t.arguments[1]&&("Literal"===t.arguments[1].type||"StringLiteral"===t.arguments[1].type)&&s.add(t.arguments[1].value)}}return u&&p(u,null),walk(a,e=>{"AssignmentExpression"===e.type&&"="===e.operator&&e.left&&"MemberExpression"===e.left.type&&e.left.object&&"Identifier"===e.left.object.type&&"module"===e.left.object.name&&e.left.property&&"Identifier"===e.left.property.type&&"exports"===e.left.property.name&&(e.right&&"ObjectExpression"===e.right.type?collectObjectKeys(e.right,s,l):e.right&&"CallExpression"===e.right.type&&e.right.callee&&"Identifier"===e.right.callee.type&&"require"===e.right.callee.name&&e.right.arguments[0]&&("Literal"===e.right.arguments[0].type||"StringLiteral"===e.right.arguments[0].type)?p(e.right.arguments[0].value,null):l.value=!0)}),0===s.size&&!l.value&&a.body.length>0&&(l.value=!0),n={names:s,uncertain:l.value},moduleExportsCache.set(r,n),n}function verifyFile(e,t){const r=[],n=extractNamedImports(t);if(0===n.length)return r;const i=path.dirname(e);for(const t of n){if(t.source.startsWith(".")||path.isAbsolute(t.source))continue;if("default"===t.imported)continue;let n;if(isBuiltinSpecifier(t.source))n=getBuiltinExports(t.source.startsWith("node:")?t.source.slice(5):t.source);else{let e;try{e=require.resolve(t.source,{paths:[i]})}catch(e){continue}try{n=getModuleExports(e,new Set)}catch(e){continue}}n&&null!==n.names&&!n.uncertain&&"function"==typeof n.names.has&&(n.names.has(t.imported)||r.push({file:e,line:t.line,source:t.source,importedName:t.imported,message:`'${t.source}' does not export '${t.imported}' — this import will be undefined at runtime`}))}return r}module.exports={verifyFile:verifyFile,extractNamedImports:extractNamedImports,getModuleExports:getModuleExports,getBuiltinExports:getBuiltinExports,isBuiltinSpecifier:isBuiltinSpecifier,_internal:{parseProgram:parseProgram,collectObjectKeys:collectObjectKeys}};
@@ -0,0 +1 @@
1
+ const https=require("https"),os=require("os"),fs=require("fs"),path=require("path"),readline=require("readline"),C={reset:"",bold:"",green:"",yellow:"",cyan:"",gray:"",red:""},CATEGORIES=["bug","feature","suggestion","other"],DIVIDER="─".repeat(38);class FeedbackClient{constructor(e={}){this.endpoint=e.endpoint||"https://europe-west2-orion-os-479912.cloudfunctions.net/thuban-api/feedback",this.maxLength=2e3,this.localStorePath=path.join(os.homedir(),".thuban","pending-feedback.json")}sanitise(e){if(!e||"string"!=typeof e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g,"[code removed]"),t=t.replace(/((?:Error|TypeError|ReferenceError|SyntaxError|RangeError)[^\n]*)\n(?:\s+at\s+[^\n]+\n?)+/g,"$1\n[stack trace removed]"),t=t.replace(/(?:\/(?:home|Users|var|tmp|opt|etc)\/|[A-Z]:\\)[^\s"'`,;)}\]]+/g,"[path removed]"),t=t.replace(/\b[A-Za-z0-9+/=_-]{33,}\b/g,"[secret removed]"),t=t.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]"),t=t.replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[ip]"),t=t.replace(/\b(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}\b/g,"[ip]"),t.length>this.maxLength&&(t=t.slice(0,this.maxLength-3)+"..."),t.trim()}getSystemInfo(){let e="0.4.6";try{const t=path.join(__dirname,"package.json"),r=JSON.parse(fs.readFileSync(t,"utf8"));r.version&&(e=r.version)}catch{}return{os:process.platform,arch:process.arch,nodeVersion:process.version,thubanVersion:e}}async submit(e,t="general",r={}){const s=this.sanitise(e);if(!s)return{ok:!1,error:"Feedback text is empty after sanitisation."};const o=this.getSystemInfo(),n={text:s,category:t,systemInfo:o,timestamp:(new Date).toISOString()},a=["",`${C.gray}${DIVIDER}${C.reset}`,`${C.bold}The following will be sent to thuban.dev:${C.reset}`,"",`${C.cyan}Category:${C.reset} ${t}`,`${C.cyan}Message:${C.reset} "${s}"`,`${C.cyan}System:${C.reset} ${o.os} / ${o.arch} / Node ${o.nodeVersion} / Thuban v${o.thubanVersion}`,"",`${C.green}No code, file paths, or personal data is included.${C.reset}`,`${C.gray}${DIVIDER}${C.reset}`].join("\n");if(!(console.log(a),r.skipConfirm||await this._confirm("Send this feedback? (y/n): ")))return console.log(`${C.yellow}Feedback cancelled.${C.reset}`),{ok:!1,error:"Cancelled by user."};const i=await this._send(n);return i.ok?console.log(`${C.green}${C.bold}Thank you! Feedback sent successfully.${C.reset}`):this.saveLocal(n),i}async startInteractive(){const e=["",` ${C.cyan}╔${"═".repeat(38)}╗${C.reset}`,` ${C.cyan}║${C.reset} ${C.bold}THUBAN Feedback${C.reset} ${C.cyan}║${C.reset}`,` ${C.cyan}║${C.reset} Help us make Thuban better ${C.cyan}║${C.reset}`,` ${C.cyan}╚${"═".repeat(38)}╝${C.reset}`,""," What type of feedback?",` ${C.bold}[1]${C.reset} Bug report`,` ${C.bold}[2]${C.reset} Feature request`,` ${C.bold}[3]${C.reset} Suggestion`,` ${C.bold}[4]${C.reset} Other`,""].join("\n");console.log(e);const t=await this._prompt(" Choice: "),r=parseInt(t,10);if(isNaN(r)||r<1||r>4)return console.log(`${C.red}Invalid choice. Please enter 1-4.${C.reset}`),{ok:!1,error:"Invalid category choice."};const s=CATEGORIES[r-1];console.log(`\n ${C.gray}Category: ${s}${C.reset}\n`);const o=await this._prompt(" Your feedback:\n > ");return o&&o.trim()?this.submit(o,s):(console.log(`${C.red}No feedback provided.${C.reset}`),{ok:!1,error:"Empty feedback."})}saveLocal(e){try{const t=path.dirname(this.localStorePath);fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0});let r=[];if(fs.existsSync(this.localStorePath))try{r=JSON.parse(fs.readFileSync(this.localStorePath,"utf8")),Array.isArray(r)||(r=[])}catch{r=[]}r.push(e),fs.writeFileSync(this.localStorePath,JSON.stringify(r,null,2),"utf8"),console.log(`\n${C.yellow}Feedback saved locally. It will be sent next time you run 'thuban feedback --retry'.${C.reset}`)}catch(e){console.error(`${C.red}Failed to save feedback locally: ${e.message}${C.reset}`)}}async retryPending(){if(!fs.existsSync(this.localStorePath))return console.log(`${C.gray}No pending feedback found.${C.reset}`),{sent:0,failed:0,total:0};let e;try{if(e=JSON.parse(fs.readFileSync(this.localStorePath,"utf8")),!Array.isArray(e)||0===e.length)return console.log(`${C.gray}No pending feedback found.${C.reset}`),{sent:0,failed:0,total:0}}catch{return console.log(`${C.red}Could not read pending feedback file.${C.reset}`),{sent:0,failed:0,total:0}}const t=e.length;console.log(`${C.cyan}Retrying ${t} pending feedback item(s)...${C.reset}`);const r=[];let s=0;for(const t of e)(await this._send(t)).ok?s++:r.push(t);if(r.length>0)fs.writeFileSync(this.localStorePath,JSON.stringify(r,null,2),"utf8");else try{fs.unlinkSync(this.localStorePath)}catch{}const o=t-s;return console.log(`${C.green}Sent: ${s}${C.reset}`+(o>0?` | ${C.red}Failed: ${o}${C.reset}`:"")),{sent:s,failed:o,total:t}}async _send(e){return new Promise(t=>{const r=JSON.stringify(e),s=new URL(this.endpoint),o={hostname:s.hostname,port:443,path:s.pathname,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)},timeout:1e4},n=https.request(o,e=>{let r="";e.on("data",e=>{r+=e}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({ok:!0}):t({ok:!1,error:`Server responded with ${e.statusCode}: ${r}`})})});n.on("timeout",()=>{n.destroy(),t({ok:!1,error:"Request timed out after 10 seconds."})}),n.on("error",e=>{t({ok:!1,error:`Network error: ${e.message}`})}),n.write(r),n.end()})}_prompt(e){return new Promise(t=>{const r=readline.createInterface({input:process.stdin,output:process.stdout});r.question(e,e=>{r.close(),t(e.trim())})})}_confirm(e){return new Promise(t=>{const r=readline.createInterface({input:process.stdin,output:process.stdout});r.question(e,e=>{r.close(),t("y"===e.trim().toLowerCase())})})}}module.exports=FeedbackClient;
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),MAX_IGNORE_PATTERNS=1e3;function loadThubanIgnore(e){const t=[];try{const n=path.join(e,".thubanignore");if(fs.existsSync(n)){if(fs.statSync(n).size>262144)return console.warn("[THUBAN] WARNING: .thubanignore exceeds 256KB — ignoring to prevent DoS"),t;const e=fs.readFileSync(n,"utf-8");for(const n of e.split("\n")){const e=n.trim();if(e&&!e.startsWith("#")&&(t.push(e),t.length>=1e3)){console.warn("[THUBAN] WARNING: .thubanignore has >1000 patterns — truncating to prevent DoS");break}}}}catch{}return t}function matchesIgnorePattern(e,t){const n=e.replace(/\\/g,"/");for(const e of t){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t&&"."!==t&&"*"!==t&&"**"!==t){if(t.endsWith("/**")){const e=t.slice(0,-3);if(!e||"."===e)continue;if(n===e||n.startsWith(e+"/"))return!0}if(n===t)return!0;if(n.startsWith(t+"/"))return!0}}return!1}function collectFiles(e,t=[]){const n=["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","coverage",".cache",".turbo",...t],i=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".cs",".php",".rb",".json"],s=1048576,r=[],o=(new Set,path.resolve(e)),c=loadThubanIgnore(o);let a=0,l=0;function u(e){const t=o+path.sep,n=path.resolve(e);return n===o||n.startsWith(t)}if(function e(t,f){if(r.length>=5e4)return;if(f>100)return;if(!u(t))return;let h;try{h=fs.readdirSync(t,{withFileTypes:!0})}catch(e){if("ENOTDIR"===e.code)try{const e=fs.lstatSync(t);if(e.isSymbolicLink())return;if(!u(t))return;e.isFile()&&i.some(e=>t.endsWith(e))&&e.size>0&&e.size<=s&&r.push(t)}catch{}return}for(const p of h){if(r.length>=5e4)return;if(n.some(e=>p.name===e))continue;if(p.name.includes("\0"))continue;const h=path.join(t,p.name),g=path.resolve(h);if(!u(g))continue;const d=path.relative(o,g);if(d.startsWith(".."))continue;if(c.length>0&&matchesIgnorePattern(d,c)){a++;continue}let y;try{y=fs.lstatSync(h)}catch{continue}y.isSymbolicLink()||(y.isDirectory()?e(h,f+1):y.isFile()&&i.some(e=>p.name.normalize("NFC").endsWith(e))&&(l++,y.size>0&&y.size<=s&&r.push(h)))}}(e,0),c.length>0&&l>0){const e=r.length+a;if(e>0){const t=a/e;t>.9&&console.warn(`[THUBAN] WARNING: .thubanignore is excluding ${a} of ${e} files (${Math.round(100*t)}%). This may indicate a malicious ignore file designed to suppress scan findings. Review .thubanignore carefully.`)}}return r}module.exports={collectFiles:collectFiles};
1
+ const fs=require("fs"),path=require("path"),MAX_IGNORE_PATTERNS=1e3;function loadThubanIgnore(e){const t=[];try{const n=path.join(e,".thubanignore");if(fs.existsSync(n)){if(fs.statSync(n).size>262144)return console.warn("[THUBAN] WARNING: .thubanignore exceeds 256KB — ignoring to prevent DoS"),t;const e=fs.readFileSync(n,"utf-8");for(const n of e.split(/\r?\n/)){const e=n.trim();if(e&&!e.startsWith("#")&&(t.push(e),t.length>=1e3)){console.warn("[THUBAN] WARNING: .thubanignore has >1000 patterns — truncating to prevent DoS");break}}}}catch{}return t}function matchesIgnorePattern(e,t){const n=e.replace(/\\/g,"/");for(const e of t){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t&&"."!==t&&"*"!==t&&"**"!==t){if(t.endsWith("/**")){const e=t.slice(0,-3);if(!e||"."===e)continue;if(n===e||n.startsWith(e+"/"))return!0}if(n===t)return!0;if(n.startsWith(t+"/"))return!0}}return!1}function collectFiles(e,t=[]){const n=["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","coverage",".cache",".turbo",...t],i=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".cs",".php",".rb",".json"],s=1048576,r=[],o=(new Set,path.resolve(e)),c=loadThubanIgnore(o);let a=0,l=0;function u(e){const t=o+path.sep,n=path.resolve(e);return n===o||n.startsWith(t)}if(function e(t,f){if(r.length>=5e4)return;if(f>100)return;if(!u(t))return;let h;try{h=fs.readdirSync(t,{withFileTypes:!0})}catch(e){if("ENOTDIR"===e.code)try{const e=fs.lstatSync(t);if(e.isSymbolicLink())return;if(!u(t))return;e.isFile()&&i.some(e=>t.endsWith(e))&&e.size>0&&e.size<=s&&r.push(t)}catch{}return}for(const p of h){if(r.length>=5e4)return;if(n.some(e=>p.name===e))continue;if(p.name.includes("\0"))continue;const h=path.join(t,p.name),g=path.resolve(h);if(!u(g))continue;const d=path.relative(o,g);if(d.startsWith(".."))continue;if(c.length>0&&matchesIgnorePattern(d,c)){a++;continue}let y;try{y=fs.lstatSync(h)}catch{continue}y.isSymbolicLink()||(y.isDirectory()?e(h,f+1):y.isFile()&&i.some(e=>p.name.normalize("NFC").endsWith(e))&&(l++,y.size>0&&y.size<=s&&r.push(h)))}}(e,0),c.length>0&&l>0){const e=r.length+a;if(e>0){const t=a/e;t>.9&&console.warn(`[THUBAN] WARNING: .thubanignore is excluding ${a} of ${e} files (${Math.round(100*t)}%). This may indicate a malicious ignore file designed to suppress scan findings. Review .thubanignore carefully.`)}}return r}module.exports={collectFiles:collectFiles};
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path");class GhostCodeDetector{constructor(e={}){this.rootPath=e.rootPath||process.cwd()}scan(e){const t=[],s={},n=new Map,i=new Map;for(const o of e){let e;try{if(fs.statSync(o).size>524288)continue;e=fs.readFileSync(o,"utf-8")}catch(e){continue}const r=path.relative(this.rootPath,o);if(this._isSkippable(r))continue;const c=e.split("\n");n.set(r,e),i.set(r,c);for(let e=0;e<c.length;e++){const n=c[e],i=this._extractFunction(n,e,c);if(i){i.file=r,i.line=e+1,i.lineCount=this._countFunctionLines(c,e),i.declKind="function",t.push(i),s[i.name]||(s[i.name]=0);continue}const o=this._extractClass(n);if(o){o.file=r,o.line=e+1,o.lineCount=this._countFunctionLines(c,e),o.declKind="class",t.push(o),s[o.name]||(s[o.name]=0);continue}const a=this._extractConstDeclaration(n);if(a){a.file=r,a.line=e+1,a.lineCount=1,a.declKind="const",t.push(a),s[a.name]||(s[a.name]=0);continue}const l=this._extractImports(n);for(const n of l)n.file=r,n.line=e+1,n.lineCount=1,n.declKind="import",t.push(n),s[n.name]||(s[n.name]=0)}}for(const i of e){const e=path.relative(this.rootPath,i),o=n.get(e);if(void 0===o)continue;const r=this._stripCommentsAndStrings(o);for(const n of t){if(n.name.length<3)continue;const t=new RegExp(`\\b${this._escapeRegex(n.name)}\\b`,"g"),i=r.match(t);if(i){const t=e===n.file;s[n.name]+=i.length-(t?1:0)}}}const o=t.filter(e=>"function"===e.declKind).filter(e=>(s[e.name]||0)<=0&&!e.isLifecycle&&e.lineCount>=3).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost",severity:e.isExport?"low":e.lineCount>30?"high":"medium",message:`${e.name}() — ${e.lineCount} lines, never called${e.isExport?" (exported — verify no external consumers)":""}`})),r=t.filter(e=>"class"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_class",severity:e.isExport?"low":"medium",message:`class ${e.name} — ${e.lineCount} lines, never referenced${e.isExport?" (exported — verify no external consumers)":""}`})),c=t.filter(e=>"const"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_const",severity:e.isExport?"low":"medium",message:`${e.kind} ${e.name} — declared but never used${e.isExport?" (exported — verify no external consumers)":""}`})),a=t.filter(e=>"import"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_import",severity:"low",message:`import '${e.name}' from '${e.source}' — never used`})),l=this._findDeadClusters(t.filter(e=>"function"===e.declKind),n,s),f=[...o,...r,...c,...a,...l].sort((e,t)=>t.wastedLines-e.wastedLines),u=f.reduce((e,t)=>e+t.wastedLines,0),p=e.reduce((e,t)=>{try{return e+fs.readFileSync(t,"utf-8").split("\n").length}catch(t){return e}},0);return{ghosts:f,totalGhosts:f.length,totalWastedLines:u,wastedPercent:p>0?Math.round(u/p*1e3)/10:0,totalLines:p,breakdown:{functions:o.length,classes:r.length,consts:c.length,imports:a.length,deadClusters:l.length}}}_extractFunction(e,t,s){const n=e.trim();let i=n.match(/^(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/);return i?{name:i[1],type:"function",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?function/),i?{name:i[1],type:"const-function",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?\(?/),i&&(n.includes("=>")||t+1<s.length&&s[t+1].includes("=>"))?{name:i[1],type:"arrow",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:private\s+|public\s+|internal\s+|protected\s+)?(?:suspend\s+)?fun\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),i?{name:i[1],type:"kotlin-fun",isExport:!n.startsWith("private"),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),i?{name:i[1],type:"go-func",isExport:/^[A-Z]/.test(i[1]),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),i?{name:i[1],type:"rust-fn",isExport:/^pub/.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:(?:public|private|protected|static)\s+)*function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),i?{name:i[1],type:"php-function",isExport:!/private/.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*)\s*[(\s]?/),i?{name:i[1],type:"ruby-def",isExport:/^def\s+self\./.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:async\s+)?([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*{/),i&&!["if","for","while","switch","catch","constructor","render","toString"].includes(i[1])?{name:i[1],type:"method",isExport:!1,isLifecycle:this._isLifecycle(i[1])}:null))))))))}_isExported(e,t,s){return!!/^export\s/.test(e.trim())||!!/module\.exports/.test(e)}_extractClass(e){const t=e.trim(),s=t.match(/^(?:export\s+(?:default\s+)?)?class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);return s?{name:s[1],type:"class",isExport:/^export\s/.test(t),isLifecycle:!1}:null}_extractConstDeclaration(e){const t=e.trim().match(/^(export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(.+)$/);if(!t)return null;const[,s,n,i,o]=t;return/^(?:async\s+)?function\b/.test(o)||/=>/.test(o)||""===o.trim()||/^\(/.test(o.trim())&&/=>/.test(o)||/require\s*\(/.test(o)?null:{name:i,kind:n,type:"const-declaration",isExport:!!s,isLifecycle:!1}}_extractImports(e){const t=e.trim(),s=[];let n=t.match(/^import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/);if(n){const e=n[1].split(",").map(e=>e.trim()).filter(Boolean);for(const t of e){const e=t.split(/\s+as\s+/),i=(e[1]||e[0]).trim();i&&s.push({name:i,source:n[2],type:"import"})}return s}if(n=t.match(/^import\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:,|from)/),n&&!/^import\s*\{/.test(t)){const e=t.match(/from\s*['"]([^'"]+)['"]/);return s.push({name:n[1],source:e?e[1]:"",type:"import"}),s}if(n=t.match(/^import\s*\*\s*as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*from\s*['"]([^'"]+)['"]/),n)return s.push({name:n[1],source:n[2],type:"import"}),s;if(n=t.match(/^(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/),n){const e=n[1].split(",").map(e=>e.trim()).filter(Boolean);for(const t of e){const e=t.split(":").map(e=>e.trim()),i=(e[1]||e[0]).trim();i&&s.push({name:i,source:n[2],type:"import"})}return s}return n=t.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/),n?(s.push({name:n[1],source:n[2],type:"import"}),s):s}_findDeadClusters(e,t,s){const n=[],i=new Map;for(const t of e)t.isExport||t.isLifecycle||i.set(t.name,t);if(i.size<2)return n;const o=new Map;for(const[e,s]of i){const n=t.get(s.file);if(!n){o.set(e,new Set);continue}const r=n.split("\n").slice(s.line-1,s.line-1+s.lineCount),c=this._stripCommentsAndStrings(r.join("\n")),a=new Set;for(const[t]of i)t!==e&&new RegExp(`\\b${this._escapeRegex(t)}\\b`).test(c)&&a.add(t);o.set(e,a)}const r=new Map,c=e=>{r.has(e)||r.set(e,e);let t=e;for(;r.get(t)!==t;)t=r.get(t);let s=e;for(;r.get(s)!==t;){const e=r.get(s);r.set(s,t),s=e}return t},a=(e,t)=>{const s=c(e),n=c(t);s!==n&&r.set(s,n)};for(const[e,t]of o){c(e);for(const s of t)c(s),a(e,s)}const l=new Map;for(const e of i.keys()){const t=c(e);l.has(t)||l.set(t,[]),l.get(t).push(e)}for(const[,e]of l){if(e.length<2)continue;let t=!1;for(const s of e){for(const n of o.get(s)||[])if(e.includes(n)&&(o.get(n)||new Set).has(s)){t=!0;break}if(t)break}if(!t)continue;let r=!1;for(const t of e)if((s[t]||0)-e.reduce((e,s)=>s===t?e:e+((o.get(s)||new Set).has(t)?1:0),0)>0){r=!0;break}if(r)continue;const c=e.reduce((e,t)=>e+(i.get(t).lineCount||0),0);n.push({name:e.join(", "),file:i.get(e[0]).file,line:i.get(e[0]).line,lineCount:c,wastedLines:c,references:0,category:"dead_cluster",severity:"high",message:`Dead cluster: ${e.join(" ↔ ")} — mutually reference each other but nothing outside the cluster calls them`})}return n}_isLifecycle(e){return["constructor","render","componentDidMount","componentWillUnmount","componentDidUpdate","shouldComponentUpdate","getSnapshotBeforeUpdate","getDerivedStateFromProps","useEffect","useState","useMemo","toString","valueOf","toJSON","inspect","setup","teardown","beforeEach","afterEach","beforeAll","afterAll","init","destroy","configure","bootstrap","main","get","set","post","put","delete","patch","handle","onCreate","onStart","onResume","onPause","onStop","onDestroy","onCreateView","onViewCreated","onDestroyView","hashCode","equals","new","default","drop","fmt","from","into","clone","copy","initialize","to_s","to_str","inspect","freeze","dup","__construct","__destruct","__toString","__get","__set","__call"].includes(e)||/^__/.test(e)||/^on[A-Z]/.test(e)}_countFunctionLines(e,t){const s=(e[t]||"").trim();if(/^def\s/.test(s)){let s=1,n=1;for(let i=t+1;i<e.length&&i<t+200;i++){n++;const t=e[i].trim();if(/^(?:def|class|module|begin|case)\b/.test(t)&&s++,/^(?:if|unless|while|until|for)\b/.test(t)&&!/\bthen\b/.test(t)&&s++,/\bdo\s*(\|[^|]*\|)?\s*$/.test(t)&&s++,/^end\b/.test(t)&&s--,s<=0)break}return n}let n=0,i=!1,o=0;for(let s=t;s<e.length&&s<t+200;s++){const t=e[s];o++;for(const e of t)"{"===e&&(n++,i=!0),"}"===e&&n--;if(i&&n<=0)break}return o}_isSkippable(e){return[/\.test\./i,/\.spec\./i,/test[\/\\]/i,/spec[\/\\]/i,/__test__/i,/__mocks__/i,/\.config\./i,/\.d\.ts$/,/index\.(js|ts)$/,/server\.(js|ts)$/,/app\.(js|ts)$/,/routes?\.(js|ts)$/,/middleware/i].some(t=>t.test(e))}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_stripCommentsAndStrings(e){return e.replace(/`[^`\\]*(?:\\[\s\S][^`\\]*)*`/g,'""').replace(/"[^"\\\n]*(?:\\.[^"\\\n]*)*"/g,'""').replace(/'[^'\\\n]*(?:\\.[^'\\\n]*)*'/g,"''").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/#[^\n]*/g," ")}}module.exports=GhostCodeDetector;
1
+ const fs=require("fs"),path=require("path");class GhostCodeDetector{constructor(e={}){this.rootPath=e.rootPath||process.cwd()}scan(e){const t=[],s={},n=new Map,i=new Map;for(const o of e){let e;try{if(fs.statSync(o).size>524288)continue;e=fs.readFileSync(o,"utf-8").replace(/\r\n/g,"\n")}catch(e){continue}const r=path.relative(this.rootPath,o);if(this._isSkippable(r))continue;const c=e.split("\n");n.set(r,e),i.set(r,c);for(let e=0;e<c.length;e++){const n=c[e],i=this._extractFunction(n,e,c);if(i){i.file=r,i.line=e+1,i.lineCount=this._countFunctionLines(c,e),i.declKind="function",t.push(i),s[i.name]||(s[i.name]=0);continue}const o=this._extractClass(n);if(o){o.file=r,o.line=e+1,o.lineCount=this._countFunctionLines(c,e),o.declKind="class",t.push(o),s[o.name]||(s[o.name]=0);continue}const a=this._extractConstDeclaration(n);if(a){a.file=r,a.line=e+1,a.lineCount=1,a.declKind="const",t.push(a),s[a.name]||(s[a.name]=0);continue}const l=this._extractImports(n);for(const n of l)n.file=r,n.line=e+1,n.lineCount=1,n.declKind="import",t.push(n),s[n.name]||(s[n.name]=0)}}for(const i of e){const e=path.relative(this.rootPath,i),o=n.get(e);if(void 0===o)continue;const r=this._stripCommentsAndStrings(o);for(const n of t){if(n.name.length<3)continue;const t=new RegExp(`\\b${this._escapeRegex(n.name)}\\b`,"g"),i=r.match(t);if(i){const t=e===n.file;s[n.name]+=i.length-(t?1:0)}}}const o=t.filter(e=>"function"===e.declKind).filter(e=>(s[e.name]||0)<=0&&!e.isLifecycle&&e.lineCount>=3).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost",severity:e.isExport?"low":e.lineCount>30?"high":"medium",message:`${e.name}() — ${e.lineCount} lines, never called${e.isExport?" (exported — verify no external consumers)":""}`})),r=t.filter(e=>"class"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_class",severity:e.isExport?"low":"medium",message:`class ${e.name} — ${e.lineCount} lines, never referenced${e.isExport?" (exported — verify no external consumers)":""}`})),c=t.filter(e=>"const"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_const",severity:e.isExport?"low":"medium",message:`${e.kind} ${e.name} — declared but never used${e.isExport?" (exported — verify no external consumers)":""}`})),a=t.filter(e=>"import"===e.declKind).filter(e=>(s[e.name]||0)<=0).map(e=>({...e,references:s[e.name]||0,wastedLines:e.lineCount,category:"ghost_import",severity:"low",message:`import '${e.name}' from '${e.source}' — never used`})),l=this._findDeadClusters(t.filter(e=>"function"===e.declKind),n,s),f=[...o,...r,...c,...a,...l].sort((e,t)=>t.wastedLines-e.wastedLines),u=f.reduce((e,t)=>e+t.wastedLines,0),p=e.reduce((e,t)=>{try{return e+fs.readFileSync(t,"utf-8").replace(/\r\n/g,"\n").split("\n").length}catch(t){return e}},0);return{ghosts:f,totalGhosts:f.length,totalWastedLines:u,wastedPercent:p>0?Math.round(u/p*1e3)/10:0,totalLines:p,breakdown:{functions:o.length,classes:r.length,consts:c.length,imports:a.length,deadClusters:l.length}}}_extractFunction(e,t,s){const n=e.trim();let i=n.match(/^(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/);return i?{name:i[1],type:"function",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?function/),i?{name:i[1],type:"const-function",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?\(?/),i&&(n.includes("=>")||t+1<s.length&&s[t+1].includes("=>"))?{name:i[1],type:"arrow",isExport:this._isExported(e,t,s),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:private\s+|public\s+|internal\s+|protected\s+)?(?:suspend\s+)?fun\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),i?{name:i[1],type:"kotlin-fun",isExport:!n.startsWith("private"),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),i?{name:i[1],type:"go-func",isExport:/^[A-Z]/.test(i[1]),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]/),i?{name:i[1],type:"rust-fn",isExport:/^pub/.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:(?:public|private|protected|static)\s+)*function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/),i?{name:i[1],type:"php-function",isExport:!/private/.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_?!]*)\s*[(\s]?/),i?{name:i[1],type:"ruby-def",isExport:/^def\s+self\./.test(n),isLifecycle:this._isLifecycle(i[1])}:(i=n.match(/^(?:async\s+)?([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*{/),i&&!["if","for","while","switch","catch","constructor","render","toString"].includes(i[1])?{name:i[1],type:"method",isExport:!1,isLifecycle:this._isLifecycle(i[1])}:null))))))))}_isExported(e,t,s){return!!/^export\s/.test(e.trim())||!!/module\.exports/.test(e)}_extractClass(e){const t=e.trim(),s=t.match(/^(?:export\s+(?:default\s+)?)?class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);return s?{name:s[1],type:"class",isExport:/^export\s/.test(t),isLifecycle:!1}:null}_extractConstDeclaration(e){const t=e.trim().match(/^(export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(.+)$/);if(!t)return null;const[,s,n,i,o]=t;return/^(?:async\s+)?function\b/.test(o)||/=>/.test(o)||""===o.trim()||/^\(/.test(o.trim())&&/=>/.test(o)||/require\s*\(/.test(o)?null:{name:i,kind:n,type:"const-declaration",isExport:!!s,isLifecycle:!1}}_extractImports(e){const t=e.trim(),s=[];let n=t.match(/^import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/);if(n){const e=n[1].split(",").map(e=>e.trim()).filter(Boolean);for(const t of e){const e=t.split(/\s+as\s+/),i=(e[1]||e[0]).trim();i&&s.push({name:i,source:n[2],type:"import"})}return s}if(n=t.match(/^import\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:,|from)/),n&&!/^import\s*\{/.test(t)){const e=t.match(/from\s*['"]([^'"]+)['"]/);return s.push({name:n[1],source:e?e[1]:"",type:"import"}),s}if(n=t.match(/^import\s*\*\s*as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*from\s*['"]([^'"]+)['"]/),n)return s.push({name:n[1],source:n[2],type:"import"}),s;if(n=t.match(/^(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/),n){const e=n[1].split(",").map(e=>e.trim()).filter(Boolean);for(const t of e){const e=t.split(":").map(e=>e.trim()),i=(e[1]||e[0]).trim();i&&s.push({name:i,source:n[2],type:"import"})}return s}return n=t.match(/^(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/),n?(s.push({name:n[1],source:n[2],type:"import"}),s):s}_findDeadClusters(e,t,s){const n=[],i=new Map;for(const t of e)t.isExport||t.isLifecycle||i.set(t.name,t);if(i.size<2)return n;const o=new Map;for(const[e,s]of i){const n=t.get(s.file);if(!n){o.set(e,new Set);continue}const r=n.split("\n").slice(s.line-1,s.line-1+s.lineCount),c=this._stripCommentsAndStrings(r.join("\n")),a=new Set;for(const[t]of i)t!==e&&new RegExp(`\\b${this._escapeRegex(t)}\\b`).test(c)&&a.add(t);o.set(e,a)}const r=new Map,c=e=>{r.has(e)||r.set(e,e);let t=e;for(;r.get(t)!==t;)t=r.get(t);let s=e;for(;r.get(s)!==t;){const e=r.get(s);r.set(s,t),s=e}return t},a=(e,t)=>{const s=c(e),n=c(t);s!==n&&r.set(s,n)};for(const[e,t]of o){c(e);for(const s of t)c(s),a(e,s)}const l=new Map;for(const e of i.keys()){const t=c(e);l.has(t)||l.set(t,[]),l.get(t).push(e)}for(const[,e]of l){if(e.length<2)continue;let t=!1;for(const s of e){for(const n of o.get(s)||[])if(e.includes(n)&&(o.get(n)||new Set).has(s)){t=!0;break}if(t)break}if(!t)continue;let r=!1;for(const t of e)if((s[t]||0)-e.reduce((e,s)=>s===t?e:e+((o.get(s)||new Set).has(t)?1:0),0)>0){r=!0;break}if(r)continue;const c=e.reduce((e,t)=>e+(i.get(t).lineCount||0),0);n.push({name:e.join(", "),file:i.get(e[0]).file,line:i.get(e[0]).line,lineCount:c,wastedLines:c,references:0,category:"dead_cluster",severity:"high",message:`Dead cluster: ${e.join(" ↔ ")} — mutually reference each other but nothing outside the cluster calls them`})}return n}_isLifecycle(e){return["constructor","render","componentDidMount","componentWillUnmount","componentDidUpdate","shouldComponentUpdate","getSnapshotBeforeUpdate","getDerivedStateFromProps","useEffect","useState","useMemo","toString","valueOf","toJSON","inspect","setup","teardown","beforeEach","afterEach","beforeAll","afterAll","init","destroy","configure","bootstrap","main","get","set","post","put","delete","patch","handle","onCreate","onStart","onResume","onPause","onStop","onDestroy","onCreateView","onViewCreated","onDestroyView","hashCode","equals","new","default","drop","fmt","from","into","clone","copy","initialize","to_s","to_str","inspect","freeze","dup","__construct","__destruct","__toString","__get","__set","__call"].includes(e)||/^__/.test(e)||/^on[A-Z]/.test(e)}_countFunctionLines(e,t){const s=(e[t]||"").trim();if(/^def\s/.test(s)){let s=1,n=1;for(let i=t+1;i<e.length&&i<t+200;i++){n++;const t=e[i].trim();if(/^(?:def|class|module|begin|case)\b/.test(t)&&s++,/^(?:if|unless|while|until|for)\b/.test(t)&&!/\bthen\b/.test(t)&&s++,/\bdo\s*(\|[^|]*\|)?\s*$/.test(t)&&s++,/^end\b/.test(t)&&s--,s<=0)break}return n}let n=0,i=!1,o=0;for(let s=t;s<e.length&&s<t+200;s++){const t=e[s];o++;for(const e of t)"{"===e&&(n++,i=!0),"}"===e&&n--;if(i&&n<=0)break}return o}_isSkippable(e){return[/\.test\./i,/\.spec\./i,/test[\/\\]/i,/spec[\/\\]/i,/__test__/i,/__mocks__/i,/\.config\./i,/\.d\.ts$/,/index\.(js|ts)$/,/server\.(js|ts)$/,/app\.(js|ts)$/,/routes?\.(js|ts)$/,/middleware/i].some(t=>t.test(e))}_escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_stripCommentsAndStrings(e){return e.replace(/`[^`\\]*(?:\\[\s\S][^`\\]*)*`/g,'""').replace(/"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"/g,'""').replace(/'[^'\\\r\n]*(?:\\.[^'\\\r\n]*)*'/g,"''").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\r\n]*/g," ").replace(/#[^\r\n]*/g," ")}}module.exports=GhostCodeDetector;
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),exportVerifier=require("./export-verifier");class HallucinationDetector{constructor(e={}){const t=new Set(["rootPath","ignorePatterns","maxFileSize"]),s={};for(const n of Object.keys(e))t.has(n)&&(s[n]=e[n]);this.config={rootPath:s.rootPath||process.cwd()},this.builtins=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib","node:fs","node:path","node:os","node:crypto","node:http","node:https","node:events","node:util","node:stream","node:child_process","node:url","node:querystring","node:buffer","node:net","node:tls","node:dns","node:readline","node:zlib","node:worker_threads","node:cluster","node:vm","node:assert","node:timers","node:timers/promises","node:test","fs/promises","stream/promises","timers/promises","dns/promises","readline/promises"]),this.phantomPackages=new Set(["node-fetch-extra","express-async","mongoose-v2","react-native-web-view","axios-retry-enhanced","lodash-extended","moment-timezone-v2","socket.io-extra","graphql-tools-v2","next-auth-v5","prisma-client-v2","tailwind-utils","react-query-v4","jest-extended-v2"]),this.phantomAPIs=[{pattern:/fs\.readFileAsync\s*\(/,suggestion:"Use fs.promises.readFile() or fs.readFileSync()",name:"fs.readFileAsync",id:"HALL_API001"},{pattern:/fs\.writeFileAsync\s*\(/,suggestion:"Use fs.promises.writeFile() or fs.writeFileSync()",name:"fs.writeFileAsync",id:"HALL_API002"},{pattern:/fs\.existsAsync\s*\(/,suggestion:"Use fs.promises.access() or fs.existsSync()",name:"fs.existsAsync",id:"HALL_API003"},{pattern:/path\.exists\s*\(/,suggestion:"Use fs.existsSync() — path module has no exists()",name:"path.exists",id:"HALL_API004"},{pattern:/path\.isFile\s*\(/,suggestion:"Use fs.statSync().isFile() — path module has no isFile()",name:"path.isFile",id:"HALL_API005"},{pattern:/path\.isDirectory\s*\(/,suggestion:"Use fs.statSync().isDirectory()",name:"path.isDirectory",id:"HALL_API006"},{pattern:/console\.success\s*\(/,suggestion:"Use console.log() — console.success() does not exist",name:"console.success",id:"HALL_API007"},{pattern:/console\.verbose\s*\(/,suggestion:"Use console.log() or console.debug()",name:"console.verbose",id:"HALL_API008"},{pattern:/JSON\.tryParse\s*\(/,suggestion:"Use try/catch with JSON.parse()",name:"JSON.tryParse",id:"HALL_API009"},{pattern:/JSON\.safeStringify\s*\(/,suggestion:"Use JSON.stringify() with a replacer",name:"JSON.safeStringify",id:"HALL_API010"},{pattern:/Array\.flatten\s*\(/,suggestion:"Use Array.prototype.flat()",name:"Array.flatten",id:"HALL_API011"},{pattern:/Object\.deepClone\s*\(/,suggestion:"Use structuredClone() or JSON.parse(JSON.stringify())",name:"Object.deepClone",id:"HALL_API012"},{pattern:/Object\.deepMerge\s*\(/,suggestion:"Use a library like lodash.merge or write a custom function",name:"Object.deepMerge",id:"HALL_API013"},{pattern:/String\.prototype\.replaceAll\s*&&.*polyfill/i,suggestion:"replaceAll() is native since ES2021 — no polyfill needed",name:"replaceAll polyfill",id:"HALL_API014"},{pattern:/require\s*\(\s*['"]fs\/sync['"]\s*\)/,suggestion:"fs/sync is not a real module — use fs directly",name:"fs/sync",id:"HALL_API015"},{pattern:/require\s*\(\s*['"]http\/server['"]\s*\)/,suggestion:"http/server is not a real module — use http.createServer()",name:"http/server",id:"HALL_API016"},{pattern:/process\.env\.get\s*\(/,suggestion:"Use process.env.VAR_NAME — process.env is a plain object, not a Map",name:"process.env.get()",id:"HALL_API017"},{pattern:/process\.exit\s*\(\s*['"]/,suggestion:"process.exit() takes a number, not a string",name:"process.exit(string)",id:"HALL_API018"}],this.pythonPhantomAPIs=[{pattern:/os\.path\.exists_sync\s*\(/,suggestion:"Use os.path.exists() — exists_sync does not exist in Python",name:"os.path.exists_sync",id:"PY_HALL001"},{pattern:/json\.tryParse\s*\(/,suggestion:"Use json.loads() with try/except",name:"json.tryParse",id:"PY_HALL002"},{pattern:/\w+\.flatMap\s*\(/,suggestion:"Python lists have no flatMap — use list comprehension or itertools.chain.from_iterable()",name:"list.flatMap",id:"PY_HALL003"},{pattern:/\w+\.merge\s*\((?!.*\bself\b)/,suggestion:"Use {**dict1, **dict2} or dict1 | dict2 (3.9+)",name:"dict.merge",id:"PY_HALL004"},{pattern:/\w+\.format_map\s*\(/,suggestion:"str.format_map exists but is rarely correct — did you mean .format()?",name:"string.format_map misuse",id:"PY_HALL005"},{pattern:/from\s+collections\s+import\s+OrderedDict.*#.*maintain\s+order/i,suggestion:"Regular dict maintains order since Python 3.7 — OrderedDict is unnecessary",name:"Unnecessary OrderedDict",id:"PY_HALL006"},{pattern:/async\s+def\s+\w+.*asyncio\.sleep\s*\(\s*0\s*\)\s*#.*yield/i,suggestion:"asyncio.sleep(0) to yield is a code smell — review async design",name:"asyncio.sleep(0) hack",id:"PY_HALL007"},{pattern:/import\s+tensorflow\.v2/,suggestion:"tensorflow.v2 is not a real module — use import tensorflow",name:"tensorflow.v2",id:"PY_HALL008"},{pattern:/from\s+sklearn\.model_selection\s+import\s+train_test_split_v2/,suggestion:"train_test_split_v2 does not exist — use train_test_split",name:"sklearn v2 hallucination",id:"PY_HALL009"},{pattern:/requests\.async_get\s*\(/,suggestion:"requests has no async_get — use aiohttp or httpx",name:"requests.async_get",id:"PY_HALL010"}],this.pythonDeprecated=[{pattern:/from\s+distutils/,suggestion:"distutils removed in Python 3.12 — use setuptools",since:"Python 3.12",name:"distutils",id:"PY_DEPR001"},{pattern:/from\s+imp\s+import/,suggestion:"imp removed in Python 3.12 — use importlib",since:"Python 3.12",name:"imp module",id:"PY_DEPR002"},{pattern:/asyncio\.get_event_loop\(\)/,suggestion:"Deprecated in 3.10+ — use asyncio.run() or get_running_loop()",since:"Python 3.10",name:"asyncio.get_event_loop()",id:"PY_DEPR003"},{pattern:/collections\.MutableMapping/,suggestion:"Moved to collections.abc.MutableMapping in Python 3.3+",since:"Python 3.9",name:"collections.MutableMapping",id:"PY_DEPR004"},{pattern:/optparse\.OptionParser/,suggestion:"optparse deprecated since Python 3.2 — use argparse",since:"Python 3.2",name:"optparse",id:"PY_DEPR005"},{pattern:/cgi\.parse_header\s*\(/,suggestion:"cgi module deprecated in Python 3.11, removed in 3.13",since:"Python 3.11",name:"cgi module",id:"PY_DEPR006"},{pattern:/from\s+typing\s+import\s+(List|Dict|Tuple|Set)\b/,suggestion:"Use built-in list, dict, tuple, set for type hints (Python 3.9+)",since:"Python 3.9",name:"typing.List/Dict/Tuple",id:"PY_DEPR007"},{pattern:/unittest\.makeSuite\s*\(/,suggestion:"makeSuite deprecated — use TestLoader.loadTestsFromTestCase",since:"Python 3.11",name:"unittest.makeSuite",id:"PY_DEPR008"}],this.pythonSmells=[{pattern:/print\s*\(\s*f?['"]\s*debug/i,id:"PY_SMELL001",name:"Debug Print",message:"Debug print statement left in code"},{pattern:/except\s*:\s*$|except\s+Exception\s*:\s*\n\s*pass/m,id:"PY_SMELL002",name:"Bare Except",message:"Bare except or swallowed exception — hides real errors"},{pattern:/#\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"PY_SMELL003",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/raise\s+NotImplementedError\s*\(?\s*\)?/,id:"PY_SMELL004",name:"Not Implemented",message:"Stub implementation — function body was not generated"},{pattern:/['"]your.api.key.here['"]|['"]sk-[.]{3,}['"]/i,id:"PY_SMELL005",name:"Dummy Credential",message:"Placeholder credential — will fail at runtime"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"PY_SMELL006",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/import\s+\*/,id:"PY_SMELL007",name:"Wildcard Import",message:"Wildcard import — pollutes namespace, hides dependencies"}],this.goDeprecated=[{pattern:/ioutil\.ReadFile\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.ReadFile()",since:"Go 1.16",name:"ioutil.ReadFile",id:"GO_DEPR001"},{pattern:/ioutil\.WriteFile\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.WriteFile()",since:"Go 1.16",name:"ioutil.WriteFile",id:"GO_DEPR002"},{pattern:/ioutil\.TempDir\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.MkdirTemp()",since:"Go 1.16",name:"ioutil.TempDir",id:"GO_DEPR003"},{pattern:/ioutil\.ReadAll\s*\(/,suggestion:"ioutil removed in Go 1.16 — use io.ReadAll()",since:"Go 1.16",name:"ioutil.ReadAll",id:"GO_DEPR004"},{pattern:/strings\.Title\s*\(/,suggestion:"strings.Title deprecated in Go 1.18 — use cases.Title from golang.org/x/text",since:"Go 1.18",name:"strings.Title",id:"GO_DEPR005"}],this.goSmells=[{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"GO_SMELL001",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/panic\s*\(\s*["']not implemented["']\s*\)/,id:"GO_SMELL002",name:"Panic Not Implemented",message:"Stub implementation — will panic at runtime"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"GO_SMELL003",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.rustPhantomAPIs=[{pattern:/std::fs::File::open_async\s*\(/,suggestion:"Use tokio::fs::File::open() for async file I/O",name:"File::open_async",id:"RS_HALL001"},{pattern:/Vec::flatten\s*\(/,suggestion:"Use .into_iter().flatten() — Vec has no flatten() method",name:"Vec::flatten",id:"RS_HALL002"},{pattern:/HashMap::get_or_default\s*\(/,suggestion:"Use .get().unwrap_or(&default) or entry().or_insert()",name:"HashMap::get_or_default",id:"RS_HALL003"},{pattern:/String::from_utf8_lossy_owned\s*\(/,suggestion:"Use String::from_utf8_lossy().into_owned()",name:"String::from_utf8_lossy_owned",id:"RS_HALL004"},{pattern:/\.async_iter\s*\(/,suggestion:"Use futures::stream::iter() from the futures crate",name:".async_iter()",id:"RS_HALL005"},{pattern:/std::net::TcpStream::connect_async\s*\(/,suggestion:"Use tokio::net::TcpStream::connect()",name:"TcpStream::connect_async",id:"RS_HALL006"},{pattern:/std::thread::sleep_async\s*\(/,suggestion:"Use tokio::time::sleep() for async sleep",name:"thread::sleep_async",id:"RS_HALL007"},{pattern:/Vec::remove_all\s*\(/,suggestion:"Use .retain(|x| condition) or .clear()",name:"Vec::remove_all",id:"RS_HALL008"},{pattern:/str::split_whitespace_n\s*\(/,suggestion:"Use .splitn(n, char::is_whitespace) instead",name:"str::split_whitespace_n",id:"RS_HALL009"},{pattern:/\.map_async\s*\(/,suggestion:"Use futures::future::join_all() or tokio::task::spawn",name:".map_async()",id:"RS_HALL010"}],this.rustDeprecated=[{pattern:/std::sync::ONCE_INIT/,suggestion:"std::sync::ONCE_INIT removed — use Once::new()",since:"Rust 1.38",name:"ONCE_INIT",id:"RS_DEPR001"},{pattern:/\bstd::mem::uninitialized\s*\(/,suggestion:"std::mem::uninitialized() removed — use MaybeUninit::uninit()",since:"Rust 1.39",name:"mem::uninitialized",id:"RS_DEPR002"},{pattern:/\btry!\s*\(/,suggestion:"try!() macro removed — use the ? operator",since:"Rust 2018",name:"try!() macro",id:"RS_DEPR003"},{pattern:/extern\s+crate\s+std\s*;/,suggestion:"extern crate std is implicit since Rust 2018 edition",since:"Rust 2018",name:"extern crate std",id:"RS_DEPR004"},{pattern:/extern\s+crate\s+alloc\s*;/,suggestion:"extern crate alloc is implicit in 2018+ edition",since:"Rust 2018",name:"extern crate alloc",id:"RS_DEPR005"},{pattern:/std::error::Error::cause\s*\(/,suggestion:".cause() deprecated — use .source() instead",since:"Rust 1.33",name:"Error::cause()",id:"RS_DEPR006"}],this.rustSmells=[{pattern:/todo!\s*\(\s*\)/,id:"RS_SMELL001",name:"todo! macro",message:"todo!() macro — will panic at runtime"},{pattern:/unimplemented!\s*\(\s*\)/,id:"RS_SMELL002",name:"unimplemented! macro",message:"unimplemented!() macro — will panic at runtime"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"RS_SMELL003",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/unwrap\(\).*unwrap\(\)/,id:"RS_SMELL004",name:"Double Unwrap",message:"Chained unwrap() — will panic on None/Err"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"RS_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/unsafe\s*\{/,id:"RS_SMELL006",name:"Unsafe Block",message:"unsafe block — verify memory safety guarantees"},{pattern:/\.unwrap\(\)\s*;/,id:"RS_SMELL007",name:"Bare unwrap()",message:".unwrap() will panic on None/Err — use ? or match"},{pattern:/println!\s*\(\s*["'].*[Dd]ebug/,id:"RS_SMELL008",name:"Debug println!",message:"Debug println! left in code — use the log crate"},{pattern:/eprintln!\s*\(\s*["'].*[Dd]ebug/,id:"RS_SMELL009",name:"Debug eprintln!",message:"Debug eprintln! left in code — use the log crate"},{pattern:/#\[allow\(dead_code\)\]/,id:"RS_SMELL010",name:"Suppressed Dead Code",message:"#[allow(dead_code)] suppresses warnings — remove unused code"}],this.javaSmells=[{pattern:/System\.out\.println\s*\(.*debug/i,id:"JAVA_SMELL001",name:"Debug Println",message:"Debug System.out.println — use a logger"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"JAVA_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/throw\s+new\s+(?:Runtime)?Exception\s*\(\s*["']Not\s+implemented["']/i,id:"JAVA_SMELL003",name:"Not Implemented",message:"Stub implementation — will throw at runtime"},{pattern:/catch\s*\(\s*Exception\s+\w+\s*\)\s*\{\s*\}/,id:"JAVA_SMELL004",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"JAVA_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.csharpSmells=[{pattern:/Console\.WriteLine\s*\(.*[Dd]ebug/i,id:"CS_SMELL001",name:"Debug WriteLine",message:"Debug Console.WriteLine — use ILogger or Debug.Write"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"CS_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/throw\s+new\s+(?:NotImplementedException)\s*\(/,id:"CS_SMELL003",name:"Not Implemented",message:"Stub implementation — will throw at runtime"},{pattern:/catch\s*\(\s*Exception\s+\w+\s*\)\s*\{\s*\}/,id:"CS_SMELL004",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"CS_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.kotlinPhantomAPIs=[{pattern:/\.flatMap\s*\{[^}]*\}(?!.*asSequence)/,suggestion:"Use .flatMap { } — verify this is not confusing sequence vs list behavior",name:"flatMap confusion",id:"KT_HALL001"},{pattern:/listOf\(\)\.stream\s*\(/,suggestion:"Kotlin lists have no .stream() — use .asSequence() or direct collection ops",name:"listOf().stream()",id:"KT_HALL002"},{pattern:/String\.format\s*\(/,suggestion:'Prefer Kotlin string templates "$variable" over String.format()',name:"String.format Java-style",id:"KT_HALL003"},{pattern:/\bObject\s*\(\s*\)/,suggestion:"Kotlin uses Any() not Object() — or use object keyword for singletons",name:"Object() Java-style",id:"KT_HALL004"},{pattern:/\.forEach\s*\(\s*::println\s*\)(?!.*debug)/i,suggestion:"println is for debug output — use a logger",name:"println via forEach",id:"KT_HALL005"},{pattern:/coroutineScope\s*\{\s*launch\s*\{[^}]*\}\s*\}(?!\s*\.join)/,suggestion:"Unjoined coroutine in coroutineScope may cause issues — ensure structured concurrency",name:"Unawaited launch",id:"KT_HALL006"},{pattern:/Dispatchers\.IO\s*\+\s*Dispatchers/,suggestion:"Combining Dispatchers is not valid — use one dispatcher at a time",name:"Combined Dispatchers",id:"KT_HALL007"},{pattern:/\.toList\(\)\.stream\(\)/,suggestion:"Use Kotlin sequences (.asSequence()) instead of .toList().stream()",name:"toList().stream()",id:"KT_HALL008"},{pattern:/companion object.*getInstance/i,suggestion:"Kotlin idiom for singletons is object keyword, not companion object + getInstance()",name:"Java-style singleton",id:"KT_HALL009"},{pattern:/lateinit var.*\?/,suggestion:"lateinit properties cannot be nullable — remove ? or use by lazy {}",name:"lateinit nullable",id:"KT_HALL010"}],this.kotlinDeprecated=[{pattern:/\bapply\s+plugin:\s*['"]kotlin-android-extensions['"]/,suggestion:"kotlin-android-extensions deprecated — use view binding or Jetpack ViewBinding",since:"Kotlin 1.8",name:"kotlin-android-extensions",id:"KT_DEPR001"},{pattern:/\bkotlinx\.android\.synthetic/,suggestion:"Synthetic imports deprecated — use view binding or findViewById",since:"Kotlin 1.8",name:"Synthetic imports",id:"KT_DEPR002"},{pattern:/\bCoroutineScope\(EmptyCoroutineContext\)/,suggestion:"EmptyCoroutineContext coroutine scope is error-prone — use viewModelScope or lifecycleScope",since:"Kotlin Coroutines 1.6",name:"EmptyCoroutineContext scope",id:"KT_DEPR003"},{pattern:/\bBuildersKt\.launch\b/,suggestion:"Internal BuildersKt APIs are deprecated — use coroutineScope { launch {} }",since:"Kotlin Coroutines 1.5",name:"BuildersKt.launch",id:"KT_DEPR004"},{pattern:/\basyncLazy\s*\{/,suggestion:"asyncLazy {} is not a standard Kotlin API — use lazy {} or async {}",since:"Kotlin 1.6",name:"asyncLazy",id:"KT_DEPR005"}],this.kotlinSmells=[{pattern:/\bprintln\s*\(/,id:"KT_SMELL001",name:"Debug println",message:"println() is for debug output — use a proper logger"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"KT_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/TODO\s*\(\s*\)/,id:"KT_SMELL003",name:"TODO() stub",message:"TODO() will throw NotImplementedError at runtime"},{pattern:/!!\s*\./,id:"KT_SMELL004",name:"Non-null assertion chain",message:"!! non-null assertion — will throw NullPointerException if null"},{pattern:/\bas\s+\w+\b(?!.*\?)/,suggestion:"Unsafe cast — prefer safe cast (as? Type) with null check",id:"KT_SMELL005",name:"Unsafe cast",message:"Unsafe cast with as — will throw ClassCastException if wrong type"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"KT_SMELL006",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/catch\s*\(\s*e:\s*Exception\s*\)\s*\{\s*\}/,id:"KT_SMELL007",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/throw\s+NotImplementedError\s*\(/,id:"KT_SMELL008",name:"Not Implemented",message:"Stub implementation — will throw at runtime"}],this.phpPhantomAPIs=[{pattern:/array_flatten\s*\(/,suggestion:"PHP has no array_flatten() — use array_merge(...$array) or a recursive function",name:"array_flatten",id:"PHP_HALL001"},{pattern:/str_contains_all\s*\(/,suggestion:"PHP has no str_contains_all() — use multiple str_contains() calls",name:"str_contains_all",id:"PHP_HALL002"},{pattern:/array_unique_values\s*\(/,suggestion:"PHP has no array_unique_values() — use array_values(array_unique())",name:"array_unique_values",id:"PHP_HALL003"},{pattern:/\$pdo->fetchAll\s*\(/,suggestion:"fetchAll() is on PDOStatement not PDO — call $stmt->fetchAll()",name:"PDO::fetchAll",id:"PHP_HALL004"},{pattern:/json_decode_safe\s*\(/,suggestion:"PHP has no json_decode_safe() — wrap json_decode() with json_last_error() check",name:"json_decode_safe",id:"PHP_HALL005"},{pattern:/str_replace_all\s*\(/,suggestion:"PHP has no str_replace_all() — use str_replace() which already replaces all occurrences",name:"str_replace_all",id:"PHP_HALL006"},{pattern:/array_map_keys\s*\(/,suggestion:"PHP has no array_map_keys() — use array_combine(array_map(...), array_keys())",name:"array_map_keys",id:"PHP_HALL007"},{pattern:/\$request->getJson\s*\(/,suggestion:'Not a standard PHP function — use json_decode(file_get_contents("php://input"))',name:"$request->getJson",id:"PHP_HALL008"},{pattern:/Date::now\s*\(/,suggestion:"PHP has no Date::now() — use new DateTime() or time()",name:"Date::now",id:"PHP_HALL009"},{pattern:/\bawait\s+/,suggestion:"PHP has no await keyword — use synchronous code or ReactPHP for async",name:"await keyword",id:"PHP_HALL010"}],this.phpDeprecated=[{pattern:/\bmysql_connect\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_connect",id:"PHP_DEPR001"},{pattern:/\bmysql_query\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_query",id:"PHP_DEPR002"},{pattern:/\bmysql_fetch_array\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_fetch_array",id:"PHP_DEPR003"},{pattern:/\bereg\s*\(/,suggestion:"ereg() removed in PHP 7 — use preg_match()",since:"PHP 7.0",name:"ereg()",id:"PHP_DEPR004"},{pattern:/\bsplit\s*\(/,suggestion:"split() removed in PHP 7 — use preg_split() or explode()",since:"PHP 7.0",name:"split()",id:"PHP_DEPR005"},{pattern:/\bcreate_function\s*\(/,suggestion:"create_function() removed in PHP 8 — use anonymous functions (closures)",since:"PHP 8.0",name:"create_function",id:"PHP_DEPR006"},{pattern:/\bmagic_quotes_gpc\b/,suggestion:"magic_quotes_gpc removed in PHP 7 — sanitize inputs manually",since:"PHP 7.0",name:"magic_quotes_gpc",id:"PHP_DEPR007"},{pattern:/\beach\s*\(/,suggestion:"each() deprecated in PHP 7.2, removed in PHP 8 — use foreach",since:"PHP 8.0",name:"each()",id:"PHP_DEPR008"},{pattern:/\bmcrypt_/,suggestion:"mcrypt removed in PHP 7.2 — use OpenSSL functions",since:"PHP 7.2",name:"mcrypt functions",id:"PHP_DEPR009"}],this.phpSmells=[{pattern:/\beval\s*\(/,id:"PHP_SMELL001",name:"eval() Usage",message:"eval() is dangerous — code injection risk"},{pattern:/\bextract\s*\(\s*\$_(?:GET|POST|REQUEST)/,id:"PHP_SMELL002",name:"extract() from superglobal",message:"extract($_GET/_POST) — variable injection vulnerability"},{pattern:/\$\$\w+/,id:"PHP_SMELL003",name:"Variable variable",message:"Variable variables ($$var) — hard to trace and injection risk"},{pattern:/\bshell_exec\s*\(/,id:"PHP_SMELL004",name:"shell_exec()",message:"shell_exec() — remote code execution risk if input unsanitized"},{pattern:/\bsystem\s*\(/,id:"PHP_SMELL005",name:"system()",message:"system() — remote code execution risk if input unsanitized"},{pattern:/\bpassthru\s*\(/,id:"PHP_SMELL006",name:"passthru()",message:"passthru() — remote code execution risk if input unsanitized"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"PHP_SMELL007",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"PHP_SMELL008",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/\$_(?:GET|POST|REQUEST)\[.*\].*SELECT.*\./i,id:"PHP_SMELL009",name:"SQL Injection Risk",message:"User input directly in SQL string — use prepared statements"},{pattern:/\bvar_dump\s*\(/,id:"PHP_SMELL010",name:"Debug var_dump",message:"var_dump() is for debug only — remove before production"}],this.rubyPhantomAPIs=[{pattern:/\.flatten_map\s*\{/,suggestion:"Ruby has no .flatten_map — use .flat_map { }",name:".flatten_map",id:"RB_HALL001"},{pattern:/Array\.of\s*\(/,suggestion:"Ruby has no Array.of() — use Array() or []",name:"Array.of()",id:"RB_HALL002"},{pattern:/Hash\.from_array\s*\(/,suggestion:"Ruby has no Hash.from_array() — use array.to_h or Hash[array]",name:"Hash.from_array",id:"RB_HALL003"},{pattern:/\.async\s*\{/,suggestion:"Ruby has no .async {} — use Thread.new or concurrent-ruby gem",name:".async block",id:"RB_HALL004"},{pattern:/String\.format\s*\(/,suggestion:"Ruby has no String.format() — use string interpolation or % operator",name:"String.format",id:"RB_HALL005"},{pattern:/\bpromise\s*\{/,suggestion:"Ruby has no built-in promise {} — use concurrent-ruby gem or Thread",name:"promise block",id:"RB_HALL006"},{pattern:/\.try!\s*\(/,suggestion:"Ruby has no .try!() — use &. (safe navigation) or Rails .try()",name:".try!()",id:"RB_HALL007"},{pattern:/JSON\.safe_parse\s*\(/,suggestion:"Ruby has no JSON.safe_parse — use JSON.parse with rescue",name:"JSON.safe_parse",id:"RB_HALL008"},{pattern:/ActiveRecord::Base\.execute\s*\(/,suggestion:"ActiveRecord::Base has no .execute() — use connection.execute() or where()",name:"Base.execute",id:"RB_HALL009"},{pattern:/\.collect_map\s*\{/,suggestion:"Ruby has no .collect_map — use .map { }.flatten(1) or .flat_map",name:".collect_map",id:"RB_HALL010"}],this.rubyDeprecated=[{pattern:/\brequire\s+['"]thread['"]/,suggestion:'require "thread" is deprecated — Thread is now built-in without require',since:"Ruby 2.0",name:'require "thread"',id:"RB_DEPR001"},{pattern:/\bObject#type\b|\.type\s*==/,suggestion:".type is deprecated — use .class or .is_a?",since:"Ruby 1.8",name:"Object#type",id:"RB_DEPR002"},{pattern:/\bERB::Util\.html_escape\b/,suggestion:"ERB::Util.html_escape deprecated — use CGI.escapeHTML or h() in views",since:"Ruby 2.6",name:"ERB::Util.html_escape",id:"RB_DEPR003"},{pattern:/\bFile\.exists\?\s*\(/,suggestion:"File.exists? deprecated — use File.exist? (no s)",since:"Ruby 2.2",name:"File.exists?",id:"RB_DEPR004"},{pattern:/\bDir\.exists\?\s*\(/,suggestion:"Dir.exists? deprecated — use Dir.exist? (no s)",since:"Ruby 2.2",name:"Dir.exists?",id:"RB_DEPR005"},{pattern:/\bObject#returning\b|\s+returning\s+/,suggestion:"Object#returning removed from Rails core — use tap { |obj| }",since:"Rails 3.0",name:"Object#returning",id:"RB_DEPR006"}],this.rubySmells=[{pattern:/\bputs\s+(?!STDOUT)/,id:"RB_SMELL001",name:"Debug puts",message:"puts is for debug output — use Rails logger or a logging library"},{pattern:/\bp\s+\w/,id:"RB_SMELL002",name:"Debug p()",message:"p() is for debug output — remove before production"},{pattern:/\beval\s*\(/,id:"RB_SMELL003",name:"eval() Usage",message:"eval() is dangerous — code injection risk"},{pattern:/\bsystem\s*\(/,id:"RB_SMELL004",name:"system() Shell Call",message:"system() call — command injection risk if input unsanitized"},{pattern:/`[^`]+`/,id:"RB_SMELL005",name:"Backtick Shell Exec",message:"Backtick shell execution — command injection risk"},{pattern:/\bexec\s*\(/,id:"RB_SMELL006",name:"exec() call",message:"exec() replaces the process — ensure this is intentional"},{pattern:/\brescue\s*$|\brescue\s+Exception\b/,id:"RB_SMELL007",name:"Bare rescue",message:"Bare rescue catches all exceptions including fatal ones — be specific"},{pattern:/["'].*#\{.*sql.*\}.*["']/i,id:"RB_SMELL008",name:"SQL String Interpolation",message:"SQL built with string interpolation — use parameterized queries"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"RB_SMELL009",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/raise\s+NotImplementedError/,id:"RB_SMELL010",name:"Not Implemented",message:"Stub implementation — will raise at runtime"}],this.jsExtensions=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs"]),this.pyExtensions=new Set([".py",".pyw"]),this.goExtensions=new Set([".go"]),this.rustExtensions=new Set([".rs"]),this.javaExtensions=new Set([".java",".kt"]),this.csharpExtensions=new Set([".cs"]),this.phpExtensions=new Set([".php"]),this.rubyExtensions=new Set([".rb"]),this.aiCodeSmells=[{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)\s*(this|here|later)/i,id:"AI_SMELL001",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished implementation"},{pattern:/throw new Error\(['"]Not implemented['"]\)/,id:"AI_SMELL002",name:"Not Implemented",message:"Stub implementation — function body was not generated"},{pattern:/\/\/\s*\.\.\.\s*(rest|remaining|more|other|additional)/i,id:"AI_SMELL003",name:"Truncated Code",message:"AI output was truncated — code is incomplete"},{pattern:/\/\/\s*(your|replace|insert|put)\s+(code|logic|implementation|api[_\s]?key)/i,id:"AI_SMELL004",name:"Template Placeholder",message:"Template placeholder left in code — needs real implementation"},{pattern:/['"]your-api-key-here['"]|['"]sk-[.]{3,}['"]|['"]xxx+['"]/i,id:"AI_SMELL005",name:"Dummy Credential",message:"Placeholder credential — will fail at runtime"},{pattern:/example\.com|test@test\.com|john@doe\.com|foo@bar\.com/i,id:"AI_SMELL006",name:"Example Domain",message:"Example domain/email in production code"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"AI_SMELL007",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.deprecatedAPIs=[{pattern:/new Buffer\s*\(/,suggestion:"Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe()",since:"Node 6",name:"new Buffer()",id:"DEPR_API001"},{pattern:/require\s*\(\s*['"]sys['"]\s*\)/,suggestion:'Use require("util") — sys was removed in Node 1.0',since:"Node 1.0",name:'require("sys")',id:"DEPR_API002"},{pattern:/fs\.exists\s*\((?!Sync)/,suggestion:"Use fs.access() or fs.stat() — fs.exists() is deprecated",since:"Node 1.0",name:"fs.exists()",id:"DEPR_API003"},{pattern:/domain\.create\s*\(/,suggestion:"Use async_hooks or try/catch — domain module is deprecated",since:"Node 4",name:"domain.create()",id:"DEPR_API004",fixable:!1},{pattern:/require\s*\(\s*['"]punycode['"]\s*\)/,suggestion:"Use userland punycode package — built-in is deprecated",since:"Node 7",name:'require("punycode")',id:"DEPR_API005",fixable:!1},{pattern:/url\.parse\s*\(/,suggestion:"Use new URL() — url.parse() is legacy",since:"Node 11",name:"url.parse()",id:"DEPR_API006"},{pattern:/querystring\.(parse|stringify)\s*\(/,suggestion:"Use URLSearchParams — querystring is legacy",since:"Node 14",name:"querystring",id:"DEPR_API007",fixable:!1},{pattern:/util\.isArray\s*\(/,suggestion:"Use Array.isArray() — util type checks are deprecated",since:"Node 4",name:"util.isArray()",id:"DEPR_API008"},{pattern:/util\.isFunction\s*\(/,suggestion:'Use typeof fn === "function"',since:"Node 4",name:"util.isFunction()",id:"DEPR_API009"},{pattern:/util\.pump\s*\(/,suggestion:"Use stream.pipeline() — util.pump() was removed",since:"Node 1.0",name:"util.pump()",id:"DEPR_API010",fixable:!1}]}async scan(e){const t=Date.now(),s={phantomImports:[],phantomAPIs:[],aiSmells:[],deprecatedAPIs:[],unresolvedDeps:[],stats:{filesScanned:0,totalIssues:0,scanTime:0}},n=this._loadDeclaredDeps(),i=this._loadIgnoreRules();for(const t of e)try{const e=path.extname(t).toLowerCase(),a=this.jsExtensions.has(e),o=this.pyExtensions.has(e),r=this.goExtensions.has(e),l=this.rustExtensions.has(e),c=this.javaExtensions.has(e),d=this.csharpExtensions.has(e),p=this.phpExtensions.has(e),m=this.rubyExtensions.has(e);if(!(a||o||r||l||c||d||p||m))continue;const u=path.relative(this.config.rootPath,t);if(i.some(e=>u.includes(e)||t.includes(e)))continue;const g=fs.readFileSync(t,"utf-8"),h=g.split("\n"),_=new Set;for(let e=0;e<h.length;e++)h[e].includes("thuban-ignore")&&(_.add(e+1),_.add(e+2));const f=this._isPatternDefinitionFile(g);s.stats.filesScanned++,a?(this._checkPhantomImports(u,t,g,h,n,s,_),f||this._checkPhantomAPIs(u,g,h,s,_),this._checkAISmells(u,g,h,s,_),f||this._checkDeprecatedAPIs(u,g,h,s,_),f||this._checkNamedExports(u,t,g,s,_)):o?(this._checkLanguagePatterns(u,g,h,s,_,this.pythonPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.pythonDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.pythonSmells)):p?(this._checkLanguagePatterns(u,g,h,s,_,this.phpPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.phpDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.phpSmells)):m?(this._checkLanguagePatterns(u,g,h,s,_,this.rubyPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.rubyDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.rubySmells)):r?(this._checkLanguagePatterns(u,g,h,s,_,this.goDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.goSmells)):l?(this._checkLanguagePatterns(u,g,h,s,_,this.rustPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.rustDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.rustSmells)):c?".kt"===e?(this._checkLanguagePatterns(u,g,h,s,_,this.kotlinPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.kotlinDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.kotlinSmells)):this._checkLanguageSmells(u,g,h,s,_,this.javaSmells):d&&this._checkLanguageSmells(u,g,h,s,_,this.csharpSmells)}catch(e){}return s.stats.totalIssues=s.phantomImports.length+s.phantomAPIs.length+s.aiSmells.length+s.deprecatedAPIs.length+s.unresolvedDeps.length,s.stats.scanTime=Date.now()-t,s}_safeRegexTest(e,t,s=1e3){const n=Date.now();try{const i=e.test(t),a=Date.now()-n;return a>s?(console.warn(`[HALLUCINATION-DETECTOR] WARNING: Regex ${e.source.substring(0,50)}... took ${a}ms on input (${t.length} chars) — skipping pattern`),null):i}catch(e){return console.warn("[HALLUCINATION-DETECTOR] Regex error during scan"),null}}_safeRegexExec(e,t,s=1e3){const n=Date.now();try{const i=e.exec(t),a=Date.now()-n;return a>s?(console.warn(`[HALLUCINATION-DETECTOR] WARNING: Regex exec ${e.source.substring(0,50)}... took ${a}ms — skipping pattern`),null):i}catch(e){return console.warn("[HALLUCINATION-DETECTOR] Regex exec error during scan"),null}}_checkLanguagePatterns(e,t,s,n,i,a,o){for(let t=0;t<s.length;t++){if(i.has(t+1))continue;const r=s[t];for(const s of a){const i=this._safeRegexTest(s.pattern,r);if(null!==i&&i){const i={file:e,line:t+1,name:s.name,id:s.id};s.suggestion&&(i.suggestion=s.suggestion),s.since&&(i.since=s.since,i.fix=s.suggestion),"deprecatedAPIs"===o?n.deprecatedAPIs.push(i):n.phantomAPIs.push(i)}}}}_checkLanguageSmells(e,t,s,n,i,a){for(let t=0;t<s.length;t++){if(i.has(t+1))continue;const o=s[t];for(const s of a){const i=this._safeRegexTest(s.pattern,o);null!==i&&i&&n.aiSmells.push({file:e,line:t+1,id:s.id,name:s.name,message:s.message,type:"ai_smell",severity:"medium"})}}}formatReport(e){const t="",s="",n="",i="",a="",o="",r="",l="";let c="";if(c+=`\n${l} ╔══════════════════════════════════════════════╗${t}\n`,c+=`${l} ║${s} THUBAN HALLUCINATION REPORT ${t}${l}║${t}\n`,c+=`${l} ╚══════════════════════════════════════════════╝${t}\n\n`,0===e.stats.totalIssues)return c+=` ${i}${s}No hallucinations detected.${t} ${r}Clean codebase.${t}\n\n`,c;if(e.phantomImports.length>0){c+=` ${n}${s}Phantom Imports (${e.phantomImports.length})${t}\n`,c+=` ${r}Packages that don't exist in package.json or node_modules${t}\n\n`;for(const s of e.phantomImports.slice(0,10))c+=` ${n}✗${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.module}${t} ${r}— ${s.reason}${t}\n`;e.phantomImports.length>10&&(c+=` ${r}... and ${e.phantomImports.length-10} more${t}\n`),c+="\n"}if(e.phantomAPIs.length>0){c+=` ${n}${s}Phantom APIs (${e.phantomAPIs.length})${t}\n`,c+=` ${r}Methods/properties that don't exist on their objects${t}\n\n`;for(const s of e.phantomAPIs.slice(0,10))c+=` ${n}✗${t} ${s.id?`${r}[${s.id}]${t} `:""}${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.name}${t} ${r}— ${s.suggestion}${t}\n`,c+=` ${r}Suppress: // thuban-ignore ${s.id||"HALL_API"}${t}\n`;e.phantomAPIs.length>10&&(c+=` ${r}... and ${e.phantomAPIs.length-10} more${t}\n`),c+="\n"}if(e.aiSmells.length>0){c+=` ${a}${s}AI Code Smells (${e.aiSmells.length})${t}\n`,c+=` ${r}Patterns typical of AI-generated code that needs review${t}\n\n`;for(const s of e.aiSmells.slice(0,10))c+=` ${a}!${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${r}${s.message}${t}\n`;e.aiSmells.length>10&&(c+=` ${r}... and ${e.aiSmells.length-10} more${t}\n`),c+="\n"}if(e.deprecatedAPIs.length>0){c+=` ${a}${s}Deprecated APIs (${e.deprecatedAPIs.length})${t}\n`,c+=` ${r}APIs that LLMs still suggest but are deprecated or removed${t}\n\n`;for(const s of e.deprecatedAPIs.slice(0,10))c+=` ${a}⚠${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.name}${t} ${r}(deprecated since ${s.since})${t}\n`,c+=` ${i}→${t} ${r}${s.suggestion}${t}\n`;e.deprecatedAPIs.length>10&&(c+=` ${r}... and ${e.deprecatedAPIs.length-10} more${t}\n`),c+="\n"}return c+=` ${s}Summary:${t} ${o}${e.stats.filesScanned}${t} files scanned, `,c+=`${e.stats.totalIssues>0?n:i}${e.stats.totalIssues}${t} hallucination issues found `,c+=`${r}(${e.stats.scanTime}ms)${t}\n\n`,c}_loadDeclaredDeps(){const e=new Set;return this._packageJsonPaths=new Map,this._collectPackageJsonDeps(this.config.rootPath,e,0),e}_collectPackageJsonDeps(e,t,s){if(!(s>5))try{const n=path.join(e,"package.json");if(fs.existsSync(n)){const s=JSON.parse(fs.readFileSync(n,"utf-8")),i=new Set;for(const e of Object.keys(s.dependencies||{}))t.add(e),i.add(e);for(const e of Object.keys(s.devDependencies||{}))t.add(e),i.add(e);for(const e of Object.keys(s.peerDependencies||{}))t.add(e),i.add(e);this._packageJsonPaths.set(e,i)}const i=new Set(["node_modules",".git","dist","build","coverage",".next",".cache","vendor"]),a=fs.readdirSync(e,{withFileTypes:!0});for(const n of a)!n.isDirectory()||i.has(n.name)||n.name.startsWith(".")||this._collectPackageJsonDeps(path.join(e,n.name),t,s+1)}catch(e){}}_checkPhantomImports(e,t,s,n,i,a,o=new Set){const r=[/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s+.*?from\s+['"]([^'"]+)['"]/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(const n of r){let r;for(;null!==(r=n.exec(s));){const n=r[1];if(n.startsWith(".")||n.startsWith("/"))continue;const l=n.split("/")[0];if(this.builtins.has(n)||this.builtins.has(l))continue;const c=n.startsWith("@")?n.split("/").slice(0,2).join("/"):l;if(!i.has(c)&&!this._findInNodeModules(t,c)){const t=this._findLineNumber(s,r.index);if(o.has(t))continue;const i=this.phantomPackages.has(n);a.phantomImports.push({file:e,line:t,module:n,reason:i?"Known AI-hallucinated package — does not exist on npm":"Not in package.json and not in node_modules",severity:i?"critical":"high",fixable:!1})}}}}_checkNamedExports(e,t,s,n,i=new Set){let a;try{a=exportVerifier.verifyFile(t,s)}catch(e){return}for(const t of a)i.has(t.line)||n.phantomImports.push({file:e,line:t.line,module:t.source,reason:t.message,severity:"critical",fixable:!1,source:"export-verifier"})}_checkPhantomAPIs(e,t,s,n,i=new Set){for(const a of this.phantomAPIs){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);if(i.has(r))continue;const l=s[r-1]||"";this._isInsidePattern(l,o[0])||n.phantomAPIs.push({file:e,line:r,name:a.name,id:a.id,suggestion:a.suggestion,severity:"high",fixable:!0,fixAction:"replace_phantom_api"})}}}_checkAISmells(e,t,s,n,i=new Set){for(const a of this.aiCodeSmells){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);i.has(r)||n.aiSmells.push({file:e,line:r,id:a.id,name:a.name,message:a.message,severity:"warning",code:s[r-1]?.trim().substring(0,100)})}}}_checkDeprecatedAPIs(e,t,s,n,i=new Set){for(const a of this.deprecatedAPIs){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);if(i.has(r))continue;const l=s[r-1]||"";this._isInsidePattern(l,o[0])||n.deprecatedAPIs.push({file:e,line:r,name:a.name,id:a.id,suggestion:a.suggestion,since:a.since,severity:"warning",fixable:!0,fixAction:"update_deprecated_api"})}}}_findLineNumber(e,t){let s=1;for(let n=0;n<t&&n<e.length;n++)"\n"===e[n]&&s++;return s}_isPatternDefinitionFile(e){const t=(e.match(/pattern:\s*\//g)||[]).length,s=(e.match(/phantom|hallucin/gi)||[]).length;return t>5&&s>2}_isInsidePattern(e,t){const s=e.trim();return!!(/pattern:\s*\//.test(s)||s.startsWith("//")||s.startsWith("*")||/(?:name|suggestion|message|description):\s*['"]/.test(s))}_loadIgnoreRules(){const e=[];try{const t=path.join(this.config.rootPath,".thubanrc.json"),s=JSON.parse(fs.readFileSync(t,"utf-8"));s.hallucination?.ignore&&e.push(...s.hallucination.ignore),s.ignore&&e.push(...s.ignore)}catch(e){}return e}_findInNodeModules(e,t){let s=path.dirname(e);const n=this.config.rootPath;for(;s.length>=n.length;){const e=path.join(s,"node_modules",t);try{if(fs.existsSync(e))return!0}catch(e){}const n=path.dirname(s);if(n===s)break;s=n}return!1}}module.exports=HallucinationDetector;
1
+ const fs=require("fs"),path=require("path"),exportVerifier=require("./export-verifier");class HallucinationDetector{constructor(e={}){const t=new Set(["rootPath","ignorePatterns","maxFileSize"]),s={};for(const n of Object.keys(e))t.has(n)&&(s[n]=e[n]);this.config={rootPath:s.rootPath||process.cwd()},this.builtins=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib","node:fs","node:path","node:os","node:crypto","node:http","node:https","node:events","node:util","node:stream","node:child_process","node:url","node:querystring","node:buffer","node:net","node:tls","node:dns","node:readline","node:zlib","node:worker_threads","node:cluster","node:vm","node:assert","node:timers","node:timers/promises","node:test","fs/promises","stream/promises","timers/promises","dns/promises","readline/promises"]),this.phantomPackages=new Set(["node-fetch-extra","express-async","mongoose-v2","react-native-web-view","axios-retry-enhanced","lodash-extended","moment-timezone-v2","socket.io-extra","graphql-tools-v2","next-auth-v5","prisma-client-v2","tailwind-utils","react-query-v4","jest-extended-v2"]),this.knownRealPackages=new Set(["express","koa","fastify","hapi","nest","@nestjs/core","@nestjs/common","next","nuxt","gatsby","remix","@remix-run/node","@remix-run/react","react","react-dom","react-native","react-router","react-router-dom","@tanstack/react-query","react-query","react-hook-form","react-redux","redux","@reduxjs/toolkit","zustand","jotai","recoil","mobx","vue","vuex","pinia","vue-router","@vue/compiler-sfc","@angular/core","@angular/common","@angular/router","@angular/forms","lodash","lodash-es","underscore","ramda","date-fns","dayjs","moment","uuid","nanoid","chalk","colors","debug","dotenv","cross-env","commander","yargs","inquirer","ora","glob","minimatch","semver","minimist","meow","execa","shelljs","fs-extra","rimraf","mkdirp","del","cpy","globby","fast-glob","chokidar","nodemon","axios","node-fetch","got","superagent","ky","undici","isomorphic-fetch","cors","helmet","body-parser","cookie-parser","compression","express-validator","joi","yup","zod","ajv","mongoose","sequelize","typeorm","prisma","@prisma/client","knex","pg","mysql","mysql2","sqlite3","better-sqlite3","redis","ioredis","mongodb","drizzle-orm","objection","bookshelf","jsonwebtoken","bcrypt","bcryptjs","passport","passport-local","passport-jwt","express-session","cookie-session","csurf","hpp","rate-limiter-flexible","express-rate-limit","next-auth","@auth/core","jest","mocha","chai","sinon","vitest","@testing-library/react","@testing-library/jest-dom","supertest","nock","cypress","playwright","@playwright/test","enzyme","nyc","istanbul","c8","ava","tap","webpack","vite","esbuild","rollup","parcel","turbo","tsup","babel-loader","@babel/core","@babel/preset-env","@babel/preset-react","@babel/preset-typescript","ts-node","tsx","typescript","tailwindcss","postcss","autoprefixer","sass","less","styled-components","@emotion/react","@emotion/styled","css-modules","classnames","clsx","winston","pino","bunyan","morgan","log4js","loglevel","sentry","@sentry/node","@sentry/react","newrelic","datadog-metrics","aws-sdk","@aws-sdk/client-s3","@aws-sdk/client-dynamodb","@google-cloud/storage","@google-cloud/pubsub","@google-cloud/firestore","firebase","firebase-admin","@supabase/supabase-js","socket.io","socket.io-client","ws","mqtt","amqplib","bull","bullmq","multer","sharp","jimp","formidable","busboy","csv-parse","csv-parser","papaparse","xlsx","exceljs","pdfkit","puppeteer","cheerio","jsdom","graphql","apollo-server","@apollo/server","@apollo/client","graphql-tag","type-graphql","graphql-yoga","urql","async","bluebird","rxjs","immutable","immer","p-limit","p-queue","eventemitter3","mitt","cron","node-cron","agenda","handlebars","ejs","pug","nunjucks","mustache","marked","markdown-it","remark","rehype","unified","nodemailer","twilio","stripe","@stripe/stripe-js","i18next","intl","i18n","luxon","eslint","prettier","stylelint","lint-staged","husky","lerna","nx","@nrwl/workspace","changesets","@changesets/cli"]),this.phantomAPIs=[{pattern:/fs\.readFileAsync\s*\(/,suggestion:"Use fs.promises.readFile() or fs.readFileSync()",name:"fs.readFileAsync",id:"HALL_API001"},{pattern:/fs\.writeFileAsync\s*\(/,suggestion:"Use fs.promises.writeFile() or fs.writeFileSync()",name:"fs.writeFileAsync",id:"HALL_API002"},{pattern:/fs\.existsAsync\s*\(/,suggestion:"Use fs.promises.access() or fs.existsSync()",name:"fs.existsAsync",id:"HALL_API003"},{pattern:/path\.exists\s*\(/,suggestion:"Use fs.existsSync() — path module has no exists()",name:"path.exists",id:"HALL_API004"},{pattern:/path\.isFile\s*\(/,suggestion:"Use fs.statSync().isFile() — path module has no isFile()",name:"path.isFile",id:"HALL_API005"},{pattern:/path\.isDirectory\s*\(/,suggestion:"Use fs.statSync().isDirectory()",name:"path.isDirectory",id:"HALL_API006"},{pattern:/console\.success\s*\(/,suggestion:"Use console.log() — console.success() does not exist",name:"console.success",id:"HALL_API007"},{pattern:/console\.verbose\s*\(/,suggestion:"Use console.log() or console.debug()",name:"console.verbose",id:"HALL_API008"},{pattern:/JSON\.tryParse\s*\(/,suggestion:"Use try/catch with JSON.parse()",name:"JSON.tryParse",id:"HALL_API009"},{pattern:/JSON\.safeStringify\s*\(/,suggestion:"Use JSON.stringify() with a replacer",name:"JSON.safeStringify",id:"HALL_API010"},{pattern:/Array\.flatten\s*\(/,suggestion:"Use Array.prototype.flat()",name:"Array.flatten",id:"HALL_API011"},{pattern:/Object\.deepClone\s*\(/,suggestion:"Use structuredClone() or JSON.parse(JSON.stringify())",name:"Object.deepClone",id:"HALL_API012"},{pattern:/Object\.deepMerge\s*\(/,suggestion:"Use a library like lodash.merge or write a custom function",name:"Object.deepMerge",id:"HALL_API013"},{pattern:/String\.prototype\.replaceAll\s*&&.*polyfill/i,suggestion:"replaceAll() is native since ES2021 — no polyfill needed",name:"replaceAll polyfill",id:"HALL_API014"},{pattern:/require\s*\(\s*['"]fs\/sync['"]\s*\)/,suggestion:"fs/sync is not a real module — use fs directly",name:"fs/sync",id:"HALL_API015"},{pattern:/require\s*\(\s*['"]http\/server['"]\s*\)/,suggestion:"http/server is not a real module — use http.createServer()",name:"http/server",id:"HALL_API016"},{pattern:/process\.env\.get\s*\(/,suggestion:"Use process.env.VAR_NAME — process.env is a plain object, not a Map",name:"process.env.get()",id:"HALL_API017"},{pattern:/process\.exit\s*\(\s*['"]/,suggestion:"process.exit() takes a number, not a string",name:"process.exit(string)",id:"HALL_API018"}],this.pythonPhantomAPIs=[{pattern:/os\.path\.exists_sync\s*\(/,suggestion:"Use os.path.exists() — exists_sync does not exist in Python",name:"os.path.exists_sync",id:"PY_HALL001"},{pattern:/json\.tryParse\s*\(/,suggestion:"Use json.loads() with try/except",name:"json.tryParse",id:"PY_HALL002"},{pattern:/\w+\.flatMap\s*\(/,suggestion:"Python lists have no flatMap — use list comprehension or itertools.chain.from_iterable()",name:"list.flatMap",id:"PY_HALL003"},{pattern:/\w+\.merge\s*\((?!.*\bself\b)/,suggestion:"Use {**dict1, **dict2} or dict1 | dict2 (3.9+)",name:"dict.merge",id:"PY_HALL004"},{pattern:/\w+\.format_map\s*\(/,suggestion:"str.format_map exists but is rarely correct — did you mean .format()?",name:"string.format_map misuse",id:"PY_HALL005"},{pattern:/from\s+collections\s+import\s+OrderedDict.*#.*maintain\s+order/i,suggestion:"Regular dict maintains order since Python 3.7 — OrderedDict is unnecessary",name:"Unnecessary OrderedDict",id:"PY_HALL006"},{pattern:/async\s+def\s+\w+.*asyncio\.sleep\s*\(\s*0\s*\)\s*#.*yield/i,suggestion:"asyncio.sleep(0) to yield is a code smell — review async design",name:"asyncio.sleep(0) hack",id:"PY_HALL007"},{pattern:/import\s+tensorflow\.v2/,suggestion:"tensorflow.v2 is not a real module — use import tensorflow",name:"tensorflow.v2",id:"PY_HALL008"},{pattern:/from\s+sklearn\.model_selection\s+import\s+train_test_split_v2/,suggestion:"train_test_split_v2 does not exist — use train_test_split",name:"sklearn v2 hallucination",id:"PY_HALL009"},{pattern:/requests\.async_get\s*\(/,suggestion:"requests has no async_get — use aiohttp or httpx",name:"requests.async_get",id:"PY_HALL010"}],this.pythonDeprecated=[{pattern:/from\s+distutils/,suggestion:"distutils removed in Python 3.12 — use setuptools",since:"Python 3.12",name:"distutils",id:"PY_DEPR001"},{pattern:/from\s+imp\s+import/,suggestion:"imp removed in Python 3.12 — use importlib",since:"Python 3.12",name:"imp module",id:"PY_DEPR002"},{pattern:/asyncio\.get_event_loop\(\)/,suggestion:"Deprecated in 3.10+ — use asyncio.run() or get_running_loop()",since:"Python 3.10",name:"asyncio.get_event_loop()",id:"PY_DEPR003"},{pattern:/collections\.MutableMapping/,suggestion:"Moved to collections.abc.MutableMapping in Python 3.3+",since:"Python 3.9",name:"collections.MutableMapping",id:"PY_DEPR004"},{pattern:/optparse\.OptionParser/,suggestion:"optparse deprecated since Python 3.2 — use argparse",since:"Python 3.2",name:"optparse",id:"PY_DEPR005"},{pattern:/cgi\.parse_header\s*\(/,suggestion:"cgi module deprecated in Python 3.11, removed in 3.13",since:"Python 3.11",name:"cgi module",id:"PY_DEPR006"},{pattern:/from\s+typing\s+import\s+(List|Dict|Tuple|Set)\b/,suggestion:"Use built-in list, dict, tuple, set for type hints (Python 3.9+)",since:"Python 3.9",name:"typing.List/Dict/Tuple",id:"PY_DEPR007"},{pattern:/unittest\.makeSuite\s*\(/,suggestion:"makeSuite deprecated — use TestLoader.loadTestsFromTestCase",since:"Python 3.11",name:"unittest.makeSuite",id:"PY_DEPR008"}],this.pythonSmells=[{pattern:/print\s*\(\s*f?['"]\s*debug/i,id:"PY_SMELL001",name:"Debug Print",message:"Debug print statement left in code"},{pattern:/except\s*:\s*$|except\s+Exception\s*:\s*\n\s*pass/m,id:"PY_SMELL002",name:"Bare Except",message:"Bare except or swallowed exception — hides real errors"},{pattern:/#\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"PY_SMELL003",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/raise\s+NotImplementedError\s*\(?\s*\)?/,id:"PY_SMELL004",name:"Not Implemented",message:"Stub implementation — function body was not generated"},{pattern:/['"]your.api.key.here['"]|['"]sk-[.]{3,}['"]/i,id:"PY_SMELL005",name:"Dummy Credential",message:"Placeholder credential — will fail at runtime"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"PY_SMELL006",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/import\s+\*/,id:"PY_SMELL007",name:"Wildcard Import",message:"Wildcard import — pollutes namespace, hides dependencies"}],this.goDeprecated=[{pattern:/ioutil\.ReadFile\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.ReadFile()",since:"Go 1.16",name:"ioutil.ReadFile",id:"GO_DEPR001"},{pattern:/ioutil\.WriteFile\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.WriteFile()",since:"Go 1.16",name:"ioutil.WriteFile",id:"GO_DEPR002"},{pattern:/ioutil\.TempDir\s*\(/,suggestion:"ioutil removed in Go 1.16 — use os.MkdirTemp()",since:"Go 1.16",name:"ioutil.TempDir",id:"GO_DEPR003"},{pattern:/ioutil\.ReadAll\s*\(/,suggestion:"ioutil removed in Go 1.16 — use io.ReadAll()",since:"Go 1.16",name:"ioutil.ReadAll",id:"GO_DEPR004"},{pattern:/strings\.Title\s*\(/,suggestion:"strings.Title deprecated in Go 1.18 — use cases.Title from golang.org/x/text",since:"Go 1.18",name:"strings.Title",id:"GO_DEPR005"}],this.goSmells=[{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"GO_SMELL001",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/panic\s*\(\s*["']not implemented["']\s*\)/,id:"GO_SMELL002",name:"Panic Not Implemented",message:"Stub implementation — will panic at runtime"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"GO_SMELL003",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.rustPhantomAPIs=[{pattern:/std::fs::File::open_async\s*\(/,suggestion:"Use tokio::fs::File::open() for async file I/O",name:"File::open_async",id:"RS_HALL001"},{pattern:/Vec::flatten\s*\(/,suggestion:"Use .into_iter().flatten() — Vec has no flatten() method",name:"Vec::flatten",id:"RS_HALL002"},{pattern:/HashMap::get_or_default\s*\(/,suggestion:"Use .get().unwrap_or(&default) or entry().or_insert()",name:"HashMap::get_or_default",id:"RS_HALL003"},{pattern:/String::from_utf8_lossy_owned\s*\(/,suggestion:"Use String::from_utf8_lossy().into_owned()",name:"String::from_utf8_lossy_owned",id:"RS_HALL004"},{pattern:/\.async_iter\s*\(/,suggestion:"Use futures::stream::iter() from the futures crate",name:".async_iter()",id:"RS_HALL005"},{pattern:/std::net::TcpStream::connect_async\s*\(/,suggestion:"Use tokio::net::TcpStream::connect()",name:"TcpStream::connect_async",id:"RS_HALL006"},{pattern:/std::thread::sleep_async\s*\(/,suggestion:"Use tokio::time::sleep() for async sleep",name:"thread::sleep_async",id:"RS_HALL007"},{pattern:/Vec::remove_all\s*\(/,suggestion:"Use .retain(|x| condition) or .clear()",name:"Vec::remove_all",id:"RS_HALL008"},{pattern:/str::split_whitespace_n\s*\(/,suggestion:"Use .splitn(n, char::is_whitespace) instead",name:"str::split_whitespace_n",id:"RS_HALL009"},{pattern:/\.map_async\s*\(/,suggestion:"Use futures::future::join_all() or tokio::task::spawn",name:".map_async()",id:"RS_HALL010"}],this.rustDeprecated=[{pattern:/std::sync::ONCE_INIT/,suggestion:"std::sync::ONCE_INIT removed — use Once::new()",since:"Rust 1.38",name:"ONCE_INIT",id:"RS_DEPR001"},{pattern:/\bstd::mem::uninitialized\s*\(/,suggestion:"std::mem::uninitialized() removed — use MaybeUninit::uninit()",since:"Rust 1.39",name:"mem::uninitialized",id:"RS_DEPR002"},{pattern:/\btry!\s*\(/,suggestion:"try!() macro removed — use the ? operator",since:"Rust 2018",name:"try!() macro",id:"RS_DEPR003"},{pattern:/extern\s+crate\s+std\s*;/,suggestion:"extern crate std is implicit since Rust 2018 edition",since:"Rust 2018",name:"extern crate std",id:"RS_DEPR004"},{pattern:/extern\s+crate\s+alloc\s*;/,suggestion:"extern crate alloc is implicit in 2018+ edition",since:"Rust 2018",name:"extern crate alloc",id:"RS_DEPR005"},{pattern:/std::error::Error::cause\s*\(/,suggestion:".cause() deprecated — use .source() instead",since:"Rust 1.33",name:"Error::cause()",id:"RS_DEPR006"}],this.rustSmells=[{pattern:/todo!\s*\(\s*\)/,id:"RS_SMELL001",name:"todo! macro",message:"todo!() macro — will panic at runtime"},{pattern:/unimplemented!\s*\(\s*\)/,id:"RS_SMELL002",name:"unimplemented! macro",message:"unimplemented!() macro — will panic at runtime"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"RS_SMELL003",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/unwrap\(\).*unwrap\(\)/,id:"RS_SMELL004",name:"Double Unwrap",message:"Chained unwrap() — will panic on None/Err"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"RS_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/unsafe\s*\{/,id:"RS_SMELL006",name:"Unsafe Block",message:"unsafe block — verify memory safety guarantees"},{pattern:/\.unwrap\(\)\s*;/,id:"RS_SMELL007",name:"Bare unwrap()",message:".unwrap() will panic on None/Err — use ? or match"},{pattern:/println!\s*\(\s*["'].*[Dd]ebug/,id:"RS_SMELL008",name:"Debug println!",message:"Debug println! left in code — use the log crate"},{pattern:/eprintln!\s*\(\s*["'].*[Dd]ebug/,id:"RS_SMELL009",name:"Debug eprintln!",message:"Debug eprintln! left in code — use the log crate"},{pattern:/#\[allow\(dead_code\)\]/,id:"RS_SMELL010",name:"Suppressed Dead Code",message:"#[allow(dead_code)] suppresses warnings — remove unused code"}],this.javaSmells=[{pattern:/System\.out\.println\s*\(.*debug/i,id:"JAVA_SMELL001",name:"Debug Println",message:"Debug System.out.println — use a logger"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"JAVA_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/throw\s+new\s+(?:Runtime)?Exception\s*\(\s*["']Not\s+implemented["']/i,id:"JAVA_SMELL003",name:"Not Implemented",message:"Stub implementation — will throw at runtime"},{pattern:/catch\s*\(\s*Exception\s+\w+\s*\)\s*\{\s*\}/,id:"JAVA_SMELL004",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"JAVA_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.csharpSmells=[{pattern:/Console\.WriteLine\s*\(.*[Dd]ebug/i,id:"CS_SMELL001",name:"Debug WriteLine",message:"Debug Console.WriteLine — use ILogger or Debug.Write"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"CS_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/throw\s+new\s+(?:NotImplementedException)\s*\(/,id:"CS_SMELL003",name:"Not Implemented",message:"Stub implementation — will throw at runtime"},{pattern:/catch\s*\(\s*Exception\s+\w+\s*\)\s*\{\s*\}/,id:"CS_SMELL004",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"CS_SMELL005",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.kotlinPhantomAPIs=[{pattern:/\.flatMap\s*\{[^}]*\}(?!.*asSequence)/,suggestion:"Use .flatMap { } — verify this is not confusing sequence vs list behavior",name:"flatMap confusion",id:"KT_HALL001"},{pattern:/listOf\(\)\.stream\s*\(/,suggestion:"Kotlin lists have no .stream() — use .asSequence() or direct collection ops",name:"listOf().stream()",id:"KT_HALL002"},{pattern:/String\.format\s*\(/,suggestion:'Prefer Kotlin string templates "$variable" over String.format()',name:"String.format Java-style",id:"KT_HALL003"},{pattern:/\bObject\s*\(\s*\)/,suggestion:"Kotlin uses Any() not Object() — or use object keyword for singletons",name:"Object() Java-style",id:"KT_HALL004"},{pattern:/\.forEach\s*\(\s*::println\s*\)(?!.*debug)/i,suggestion:"println is for debug output — use a logger",name:"println via forEach",id:"KT_HALL005"},{pattern:/coroutineScope\s*\{\s*launch\s*\{[^}]*\}\s*\}(?!\s*\.join)/,suggestion:"Unjoined coroutine in coroutineScope may cause issues — ensure structured concurrency",name:"Unawaited launch",id:"KT_HALL006"},{pattern:/Dispatchers\.IO\s*\+\s*Dispatchers/,suggestion:"Combining Dispatchers is not valid — use one dispatcher at a time",name:"Combined Dispatchers",id:"KT_HALL007"},{pattern:/\.toList\(\)\.stream\(\)/,suggestion:"Use Kotlin sequences (.asSequence()) instead of .toList().stream()",name:"toList().stream()",id:"KT_HALL008"},{pattern:/companion object.*getInstance/i,suggestion:"Kotlin idiom for singletons is object keyword, not companion object + getInstance()",name:"Java-style singleton",id:"KT_HALL009"},{pattern:/lateinit var.*\?/,suggestion:"lateinit properties cannot be nullable — remove ? or use by lazy {}",name:"lateinit nullable",id:"KT_HALL010"}],this.kotlinDeprecated=[{pattern:/\bapply\s+plugin:\s*['"]kotlin-android-extensions['"]/,suggestion:"kotlin-android-extensions deprecated — use view binding or Jetpack ViewBinding",since:"Kotlin 1.8",name:"kotlin-android-extensions",id:"KT_DEPR001"},{pattern:/\bkotlinx\.android\.synthetic/,suggestion:"Synthetic imports deprecated — use view binding or findViewById",since:"Kotlin 1.8",name:"Synthetic imports",id:"KT_DEPR002"},{pattern:/\bCoroutineScope\(EmptyCoroutineContext\)/,suggestion:"EmptyCoroutineContext coroutine scope is error-prone — use viewModelScope or lifecycleScope",since:"Kotlin Coroutines 1.6",name:"EmptyCoroutineContext scope",id:"KT_DEPR003"},{pattern:/\bBuildersKt\.launch\b/,suggestion:"Internal BuildersKt APIs are deprecated — use coroutineScope { launch {} }",since:"Kotlin Coroutines 1.5",name:"BuildersKt.launch",id:"KT_DEPR004"},{pattern:/\basyncLazy\s*\{/,suggestion:"asyncLazy {} is not a standard Kotlin API — use lazy {} or async {}",since:"Kotlin 1.6",name:"asyncLazy",id:"KT_DEPR005"}],this.kotlinSmells=[{pattern:/\bprintln\s*\(/,id:"KT_SMELL001",name:"Debug println",message:"println() is for debug output — use a proper logger"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"KT_SMELL002",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/TODO\s*\(\s*\)/,id:"KT_SMELL003",name:"TODO() stub",message:"TODO() will throw NotImplementedError at runtime"},{pattern:/!!\s*\./,id:"KT_SMELL004",name:"Non-null assertion chain",message:"!! non-null assertion — will throw NullPointerException if null"},{pattern:/\bas\s+\w+\b(?!.*\?)/,suggestion:"Unsafe cast — prefer safe cast (as? Type) with null check",id:"KT_SMELL005",name:"Unsafe cast",message:"Unsafe cast with as — will throw ClassCastException if wrong type"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"KT_SMELL006",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/catch\s*\(\s*e:\s*Exception\s*\)\s*\{\s*\}/,id:"KT_SMELL007",name:"Empty Catch",message:"Empty catch block — swallows all exceptions"},{pattern:/throw\s+NotImplementedError\s*\(/,id:"KT_SMELL008",name:"Not Implemented",message:"Stub implementation — will throw at runtime"}],this.phpPhantomAPIs=[{pattern:/array_flatten\s*\(/,suggestion:"PHP has no array_flatten() — use array_merge(...$array) or a recursive function",name:"array_flatten",id:"PHP_HALL001"},{pattern:/str_contains_all\s*\(/,suggestion:"PHP has no str_contains_all() — use multiple str_contains() calls",name:"str_contains_all",id:"PHP_HALL002"},{pattern:/array_unique_values\s*\(/,suggestion:"PHP has no array_unique_values() — use array_values(array_unique())",name:"array_unique_values",id:"PHP_HALL003"},{pattern:/\$pdo->fetchAll\s*\(/,suggestion:"fetchAll() is on PDOStatement not PDO — call $stmt->fetchAll()",name:"PDO::fetchAll",id:"PHP_HALL004"},{pattern:/json_decode_safe\s*\(/,suggestion:"PHP has no json_decode_safe() — wrap json_decode() with json_last_error() check",name:"json_decode_safe",id:"PHP_HALL005"},{pattern:/str_replace_all\s*\(/,suggestion:"PHP has no str_replace_all() — use str_replace() which already replaces all occurrences",name:"str_replace_all",id:"PHP_HALL006"},{pattern:/array_map_keys\s*\(/,suggestion:"PHP has no array_map_keys() — use array_combine(array_map(...), array_keys())",name:"array_map_keys",id:"PHP_HALL007"},{pattern:/\$request->getJson\s*\(/,suggestion:'Not a standard PHP function — use json_decode(file_get_contents("php://input"))',name:"$request->getJson",id:"PHP_HALL008"},{pattern:/Date::now\s*\(/,suggestion:"PHP has no Date::now() — use new DateTime() or time()",name:"Date::now",id:"PHP_HALL009"},{pattern:/\bawait\s+/,suggestion:"PHP has no await keyword — use synchronous code or ReactPHP for async",name:"await keyword",id:"PHP_HALL010"}],this.phpDeprecated=[{pattern:/\bmysql_connect\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_connect",id:"PHP_DEPR001"},{pattern:/\bmysql_query\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_query",id:"PHP_DEPR002"},{pattern:/\bmysql_fetch_array\s*\(/,suggestion:"mysql_* functions removed in PHP 7 — use PDO or MySQLi",since:"PHP 7.0",name:"mysql_fetch_array",id:"PHP_DEPR003"},{pattern:/\bereg\s*\(/,suggestion:"ereg() removed in PHP 7 — use preg_match()",since:"PHP 7.0",name:"ereg()",id:"PHP_DEPR004"},{pattern:/\bsplit\s*\(/,suggestion:"split() removed in PHP 7 — use preg_split() or explode()",since:"PHP 7.0",name:"split()",id:"PHP_DEPR005"},{pattern:/\bcreate_function\s*\(/,suggestion:"create_function() removed in PHP 8 — use anonymous functions (closures)",since:"PHP 8.0",name:"create_function",id:"PHP_DEPR006"},{pattern:/\bmagic_quotes_gpc\b/,suggestion:"magic_quotes_gpc removed in PHP 7 — sanitize inputs manually",since:"PHP 7.0",name:"magic_quotes_gpc",id:"PHP_DEPR007"},{pattern:/\beach\s*\(/,suggestion:"each() deprecated in PHP 7.2, removed in PHP 8 — use foreach",since:"PHP 8.0",name:"each()",id:"PHP_DEPR008"},{pattern:/\bmcrypt_/,suggestion:"mcrypt removed in PHP 7.2 — use OpenSSL functions",since:"PHP 7.2",name:"mcrypt functions",id:"PHP_DEPR009"}],this.phpSmells=[{pattern:/\beval\s*\(/,id:"PHP_SMELL001",name:"eval() Usage",message:"eval() is dangerous — code injection risk"},{pattern:/\bextract\s*\(\s*\$_(?:GET|POST|REQUEST)/,id:"PHP_SMELL002",name:"extract() from superglobal",message:"extract($_GET/_POST) — variable injection vulnerability"},{pattern:/\$\$\w+/,id:"PHP_SMELL003",name:"Variable variable",message:"Variable variables ($$var) — hard to trace and injection risk"},{pattern:/\bshell_exec\s*\(/,id:"PHP_SMELL004",name:"shell_exec()",message:"shell_exec() — remote code execution risk if input unsanitized"},{pattern:/\bsystem\s*\(/,id:"PHP_SMELL005",name:"system()",message:"system() — remote code execution risk if input unsanitized"},{pattern:/\bpassthru\s*\(/,id:"PHP_SMELL006",name:"passthru()",message:"passthru() — remote code execution risk if input unsanitized"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"PHP_SMELL007",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"PHP_SMELL008",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"},{pattern:/\$_(?:GET|POST|REQUEST)\[.*\].*SELECT.*\./i,id:"PHP_SMELL009",name:"SQL Injection Risk",message:"User input directly in SQL string — use prepared statements"},{pattern:/\bvar_dump\s*\(/,id:"PHP_SMELL010",name:"Debug var_dump",message:"var_dump() is for debug only — remove before production"}],this.rubyPhantomAPIs=[{pattern:/\.flatten_map\s*\{/,suggestion:"Ruby has no .flatten_map — use .flat_map { }",name:".flatten_map",id:"RB_HALL001"},{pattern:/Array\.of\s*\(/,suggestion:"Ruby has no Array.of() — use Array() or []",name:"Array.of()",id:"RB_HALL002"},{pattern:/Hash\.from_array\s*\(/,suggestion:"Ruby has no Hash.from_array() — use array.to_h or Hash[array]",name:"Hash.from_array",id:"RB_HALL003"},{pattern:/\.async\s*\{/,suggestion:"Ruby has no .async {} — use Thread.new or concurrent-ruby gem",name:".async block",id:"RB_HALL004"},{pattern:/String\.format\s*\(/,suggestion:"Ruby has no String.format() — use string interpolation or % operator",name:"String.format",id:"RB_HALL005"},{pattern:/\bpromise\s*\{/,suggestion:"Ruby has no built-in promise {} — use concurrent-ruby gem or Thread",name:"promise block",id:"RB_HALL006"},{pattern:/\.try!\s*\(/,suggestion:"Ruby has no .try!() — use &. (safe navigation) or Rails .try()",name:".try!()",id:"RB_HALL007"},{pattern:/JSON\.safe_parse\s*\(/,suggestion:"Ruby has no JSON.safe_parse — use JSON.parse with rescue",name:"JSON.safe_parse",id:"RB_HALL008"},{pattern:/ActiveRecord::Base\.execute\s*\(/,suggestion:"ActiveRecord::Base has no .execute() — use connection.execute() or where()",name:"Base.execute",id:"RB_HALL009"},{pattern:/\.collect_map\s*\{/,suggestion:"Ruby has no .collect_map — use .map { }.flatten(1) or .flat_map",name:".collect_map",id:"RB_HALL010"}],this.rubyDeprecated=[{pattern:/\brequire\s+['"]thread['"]/,suggestion:'require "thread" is deprecated — Thread is now built-in without require',since:"Ruby 2.0",name:'require "thread"',id:"RB_DEPR001"},{pattern:/\bObject#type\b|\.type\s*==/,suggestion:".type is deprecated — use .class or .is_a?",since:"Ruby 1.8",name:"Object#type",id:"RB_DEPR002"},{pattern:/\bERB::Util\.html_escape\b/,suggestion:"ERB::Util.html_escape deprecated — use CGI.escapeHTML or h() in views",since:"Ruby 2.6",name:"ERB::Util.html_escape",id:"RB_DEPR003"},{pattern:/\bFile\.exists\?\s*\(/,suggestion:"File.exists? deprecated — use File.exist? (no s)",since:"Ruby 2.2",name:"File.exists?",id:"RB_DEPR004"},{pattern:/\bDir\.exists\?\s*\(/,suggestion:"Dir.exists? deprecated — use Dir.exist? (no s)",since:"Ruby 2.2",name:"Dir.exists?",id:"RB_DEPR005"},{pattern:/\bObject#returning\b|\s+returning\s+/,suggestion:"Object#returning removed from Rails core — use tap { |obj| }",since:"Rails 3.0",name:"Object#returning",id:"RB_DEPR006"}],this.rubySmells=[{pattern:/\bputs\s+(?!STDOUT)/,id:"RB_SMELL001",name:"Debug puts",message:"puts is for debug output — use Rails logger or a logging library"},{pattern:/\bp\s+\w/,id:"RB_SMELL002",name:"Debug p()",message:"p() is for debug output — remove before production"},{pattern:/\beval\s*\(/,id:"RB_SMELL003",name:"eval() Usage",message:"eval() is dangerous — code injection risk"},{pattern:/\bsystem\s*\(/,id:"RB_SMELL004",name:"system() Shell Call",message:"system() call — command injection risk if input unsanitized"},{pattern:/`[^`]+`/,id:"RB_SMELL005",name:"Backtick Shell Exec",message:"Backtick shell execution — command injection risk"},{pattern:/\bexec\s*\(/,id:"RB_SMELL006",name:"exec() call",message:"exec() replaces the process — ensure this is intentional"},{pattern:/\brescue\s*$|\brescue\s+Exception\b/,id:"RB_SMELL007",name:"Bare rescue",message:"Bare rescue catches all exceptions including fatal ones — be specific"},{pattern:/["'].*#\{.*sql.*\}.*["']/i,id:"RB_SMELL008",name:"SQL String Interpolation",message:"SQL built with string interpolation — use parameterized queries"},{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)/i,id:"RB_SMELL009",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished"},{pattern:/raise\s+NotImplementedError/,id:"RB_SMELL010",name:"Not Implemented",message:"Stub implementation — will raise at runtime"}],this.jsExtensions=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs"]),this.pyExtensions=new Set([".py",".pyw"]),this.goExtensions=new Set([".go"]),this.rustExtensions=new Set([".rs"]),this.javaExtensions=new Set([".java",".kt"]),this.csharpExtensions=new Set([".cs"]),this.phpExtensions=new Set([".php"]),this.rubyExtensions=new Set([".rb"]),this.aiCodeSmells=[{pattern:/\/\/\s*TODO:?\s*(implement|add|fix|complete|finish)\s*(this|here|later)/i,id:"AI_SMELL001",name:"Placeholder TODO",message:"AI-generated placeholder — likely unfinished implementation"},{pattern:/throw new Error\(['"]Not implemented['"]\)/,id:"AI_SMELL002",name:"Not Implemented",message:"Stub implementation — function body was not generated"},{pattern:/\/\/\s*\.\.\.\s*(rest|remaining|more|other|additional)/i,id:"AI_SMELL003",name:"Truncated Code",message:"AI output was truncated — code is incomplete"},{pattern:/\/\/\s*(your|replace|insert|put)\s+(code|logic|implementation|api[_\s]?key)/i,id:"AI_SMELL004",name:"Template Placeholder",message:"Template placeholder left in code — needs real implementation"},{pattern:/['"]your-api-key-here['"]|['"]sk-[.]{3,}['"]|['"]xxx+['"]/i,id:"AI_SMELL005",name:"Dummy Credential",message:"Placeholder credential — will fail at runtime"},{pattern:/example\.com|test@test\.com|john@doe\.com|foo@bar\.com/i,id:"AI_SMELL006",name:"Example Domain",message:"Example domain/email in production code"},{pattern:/localhost:\d{4}(?!.*(?:dev|test|local|development))/i,id:"AI_SMELL007",name:"Hardcoded Localhost",message:"Hardcoded localhost URL — will fail in production"}],this.deprecatedAPIs=[{pattern:/new Buffer\s*\(/,suggestion:"Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe()",since:"Node 6",name:"new Buffer()",id:"DEPR_API001"},{pattern:/require\s*\(\s*['"]sys['"]\s*\)/,suggestion:'Use require("util") — sys was removed in Node 1.0',since:"Node 1.0",name:'require("sys")',id:"DEPR_API002"},{pattern:/fs\.exists\s*\((?!Sync)/,suggestion:"Use fs.access() or fs.stat() — fs.exists() is deprecated",since:"Node 1.0",name:"fs.exists()",id:"DEPR_API003"},{pattern:/domain\.create\s*\(/,suggestion:"Use async_hooks or try/catch — domain module is deprecated",since:"Node 4",name:"domain.create()",id:"DEPR_API004",fixable:!1},{pattern:/require\s*\(\s*['"]punycode['"]\s*\)/,suggestion:"Use userland punycode package — built-in is deprecated",since:"Node 7",name:'require("punycode")',id:"DEPR_API005",fixable:!1},{pattern:/url\.parse\s*\(/,suggestion:"Use new URL() — url.parse() is legacy",since:"Node 11",name:"url.parse()",id:"DEPR_API006"},{pattern:/querystring\.(parse|stringify)\s*\(/,suggestion:"Use URLSearchParams — querystring is legacy",since:"Node 14",name:"querystring",id:"DEPR_API007",fixable:!1},{pattern:/util\.isArray\s*\(/,suggestion:"Use Array.isArray() — util type checks are deprecated",since:"Node 4",name:"util.isArray()",id:"DEPR_API008"},{pattern:/util\.isFunction\s*\(/,suggestion:'Use typeof fn === "function"',since:"Node 4",name:"util.isFunction()",id:"DEPR_API009"},{pattern:/util\.pump\s*\(/,suggestion:"Use stream.pipeline() — util.pump() was removed",since:"Node 1.0",name:"util.pump()",id:"DEPR_API010",fixable:!1}]}async scan(e){const t=Date.now(),s={phantomImports:[],phantomAPIs:[],aiSmells:[],deprecatedAPIs:[],unresolvedDeps:[],stats:{filesScanned:0,totalIssues:0,scanTime:0}},n=this._loadDeclaredDeps(),i=this._loadIgnoreRules();for(const t of e)try{const e=path.extname(t).toLowerCase(),a=this.jsExtensions.has(e),o=this.pyExtensions.has(e),r=this.goExtensions.has(e),l=this.rustExtensions.has(e),c=this.javaExtensions.has(e),d=this.csharpExtensions.has(e),p=this.phpExtensions.has(e),m=this.rubyExtensions.has(e);if(!(a||o||r||l||c||d||p||m))continue;const u=path.relative(this.config.rootPath,t);if(i.some(e=>u.includes(e)||t.includes(e)))continue;const g=fs.readFileSync(t,"utf-8").replace(/\r\n/g,"\n"),h=g.split("\n"),_=new Set;for(let e=0;e<h.length;e++)h[e].includes("thuban-ignore")&&(_.add(e+1),_.add(e+2));const f=this._isPatternDefinitionFile(g);s.stats.filesScanned++,a?(this._checkPhantomImports(u,t,g,h,n,s,_),f||this._checkPhantomAPIs(u,g,h,s,_),this._checkAISmells(u,g,h,s,_),f||this._checkDeprecatedAPIs(u,g,h,s,_),f||this._checkNamedExports(u,t,g,s,_)):o?(this._checkLanguagePatterns(u,g,h,s,_,this.pythonPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.pythonDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.pythonSmells)):p?(this._checkLanguagePatterns(u,g,h,s,_,this.phpPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.phpDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.phpSmells)):m?(this._checkLanguagePatterns(u,g,h,s,_,this.rubyPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.rubyDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.rubySmells)):r?(this._checkLanguagePatterns(u,g,h,s,_,this.goDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.goSmells)):l?(this._checkLanguagePatterns(u,g,h,s,_,this.rustPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.rustDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.rustSmells)):c?".kt"===e?(this._checkLanguagePatterns(u,g,h,s,_,this.kotlinPhantomAPIs,"phantomAPIs"),this._checkLanguagePatterns(u,g,h,s,_,this.kotlinDeprecated,"deprecatedAPIs"),this._checkLanguageSmells(u,g,h,s,_,this.kotlinSmells)):this._checkLanguageSmells(u,g,h,s,_,this.javaSmells):d&&this._checkLanguageSmells(u,g,h,s,_,this.csharpSmells)}catch(e){}return s.stats.totalIssues=s.phantomImports.length+s.phantomAPIs.length+s.aiSmells.length+s.deprecatedAPIs.length+s.unresolvedDeps.length,s.stats.scanTime=Date.now()-t,s}_safeRegexTest(e,t,s=1e3){const n=Date.now();try{const i=e.test(t),a=Date.now()-n;return a>s?(console.warn(`[HALLUCINATION-DETECTOR] WARNING: Regex ${e.source.substring(0,50)}... took ${a}ms on input (${t.length} chars) — skipping pattern`),null):i}catch(e){return console.warn("[HALLUCINATION-DETECTOR] Regex error during scan"),null}}_safeRegexExec(e,t,s=1e3){const n=Date.now();try{const i=e.exec(t),a=Date.now()-n;return a>s?(console.warn(`[HALLUCINATION-DETECTOR] WARNING: Regex exec ${e.source.substring(0,50)}... took ${a}ms — skipping pattern`),null):i}catch(e){return console.warn("[HALLUCINATION-DETECTOR] Regex exec error during scan"),null}}_checkLanguagePatterns(e,t,s,n,i,a,o){for(let t=0;t<s.length;t++){if(i.has(t+1))continue;const r=s[t];for(const s of a){const i=this._safeRegexTest(s.pattern,r);if(null!==i&&i){const i={file:e,line:t+1,name:s.name,id:s.id};s.suggestion&&(i.suggestion=s.suggestion),s.since&&(i.since=s.since,i.fix=s.suggestion),"deprecatedAPIs"===o?n.deprecatedAPIs.push(i):n.phantomAPIs.push(i)}}}}_checkLanguageSmells(e,t,s,n,i,a){for(let t=0;t<s.length;t++){if(i.has(t+1))continue;const o=s[t];for(const s of a){const i=this._safeRegexTest(s.pattern,o);null!==i&&i&&n.aiSmells.push({file:e,line:t+1,id:s.id,name:s.name,message:s.message,type:"ai_smell",severity:"medium"})}}}formatReport(e){const t="",s="",n="",i="",a="",o="",r="",l="";let c="";if(c+=`\n${l} ╔══════════════════════════════════════════════╗${t}\n`,c+=`${l} ║${s} THUBAN HALLUCINATION REPORT ${t}${l}║${t}\n`,c+=`${l} ╚══════════════════════════════════════════════╝${t}\n\n`,0===e.stats.totalIssues)return c+=` ${i}${s}No hallucinations detected.${t} ${r}Clean codebase.${t}\n\n`,c;if(e.phantomImports.length>0){c+=` ${n}${s}Phantom Imports (${e.phantomImports.length})${t}\n`,c+=` ${r}Packages that don't exist in package.json or node_modules${t}\n\n`;for(const s of e.phantomImports.slice(0,10))c+=` ${n}✗${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.module}${t} ${r}— ${s.reason}${t}\n`;e.phantomImports.length>10&&(c+=` ${r}... and ${e.phantomImports.length-10} more${t}\n`),c+="\n"}if(e.phantomAPIs.length>0){c+=` ${n}${s}Phantom APIs (${e.phantomAPIs.length})${t}\n`,c+=` ${r}Methods/properties that don't exist on their objects${t}\n\n`;for(const s of e.phantomAPIs.slice(0,10))c+=` ${n}✗${t} ${s.id?`${r}[${s.id}]${t} `:""}${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.name}${t} ${r}— ${s.suggestion}${t}\n`,c+=` ${r}Suppress: // thuban-ignore ${s.id||"HALL_API"}${t}\n`;e.phantomAPIs.length>10&&(c+=` ${r}... and ${e.phantomAPIs.length-10} more${t}\n`),c+="\n"}if(e.aiSmells.length>0){c+=` ${a}${s}AI Code Smells (${e.aiSmells.length})${t}\n`,c+=` ${r}Patterns typical of AI-generated code that needs review${t}\n\n`;for(const s of e.aiSmells.slice(0,10))c+=` ${a}!${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${r}${s.message}${t}\n`;e.aiSmells.length>10&&(c+=` ${r}... and ${e.aiSmells.length-10} more${t}\n`),c+="\n"}if(e.deprecatedAPIs.length>0){c+=` ${a}${s}Deprecated APIs (${e.deprecatedAPIs.length})${t}\n`,c+=` ${r}APIs that LLMs still suggest but are deprecated or removed${t}\n\n`;for(const s of e.deprecatedAPIs.slice(0,10))c+=` ${a}⚠${t} ${o}${s.file}${t}:${s.line}\n`,c+=` ${a}${s.name}${t} ${r}(deprecated since ${s.since})${t}\n`,c+=` ${i}→${t} ${r}${s.suggestion}${t}\n`;e.deprecatedAPIs.length>10&&(c+=` ${r}... and ${e.deprecatedAPIs.length-10} more${t}\n`),c+="\n"}return c+=` ${s}Summary:${t} ${o}${e.stats.filesScanned}${t} files scanned, `,c+=`${e.stats.totalIssues>0?n:i}${e.stats.totalIssues}${t} hallucination issues found `,c+=`${r}(${e.stats.scanTime}ms)${t}\n\n`,c}_loadDeclaredDeps(){const e=new Set;return this._packageJsonPaths=new Map,this._collectPackageJsonDeps(this.config.rootPath,e,0),e}_collectPackageJsonDeps(e,t,s){if(!(s>5))try{const n=path.join(e,"package.json");if(fs.existsSync(n)){const s=JSON.parse(fs.readFileSync(n,"utf-8")),i=new Set;for(const e of Object.keys(s.dependencies||{}))t.add(e),i.add(e);for(const e of Object.keys(s.devDependencies||{}))t.add(e),i.add(e);for(const e of Object.keys(s.peerDependencies||{}))t.add(e),i.add(e);this._packageJsonPaths.set(e,i)}const i=new Set(["node_modules",".git","dist","build","coverage",".next",".cache","vendor"]),a=fs.readdirSync(e,{withFileTypes:!0});for(const n of a)!n.isDirectory()||i.has(n.name)||n.name.startsWith(".")||this._collectPackageJsonDeps(path.join(e,n.name),t,s+1)}catch(e){}}_checkPhantomImports(e,t,s,n,i,a,o=new Set){const r=[/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s+.*?from\s+['"]([^'"]+)['"]/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(const n of r){let r;for(;null!==(r=n.exec(s));){const n=r[1];if(n.startsWith(".")||path.isAbsolute(n))continue;const l=n.split("/")[0];if(this.builtins.has(n)||this.builtins.has(l))continue;const c=n.startsWith("@")?n.split("/").slice(0,2).join("/"):l;if(!i.has(c)){if(this.knownRealPackages.has(c))continue;if(!this._findInNodeModules(t,c)){const t=this._findLineNumber(s,r.index);if(o.has(t))continue;const i=this.phantomPackages.has(n);a.phantomImports.push({file:e,line:t,module:n,reason:i?"Known AI-hallucinated package — does not exist on npm":"Not in package.json and not in node_modules",severity:i?"critical":"high",fixable:!1})}}}}}_checkNamedExports(e,t,s,n,i=new Set){let a;try{a=exportVerifier.verifyFile(t,s)}catch(e){return}for(const t of a)i.has(t.line)||n.phantomImports.push({file:e,line:t.line,module:t.source,reason:t.message,severity:"critical",fixable:!1,source:"export-verifier"})}_checkPhantomAPIs(e,t,s,n,i=new Set){for(const a of this.phantomAPIs){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);if(i.has(r))continue;const l=s[r-1]||"";this._isInsidePattern(l,o[0])||n.phantomAPIs.push({file:e,line:r,name:a.name,id:a.id,suggestion:a.suggestion,severity:"high",fixable:!0,fixAction:"replace_phantom_api"})}}this._checkDynamicBuiltinCalls(e,t,s,n,i)}_checkDynamicBuiltinCalls(e,t,s,n,i){const a=new Map,o=/(?:const|let|var)\s+(\w+)\s*=\s*require\s*\(\s*['"](?:node:)?(\w+)['"]\s*\)/g;let r;for(;null!==(r=o.exec(t));){const e=r[1],t=r[2];this.builtins.has(t)&&a.set(e,t)}const l=/import\s+(?:\*\s+as\s+)?(\w+)\s+from\s+['"](?:node:)?(\w+)['"]/g;let c;for(;null!==(c=l.exec(t));){const e=c[1],t=c[2];this.builtins.has(t)&&a.set(e,t)}if(0!==a.size){this._builtinMethodCache||(this._builtinMethodCache=new Map);for(const[o,r]of a){if(!this._builtinMethodCache.has(r))try{const e=require(r),t=new Set(Object.keys(e));"object"==typeof e&&null!==e&&Object.getOwnPropertyNames(e).forEach(e=>t.add(e)),this._builtinMethodCache.set(r,t)}catch{this._builtinMethodCache.set(r,null);continue}const a=this._builtinMethodCache.get(r);if(!a)continue;const l=new RegExp(`\\b${o}\\.(\\w+)\\s*\\(`,"g");let c;for(;null!==(c=l.exec(t));){const o=c[1],l=this._findLineNumber(t,c.index);if(i.has(l))continue;const d=s[l-1]||"";if(!this._isInsidePattern(d,c[0])&&!a.has(o)){if(n.phantomAPIs.some(t=>t.file===e&&t.line===l))continue;n.phantomAPIs.push({file:e,line:l,name:`${r}.${o}`,id:"HALL_DYN",suggestion:`'${o}' does not exist on the '${r}' module — this is a hallucinated API`,severity:"critical",fixable:!1})}}}}}_checkAISmells(e,t,s,n,i=new Set){for(const a of this.aiCodeSmells){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);i.has(r)||n.aiSmells.push({file:e,line:r,id:a.id,name:a.name,message:a.message,severity:"warning",code:s[r-1]?.trim().substring(0,100)})}}}_checkDeprecatedAPIs(e,t,s,n,i=new Set){for(const a of this.deprecatedAPIs){let o;const r=new RegExp(a.pattern.source,a.pattern.flags+(a.pattern.flags.includes("g")?"":"g"));for(;null!==(o=this._safeRegexExec(r,t));){const r=this._findLineNumber(t,o.index);if(i.has(r))continue;const l=s[r-1]||"";this._isInsidePattern(l,o[0])||n.deprecatedAPIs.push({file:e,line:r,name:a.name,id:a.id,suggestion:a.suggestion,since:a.since,severity:"warning",fixable:!0,fixAction:"update_deprecated_api"})}}}_findLineNumber(e,t){let s=1;for(let n=0;n<t&&n<e.length;n++)"\n"===e[n]&&s++;return s}_isPatternDefinitionFile(e){const t=(e.match(/pattern:\s*\//g)||[]).length,s=(e.match(/phantom|hallucin/gi)||[]).length;return t>5&&s>2}_isInsidePattern(e,t){const s=e.trim();return!!(/pattern:\s*\//.test(s)||s.startsWith("//")||s.startsWith("*")||/(?:name|suggestion|message|description):\s*['"]/.test(s))}_loadIgnoreRules(){const e=[];try{const t=path.join(this.config.rootPath,".thubanrc.json"),s=JSON.parse(fs.readFileSync(t,"utf-8"));s.hallucination?.ignore&&e.push(...s.hallucination.ignore),s.ignore&&e.push(...s.ignore)}catch(e){}return e}_findInNodeModules(e,t){let s=path.dirname(e);const n=this.config.rootPath;for(;s.length>=n.length;){const e=path.join(s,"node_modules",t);try{if(fs.existsSync(e))return!0}catch(e){}const n=path.dirname(s);if(n===s)break;s=n}return!1}}module.exports=HallucinationDetector;