thuban 0.4.6 → 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.
- package/dist/cli.js +1 -1
- package/dist/package.json +2 -1
- package/dist/packages/scanner/feedback-client.js +1 -0
- package/dist/packages/scanner/hallucination-detector.js +1 -1
- package/dist/packages/scanner/investor-report.js +1 -0
- package/dist/packages/scanner/python_ast_helper.py +426 -0
- package/dist/packages/scanner/slack-notifier.js +1 -0
- package/dist/packages/scanner/support-bot.js +1 -0
- package/dist/packages/scanner/support-knowledge.js +1 -0
- package/package.json +2 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const https=require("https"),os=require("os"),fs=require("fs"),path=require("path"),readline=require("readline"),C={reset:"[0m",bold:"[1m",green:"[32m",yellow:"[33m",cyan:"[36m",gray:"[90m",red:"[31m"},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"),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").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="[0m",s="[1m",n="[31m",i="[32m",a="[33m",o="[36m",r="[90m",l="[35m";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)&&!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="[0m",s="[1m",n="[31m",i="[32m",a="[33m",o="[36m",r="[90m",l="[35m";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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const fs=require("fs"),path=require("path"),crypto=require("crypto");class InvestorReport{constructor(e={}){this.rootPath=e.rootPath||process.cwd(),this.companyName=e.companyName||this._detectProjectName(),this.generatedAt=new Date,this.reportKey=e.reportKey||null,this.tier=this._validateKey(this.reportKey)}_validateKey(e){if(!e||"string"!=typeof e)return"free";try{const n=e.split(":");if(n.length<3)return"free";const t=n[0],s=n[1],r=n.slice(2).join(":");if(!["snapshot","full"].includes(t))return"free";const o=parseInt(s,10);if(isNaN(o)||Date.now()-o>7776e6)return"free";const a="thuban-investor-salt-2026";return r===crypto.createHmac("sha256",a).update(`thuban-investor-${t}:${s}`).digest("hex").slice(0,16)?t:"free"}catch{return"free"}}static generateKey(e="full"){const n=Date.now().toString();return`${e}:${n}:${crypto.createHmac("sha256","thuban-investor-salt-2026").update(`thuban-investor-${e}:${n}`).digest("hex").slice(0,16)}`}_detectProjectName(){try{return JSON.parse(fs.readFileSync(path.join(this.rootPath,"package.json"),"utf-8")).name||path.basename(this.rootPath)}catch{return path.basename(this.rootPath)}}generate(e){const{scanResults:n={},hallResults:t={},debtCost:s={},ghostResults:r={},aiScoreResults:o={},cloneResults:a={},passportData:i={},fileCount:l=0,lineCount:d=0}=e,c=`THB-INV-${Date.now().toString(36).toUpperCase()}`,m=this._calculateOverallScore(e),u=this._scoreToGrade(m),g=this._gradeColor(u);return this._renderHTML({reportId:c,score:m,grade:u,gradeColor:g,scanResults:n,hallResults:t,debtCost:s,ghostResults:r,aiScoreResults:o,cloneResults:a,passportData:i,fileCount:l,lineCount:d,tier:this.tier})}_calculateOverallScore(e){let n=100;const t=e.hallResults||{},s=e.ghostResults||{},r=e.cloneResults||{},o=e.aiScoreResults||{},a=e.scanResults||{};n-=15*(t.phantomAPIs?.length||0),n-=5*(t.deprecatedAPIs?.length||0),n-=2*(s.totalGhosts||0),n-=3*(r.totalClusters||0),n-=1*(o.aiLikelyCount||0);let i=0;if(a&&"object"==typeof a)for(const[,e]of Object.entries(a))e?.issues&&(i+=e.issues.length);return n-=Math.min(.5*i,30),Math.max(0,Math.min(100,Math.round(n)))}_scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=65?"C":e>=50?"D":"F"}_gradeColor(e){return{A:"#00ff88",B:"#88ff00",C:"#ffd93d",D:"#ff8844",F:"#ff4444"}[e]||"#ff4444"}_investmentVerdict(e){return e>=80?{label:"PASS — Low Risk Investment",color:"#00ff88",bg:"rgba(0,255,136,0.1)",border:"rgba(0,255,136,0.3)"}:e>=65?{label:"CONDITIONAL PASS — Moderate Risk, Remediation Required",color:"#ffd93d",bg:"rgba(255,217,61,0.1)",border:"rgba(255,217,61,0.3)"}:e>=50?{label:"HIGH RISK — Significant Technical Debt",color:"#ff8844",bg:"rgba(255,136,68,0.1)",border:"rgba(255,136,68,0.3)"}:{label:"DO NOT INVEST — Critical Code Quality Issues",color:"#ff4444",bg:"rgba(255,68,68,0.1)",border:"rgba(255,68,68,0.3)"}}_aiDependencyAssessment(e){return e<10?{level:"Minimal",description:"Minimal AI dependency — traditional development team",color:"#00ff88"}:e<30?{level:"Moderate",description:"Moderate AI usage — within normal range for modern development",color:"#ffd93d"}:e<60?{level:"Heavy",description:"Heavy AI dependency — verify team can maintain without AI tools",color:"#ff8844"}:{level:"AI-Dominant",description:"AI-dominant codebase — high bus-factor risk if AI tools become unavailable",color:"#ff4444"}}_buildRemediationEstimate(e){const n=[],t=e.hallResults||{},s=e.ghostResults||{},r=e.cloneResults||{},o=e.aiScoreResults||{},a=t.phantomAPIs?.length||0,i=t.deprecatedAPIs?.length||0,l=s.totalGhosts||0,d=r.totalClusters||0,c=o.aiLikelyCount||0;if(a>0){const e=2*a;n.push({category:"Hallucinated APIs",issues:a,hours:e,cost80:80*e,cost120:120*e,priority:"Critical"})}if(i>0){const e=Math.ceil(1.5*i);n.push({category:"Deprecated APIs",issues:i,hours:e,cost80:80*e,cost120:120*e,priority:"High"})}if(l>0){const e=Math.ceil(.5*l);n.push({category:"Ghost / Dead Code",issues:l,hours:e,cost80:80*e,cost120:120*e,priority:"Medium"})}if(d>0){const e=3*d;n.push({category:"Code Clones / Duplication",issues:d,hours:e,cost80:80*e,cost120:120*e,priority:"Medium"})}if(c>0){const e=1*c;n.push({category:"AI-Generated Code Review",issues:c,hours:e,cost80:80*e,cost120:120*e,priority:"Low"})}let m=0;const u=e.scanResults||{};if(u&&"object"==typeof u)for(const[,e]of Object.entries(u))e?.issues&&(m+=e.issues.length);if(m>0){const e=Math.ceil(.3*m);n.push({category:"Code Quality Issues",issues:m,hours:e,cost80:80*e,cost120:120*e,priority:"Low"})}return n}_assessTeamCompetency(e){const n=e.scanResults||{},t=e.ghostResults||{},s=(e.cloneResults,e.aiScoreResults,e.lineCount,e.fileCount||1);let r=0,o=0;if(n&&"object"==typeof n)for(const[,e]of Object.entries(n))if(e?.issues){o+=e.issues.length;for(const n of e.issues){const e=(n.message||n.rule||"").toLowerCase();(e.includes("error")||e.includes("catch")||e.includes("exception")||e.includes("try"))&&r++}}const a=o>0?1-r/o:1,i=o/s,l=t.wastedPercent||0,d=(e.testFileCount||0)/s,c=e.commentRatio||0,m=[];return a>=.9?m.push({name:"Error Handling Patterns",rating:"Strong",color:"#00ff88"}):a>=.7?m.push({name:"Error Handling Patterns",rating:"Adequate",color:"#ffd93d"}):a>=.4?m.push({name:"Error Handling Patterns",rating:"Needs Improvement",color:"#ff8844"}):m.push({name:"Error Handling Patterns",rating:"Concerning",color:"#ff4444"}),i<=1?m.push({name:"Naming Consistency",rating:"Strong",color:"#00ff88"}):i<=3?m.push({name:"Naming Consistency",rating:"Adequate",color:"#ffd93d"}):i<=6?m.push({name:"Naming Consistency",rating:"Needs Improvement",color:"#ff8844"}):m.push({name:"Naming Consistency",rating:"Concerning",color:"#ff4444"}),l<=3?m.push({name:"Function Size Distribution",rating:"Strong",color:"#00ff88"}):l<=8?m.push({name:"Function Size Distribution",rating:"Adequate",color:"#ffd93d"}):l<=15?m.push({name:"Function Size Distribution",rating:"Needs Improvement",color:"#ff8844"}):m.push({name:"Function Size Distribution",rating:"Concerning",color:"#ff4444"}),d>=.3?m.push({name:"Test Coverage Indicators",rating:"Strong",color:"#00ff88"}):d>=.15?m.push({name:"Test Coverage Indicators",rating:"Adequate",color:"#ffd93d"}):d>=.05?m.push({name:"Test Coverage Indicators",rating:"Needs Improvement",color:"#ff8844"}):m.push({name:"Test Coverage Indicators",rating:"Concerning",color:"#ff4444"}),c>=.15?m.push({name:"Documentation Quality",rating:"Strong",color:"#00ff88"}):c>=.08?m.push({name:"Documentation Quality",rating:"Adequate",color:"#ffd93d"}):c>=.03?m.push({name:"Documentation Quality",rating:"Needs Improvement",color:"#ff8844"}):m.push({name:"Documentation Quality",rating:"Concerning",color:"#ff4444"}),m}_buildExecutiveSummary(e,n){const t=n.hallResults||{},s=n.ghostResults||{},r=n.aiScoreResults||{},o=t.phantomAPIs?.length||0,a=s.totalGhosts||0,i=r.aiPercentage||0,l=this._buildRemediationEstimate(n),d=l.reduce((e,n)=>e+n.hours,0),c=l.reduce((e,n)=>e+n.cost80,0);let m;m=e>=80?"demonstrates strong engineering practices":e>=65?"demonstrates competent engineering practices with areas requiring attention":e>=50?"shows foundational engineering capability but carries significant technical debt":"exhibits critical code quality deficiencies that pose material risk";let u=[`This codebase ${m} with a trust score of ${e}/100.`];return o>0?u.push(`${o} critical AI-hallucinated API call${o>1?"s":""} require${1===o?"s":""} immediate remediation (estimated ${2*o} dev-hours).`):a>0&&u.push(`${a} dead code function${a>1?"s":""} should be removed to reduce maintenance surface area.`),i>30?u.push(`${i}% of the codebase shows AI-generation signals, indicating elevated dependency on AI tooling.`):e>=65?u.push("The development team shows strong architectural discipline with manageable technical debt."):u.push("The development team would benefit from structured code review processes and automated quality gates."),d>0&&u.push(`Estimated remediation cost to reach investment-grade: £${c.toLocaleString()}.`),u.join(" ")}_buildRiskMatrix(e){const n=e.hallResults||{},t=e.ghostResults||{},s=e.cloneResults||{},r=e.scanResults||{},o=n.phantomAPIs?.length||0,a=n.deprecatedAPIs?.length||0,i=t.totalGhosts||0,l=s.totalClusters||0;let d=0,c=0;if(r&&"object"==typeof r)for(const[,e]of Object.entries(r))if(e?.issues)for(const n of e.issues){const e=(n.message||n.rule||"").toLowerCase();(e.includes("inject")||e.includes("sql")||e.includes("xss")||e.includes("taint"))&&d++,(e.includes("style")||e.includes("format")||e.includes("indent")||e.includes("naming"))&&c++}return{criticalLikely:{items:[],count:o+d},criticalUnlikely:{items:[],count:0},moderateLikely:{items:[],count:i+l},moderateUnlikely:{items:[],count:a+c},phantomCount:o,injectionCount:d,ghostCount:i,cloneCount:l,deprecatedCount:a,styleIssueCount:c}}_renderHTML(e){const n=this.generatedAt,t=n.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"}),s=n.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),r=e.hallResults.phantomAPIs?.length||0,o=e.hallResults.deprecatedAPIs?.length||0,a=e.ghostResults.totalGhosts||0,i=e.ghostResults.totalWastedLines||0,l=(e.cloneResults.totalClusters,e.cloneResults.totalDuplicateLines,e.aiScoreResults.aiLikelyCount||0),d=e.aiScoreResults.aiPossibleCount||0,c=e.aiScoreResults.aiPercentage||0,m=e.debtCost.totalHoursManual||0,u=e.debtCost.totalCostManual||0,g=e.debtCost.totalHoursThuban||0,h=e.debtCost.totalSaving||0,p=e.debtCost.savingPercent||0,v=this._investmentVerdict(e.score),f=this._aiDependencyAssessment(c),b=this._buildExecutiveSummary(e.score,{hallResults:e.hallResults,ghostResults:e.ghostResults,aiScoreResults:e.aiScoreResults,debtCost:e.debtCost,scanResults:e.scanResults,fileCount:e.fileCount,lineCount:e.lineCount}),y=this._buildRemediationEstimate({hallResults:e.hallResults,ghostResults:e.ghostResults,aiScoreResults:e.aiScoreResults,cloneResults:e.cloneResults,scanResults:e.scanResults}),x=y.reduce((e,n)=>e+n.hours,0),C=y.reduce((e,n)=>e+n.cost80,0),w=y.reduce((e,n)=>e+n.cost120,0),$=y.reduce((e,n)=>e+n.issues,0),R=this._buildRiskMatrix({hallResults:e.hallResults,ghostResults:e.ghostResults,cloneResults:e.cloneResults,scanResults:e.scanResults}),k=this._assessTeamCompetency({scanResults:e.scanResults,ghostResults:e.ghostResults,cloneResults:e.cloneResults,aiScoreResults:e.aiScoreResults,fileCount:e.fileCount,lineCount:e.lineCount,testFileCount:e.passportData?.testFileCount||0,commentRatio:e.passportData?.commentRatio||0});let I="";if(e.hallResults.phantomAPIs)for(const n of e.hallResults.phantomAPIs.slice(0,8))I+=`<tr>\n <td class="sev-critical">CRITICAL</td>\n <td>${this._esc(n.file||"")}:${n.line||"?"}</td>\n <td>${this._esc(n.name||n.code||"Phantom API")}</td>\n <td>Will crash at runtime — method does not exist</td>\n </tr>`;if(e.hallResults.deprecatedAPIs)for(const n of e.hallResults.deprecatedAPIs.slice(0,5))I+=`<tr>\n <td class="sev-high">HIGH</td>\n <td>${this._esc(n.file||"")}:${n.line||"?"}</td>\n <td>${this._esc(n.name||n.code||"Deprecated API")}</td>\n <td>Deprecated — will break in future versions</td>\n </tr>`;let A="";if(e.ghostResults.ghosts)for(const n of e.ghostResults.ghosts.slice(0,8))A+=`<tr>\n <td>${this._esc(n.file)}:${n.line}</td>\n <td>${this._esc(n.name)}()</td>\n <td>${n.wastedLines} lines</td>\n <td>${n.references} references</td>\n </tr>`;let S="";for(const e of y){const n="Critical"===e.priority?"var(--red)":"High"===e.priority?"var(--yellow)":"Medium"===e.priority?"var(--cyan)":"var(--dim)";S+=`<tr>\n <td>${this._esc(e.category)}</td>\n <td style="text-align:center">${e.issues}</td>\n <td style="text-align:center">${e.hours}</td>\n <td style="text-align:right">£${e.cost80.toLocaleString()}</td>\n <td style="text-align:right">£${e.cost120.toLocaleString()}</td>\n <td style="color:${n}; font-weight:600">${e.priority}</td>\n </tr>`}let z="";for(const e of k)z+=`<tr>\n <td>${this._esc(e.name)}</td>\n <td style="color:${e.color}; font-weight:600">${e.rating}</td>\n </tr>`;const T=[{label:"Pre-seed typical",min:40,max:55},{label:"Seed typical",min:50,max:65},{label:"Series A typical",min:60,max:75},{label:"Series B typical",min:70,max:80},{label:"Series C+",min:80,max:90}];let P="";for(const n of T)P+=`\n <div class="benchmark-row">\n <div class="benchmark-label">${n.label}</div>\n <div class="benchmark-track">\n <div class="benchmark-range" style="left:${n.min}%; width:${n.max-n.min}%"></div>\n <div class="benchmark-marker" style="left:${e.score}%" title="This codebase: ${e.score}"></div>\n </div>\n <div class="benchmark-values">${n.min}–${n.max}</div>\n </div>`;return`<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<title>Thuban Investor Due Diligence Report — ${this._esc(this.companyName)}</title>\n<style>\n @page { size: A4; margin: 15mm; }\n @media print {\n body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }\n .no-print { display: none !important; }\n .page-break { page-break-before: always; }\n .verdict-banner { break-inside: avoid; }\n }\n\n :root {\n --bg: #0a0a1a;\n --surface: #12122a;\n --border: #2a2a5a;\n --text: #e0e0f0;\n --dim: #8888aa;\n --cyan: #00f6ff;\n --green: #00ff88;\n --yellow: #ffd93d;\n --red: #ff4444;\n --purple: #a855f7;\n --orange: #ff8844;\n --mono: 'JetBrains Mono', 'Cascadia Code', 'Consolas', monospace;\n --sans: 'Segoe UI', system-ui, -apple-system, sans-serif;\n }\n\n * { margin: 0; padding: 0; box-sizing: border-box; }\n\n body {\n background: var(--bg);\n color: var(--text);\n font-family: var(--sans);\n font-size: 11pt;\n line-height: 1.5;\n max-width: 210mm;\n margin: 0 auto;\n padding: 20mm 15mm;\n }\n\n /* Header */\n .report-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n border-bottom: 2px solid var(--cyan);\n padding-bottom: 1.5rem;\n margin-bottom: 2rem;\n }\n\n .report-header .logo {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n }\n\n .report-header .logo svg { width: 36px; height: 36px; }\n\n .report-header .logo-text {\n font-size: 1.5rem;\n font-weight: 300;\n letter-spacing: 0.3em;\n color: var(--cyan);\n }\n\n .report-header .meta {\n text-align: right;\n font-size: 0.8rem;\n color: var(--dim);\n line-height: 1.8;\n }\n\n .report-title {\n text-align: center;\n margin-bottom: 2rem;\n }\n\n .report-title h1 {\n font-size: 1.8rem;\n font-weight: 700;\n margin-bottom: 0.25rem;\n }\n\n .report-title .subtitle {\n font-size: 0.85rem;\n color: var(--dim);\n text-transform: uppercase;\n letter-spacing: 0.15em;\n margin-bottom: 0.25rem;\n }\n\n .report-title .project-name {\n color: var(--cyan);\n font-size: 1.1rem;\n font-family: var(--mono);\n }\n\n /* Verdict Banner */\n .verdict-banner {\n text-align: center;\n padding: 1.5rem 2rem;\n border-radius: 12px;\n margin-bottom: 2rem;\n font-size: 1.3rem;\n font-weight: 700;\n letter-spacing: 0.05em;\n }\n\n /* Executive Summary */\n .exec-summary {\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 1.5rem 2rem;\n margin-bottom: 2rem;\n font-size: 0.9rem;\n line-height: 1.7;\n color: var(--text);\n }\n\n .exec-summary .summary-label {\n font-size: 0.7rem;\n text-transform: uppercase;\n letter-spacing: 0.1em;\n color: var(--dim);\n margin-bottom: 0.5rem;\n font-weight: 600;\n }\n\n /* Score Ring */\n .score-section {\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 3rem;\n margin-bottom: 2.5rem;\n padding: 2rem;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 12px;\n }\n\n .score-ring {\n position: relative;\n width: 140px;\n height: 140px;\n }\n\n .score-ring svg { transform: rotate(-90deg); }\n\n .score-ring .score-value {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n text-align: center;\n }\n\n .score-ring .grade {\n font-size: 2.5rem;\n font-weight: 700;\n font-family: var(--mono);\n line-height: 1;\n }\n\n .score-ring .number {\n font-size: 0.85rem;\n color: var(--dim);\n }\n\n .score-summary { flex: 1; }\n\n .score-summary h2 {\n font-size: 1.3rem;\n margin-bottom: 0.75rem;\n }\n\n .stat-row {\n display: flex;\n gap: 2rem;\n flex-wrap: wrap;\n margin-top: 1rem;\n }\n\n .stat {\n text-align: center;\n min-width: 80px;\n }\n\n .stat .stat-value {\n font-size: 1.5rem;\n font-weight: 700;\n font-family: var(--mono);\n }\n\n .stat .stat-label {\n font-size: 0.7rem;\n color: var(--dim);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n .stat-critical .stat-value { color: var(--red); }\n .stat-warning .stat-value { color: var(--yellow); }\n .stat-good .stat-value { color: var(--green); }\n .stat-info .stat-value { color: var(--cyan); }\n\n /* Sections */\n .section {\n margin-bottom: 2rem;\n }\n\n .section-header {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n margin-bottom: 1rem;\n padding-bottom: 0.5rem;\n border-bottom: 1px solid var(--border);\n }\n\n .section-header h3 {\n font-size: 1rem;\n font-weight: 600;\n }\n\n .section-header .icon { font-size: 1.2rem; }\n\n /* Tables */\n table {\n width: 100%;\n border-collapse: collapse;\n font-size: 0.8rem;\n margin-bottom: 1rem;\n }\n\n th {\n text-align: left;\n padding: 0.5rem;\n background: var(--surface);\n border-bottom: 1px solid var(--border);\n font-weight: 600;\n font-size: 0.7rem;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--dim);\n }\n\n td {\n padding: 0.4rem 0.5rem;\n border-bottom: 1px solid rgba(42,42,90,0.3);\n font-family: var(--mono);\n font-size: 0.75rem;\n word-break: break-all;\n }\n\n .sev-critical { color: var(--red); font-weight: 700; }\n .sev-high { color: var(--yellow); font-weight: 600; }\n\n /* Risk Matrix */\n .risk-matrix {\n display: grid;\n grid-template-columns: auto 1fr 1fr;\n grid-template-rows: auto 1fr 1fr;\n gap: 0;\n margin-bottom: 1rem;\n border: 1px solid var(--border);\n border-radius: 12px;\n overflow: hidden;\n }\n\n .risk-matrix .rm-corner {\n background: var(--surface);\n padding: 0.5rem;\n }\n\n .risk-matrix .rm-col-header {\n background: var(--surface);\n padding: 0.6rem 0.75rem;\n text-align: center;\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--dim);\n border-bottom: 1px solid var(--border);\n }\n\n .risk-matrix .rm-row-header {\n background: var(--surface);\n padding: 0.6rem 0.75rem;\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n color: var(--dim);\n display: flex;\n align-items: center;\n border-right: 1px solid var(--border);\n }\n\n .risk-matrix .rm-cell {\n padding: 0.75rem;\n font-size: 0.75rem;\n border-right: 1px solid rgba(42,42,90,0.3);\n border-bottom: 1px solid rgba(42,42,90,0.3);\n }\n\n .rm-cell-critical-likely { background: rgba(255,68,68,0.12); }\n .rm-cell-critical-unlikely { background: rgba(255,136,68,0.08); }\n .rm-cell-moderate-likely { background: rgba(255,217,61,0.08); }\n .rm-cell-moderate-unlikely { background: rgba(0,246,255,0.05); }\n\n .rm-cell .rm-count {\n font-family: var(--mono);\n font-size: 1.2rem;\n font-weight: 700;\n margin-bottom: 0.25rem;\n }\n\n .rm-cell .rm-items {\n font-size: 0.7rem;\n color: var(--dim);\n line-height: 1.4;\n }\n\n /* AI Dependency */\n .ai-dep-bar {\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 1.5rem 2rem;\n margin-bottom: 1rem;\n }\n\n .ai-dep-meter {\n height: 24px;\n background: rgba(42,42,90,0.5);\n border-radius: 12px;\n position: relative;\n margin: 1rem 0;\n overflow: visible;\n }\n\n .ai-dep-fill {\n height: 100%;\n border-radius: 12px;\n transition: width 0.3s;\n }\n\n .ai-dep-zones {\n display: flex;\n justify-content: space-between;\n font-size: 0.65rem;\n color: var(--dim);\n margin-top: 0.5rem;\n }\n\n .ai-dep-assessment {\n margin-top: 1rem;\n font-size: 0.85rem;\n line-height: 1.6;\n }\n\n /* Cost Box */\n .cost-box {\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 1.5rem 2rem;\n margin-bottom: 1rem;\n }\n\n .cost-grid {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr;\n gap: 1.5rem;\n text-align: center;\n }\n\n .cost-item .cost-value {\n font-size: 1.8rem;\n font-weight: 700;\n font-family: var(--mono);\n }\n\n .cost-item .cost-label {\n font-size: 0.75rem;\n color: var(--dim);\n margin-top: 0.25rem;\n }\n\n .cost-manual .cost-value { color: var(--red); }\n .cost-thuban .cost-value { color: var(--cyan); }\n .cost-saving .cost-value { color: var(--green); }\n\n /* Benchmarks */\n .benchmark-row {\n display: flex;\n align-items: center;\n gap: 1rem;\n margin-bottom: 0.75rem;\n }\n\n .benchmark-label {\n width: 130px;\n font-size: 0.75rem;\n color: var(--dim);\n text-align: right;\n flex-shrink: 0;\n }\n\n .benchmark-track {\n flex: 1;\n height: 20px;\n background: rgba(42,42,90,0.4);\n border-radius: 10px;\n position: relative;\n }\n\n .benchmark-range {\n position: absolute;\n top: 3px;\n height: 14px;\n background: rgba(0,246,255,0.15);\n border: 1px solid rgba(0,246,255,0.3);\n border-radius: 7px;\n }\n\n .benchmark-marker {\n position: absolute;\n top: -2px;\n width: 4px;\n height: 24px;\n background: var(--cyan);\n border-radius: 2px;\n box-shadow: 0 0 8px rgba(0,246,255,0.5);\n transform: translateX(-2px);\n }\n\n .benchmark-values {\n width: 50px;\n font-size: 0.7rem;\n color: var(--dim);\n font-family: var(--mono);\n flex-shrink: 0;\n }\n\n /* Team Competency */\n .competency-table td:first-child {\n font-family: var(--sans);\n font-size: 0.8rem;\n word-break: normal;\n }\n\n .competency-table td:last-child {\n text-align: center;\n font-size: 0.8rem;\n width: 140px;\n }\n\n /* Callouts */\n .callout {\n padding: 1rem 1.5rem;\n border-radius: 8px;\n margin-bottom: 1rem;\n font-size: 0.85rem;\n }\n\n .callout-danger {\n background: rgba(255,68,68,0.08);\n border: 1px solid rgba(255,68,68,0.2);\n color: #ffaaaa;\n }\n\n .callout-warning {\n background: rgba(255,217,61,0.08);\n border: 1px solid rgba(255,217,61,0.2);\n color: #ffe088;\n }\n\n /* Paywall Gate */\n .paywall-section { position: relative; }\n .paywall-overlay {\n padding: 3rem 2rem;\n text-align: center;\n background: linear-gradient(135deg, rgba(18,18,42,0.95), rgba(10,10,26,0.98));\n border: 1px dashed var(--border);\n border-radius: 12px;\n }\n .paywall-message { max-width: 420px; margin: 0 auto; }\n .paywall-message h4 { font-size: 1.1rem; }\n .paywall-message code {\n background: rgba(0,246,255,0.1);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 0.8rem;\n }\n .paywall-message a { text-decoration: none; }\n .paywall-message a:hover { text-decoration: underline; }\n\n /* Confidentiality Footer */\n .confidentiality {\n margin-top: 3rem;\n padding: 1.25rem 1.5rem;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 8px;\n font-size: 0.7rem;\n color: var(--dim);\n line-height: 1.6;\n text-align: center;\n }\n\n .confidentiality strong {\n color: var(--yellow);\n letter-spacing: 0.1em;\n }\n\n /* Footer */\n .report-footer {\n margin-top: 1.5rem;\n padding-top: 1.5rem;\n border-top: 1px solid var(--border);\n display: flex;\n justify-content: space-between;\n font-size: 0.75rem;\n color: var(--dim);\n }\n\n .report-footer a { color: var(--cyan); text-decoration: none; }\n\n /* Print button */\n .print-btn {\n position: fixed;\n bottom: 2rem;\n right: 2rem;\n background: var(--cyan);\n color: var(--bg);\n border: none;\n padding: 0.75rem 1.5rem;\n border-radius: 8px;\n font-weight: 600;\n font-size: 0.9rem;\n cursor: pointer;\n box-shadow: 0 4px 20px rgba(0,246,255,0.3);\n z-index: 100;\n }\n\n .print-btn:hover { background: #33f8ff; }\n\n /* Totals row */\n .totals-row td {\n font-weight: 700;\n border-top: 2px solid var(--border);\n padding-top: 0.6rem;\n }\n\n /* Responsive */\n @media screen and (max-width: 700px) {\n body { padding: 1rem; }\n .cost-grid { grid-template-columns: 1fr; }\n .stat-row { flex-direction: column; gap: 0.75rem; }\n .score-section { flex-direction: column; gap: 1.5rem; }\n .risk-matrix { grid-template-columns: auto 1fr; }\n .benchmark-label { width: 80px; font-size: 0.65rem; }\n }\n</style>\n</head>\n<body>\n\n<button class="print-btn no-print" onclick="window.print()">Save as PDF</button>\n\n\x3c!-- Header --\x3e\n<div class="report-header">\n <div class="logo">\n <svg viewBox="0 0 32 32" fill="none">\n <polygon points="16,2 30,28 2,28" stroke="#00f6ff" stroke-width="2" fill="none"/>\n <polygon points="16,8 25,25 7,25" stroke="#00f6ff" stroke-width="1" fill="rgba(0,246,255,0.1)"/>\n <circle cx="16" cy="18" r="3" fill="#00f6ff"/>\n </svg>\n <span class="logo-text">THUBAN</span>\n </div>\n <div class="meta">\n Report ID: ${e.reportId}<br>\n Generated: ${t} at ${s}<br>\n Engine: Thuban Code Health v0.3.0<br>\n Classification: Investor Due Diligence\n </div>\n</div>\n\n\x3c!-- Title --\x3e\n<div class="report-title">\n <div class="subtitle">Investor Due Diligence Report</div>\n <h1>Code Health Assessment</h1>\n <div class="project-name">${this._esc(this.companyName)}</div>\n</div>\n\n\x3c!-- Investment Verdict Banner --\x3e\n<div class="verdict-banner" style="background:${v.bg}; border:2px solid ${v.border}; color:${v.color}">\n ${v.label}\n</div>\n\n\x3c!-- Executive Summary --\x3e\n<div class="exec-summary">\n <div class="summary-label">Executive Summary</div>\n ${b}\n</div>\n\n\x3c!-- Score --\x3e\n<div class="score-section">\n <div class="score-ring">\n <svg width="140" height="140" viewBox="0 0 140 140">\n <circle cx="70" cy="70" r="60" fill="none" stroke="${e.gradeColor}22" stroke-width="10"/>\n <circle cx="70" cy="70" r="60" fill="none" stroke="${e.gradeColor}" stroke-width="10"\n stroke-dasharray="${Math.round(3.77*e.score)} 377"\n stroke-linecap="round"/>\n </svg>\n <div class="score-value">\n <div class="grade" style="color:${e.gradeColor}">${e.grade}</div>\n <div class="number">${e.score}/100</div>\n </div>\n </div>\n <div class="score-summary">\n <h2>Trust Score: ${"A"===e.grade?"Excellent":"B"===e.grade?"Good":"C"===e.grade?"Needs Attention":"D"===e.grade?"At Risk":"Critical"}</h2>\n <div class="stat-row">\n <div class="stat stat-info">\n <div class="stat-value">${e.fileCount.toLocaleString()}</div>\n <div class="stat-label">Files Scanned</div>\n </div>\n <div class="stat stat-info">\n <div class="stat-value">${e.lineCount.toLocaleString()}</div>\n <div class="stat-label">Lines of Code</div>\n </div>\n <div class="stat ${r>0?"stat-critical":"stat-good"}">\n <div class="stat-value">${r}</div>\n <div class="stat-label">Hallucinated APIs</div>\n </div>\n <div class="stat ${a>0?"stat-warning":"stat-good"}">\n <div class="stat-value">${a}</div>\n <div class="stat-label">Ghost Functions</div>\n </div>\n <div class="stat ${l>0?"stat-warning":"stat-good"}">\n <div class="stat-value">${c}%</div>\n <div class="stat-label">AI-Generated</div>\n </div>\n </div>\n </div>\n</div>\n\n${r>0?`\n<div class="callout callout-danger">\n <strong>MATERIAL RISK:</strong> ${r} API call${r>1?"s":""} in this codebase reference${1===r?"s":""} methods that do not exist.\n These will throw runtime errors in production. This represents a direct threat to service reliability and customer trust.\n</div>\n`:""}\n\n\x3c!-- Risk Matrix --\x3e\n${"free"===e.tier?'\n<div class="section paywall-section">\n <div class="section-header">\n <span class="icon">⚠</span>\n <h3>Risk Matrix</h3>\n </div>\n <div class="paywall-overlay">\n <div class="paywall-message">\n <div style="font-size:2rem;margin-bottom:0.75rem;">🔒</div>\n <h4 style="margin-bottom:0.5rem;color:var(--text);">Unlock Full Risk Analysis</h4>\n <p style="color:var(--dim);font-size:0.85rem;margin-bottom:1rem;">Risk Matrix, AI Dependency Assessment, and detailed findings are available with a Snapshot ($99) or Full Audit ($399) report key.</p>\n <div style="font-family:var(--mono);font-size:0.8rem;color:var(--cyan);background:rgba(0,246,255,0.05);padding:0.75rem 1rem;border-radius:8px;border:1px solid rgba(0,246,255,0.15);">\n Purchase at <a href="https://thuban.dev/#investors" style="color:var(--cyan)">thuban.dev</a> → run with <code>--key=YOUR_KEY</code>\n </div>\n </div>\n </div>\n</div>\n':`\n<div class="section">\n <div class="section-header">\n <span class="icon">⚠</span>\n <h3>Risk Matrix</h3>\n </div>\n <div class="risk-matrix">\n <div class="rm-corner"></div>\n <div class="rm-col-header" style="border-left:1px solid var(--border)">Likely</div>\n <div class="rm-col-header">Unlikely</div>\n\n <div class="rm-row-header">Critical</div>\n <div class="rm-cell rm-cell-critical-likely" style="border-left:1px solid rgba(42,42,90,0.3)">\n <div class="rm-count" style="color:var(--red)">${R.phantomCount+R.injectionCount}</div>\n <div class="rm-items">\n ${R.phantomCount>0?`${R.phantomCount} hallucinated API${R.phantomCount>1?"s":""}<br>`:""}\n ${R.injectionCount>0?`${R.injectionCount} injection risk${R.injectionCount>1?"s":""}`:""}\n ${0===R.phantomCount&&0===R.injectionCount?"None detected":""}\n </div>\n </div>\n <div class="rm-cell rm-cell-critical-unlikely">\n <div class="rm-count" style="color:var(--orange)">0</div>\n <div class="rm-items">Complex taint paths<br>(not yet assessed)</div>\n </div>\n\n <div class="rm-row-header" style="border-top:1px solid var(--border)">Moderate</div>\n <div class="rm-cell rm-cell-moderate-likely" style="border-left:1px solid rgba(42,42,90,0.3)">\n <div class="rm-count" style="color:var(--yellow)">${R.ghostCount+R.cloneCount}</div>\n <div class="rm-items">\n ${R.ghostCount>0?`${R.ghostCount} ghost/dead code<br>`:""}\n ${R.cloneCount>0?`${R.cloneCount} code clone${R.cloneCount>1?"s":""}`:""}\n ${0===R.ghostCount&&0===R.cloneCount?"None detected":""}\n </div>\n </div>\n <div class="rm-cell rm-cell-moderate-unlikely">\n <div class="rm-count" style="color:var(--cyan)">${R.deprecatedCount+R.styleIssueCount}</div>\n <div class="rm-items">\n ${R.deprecatedCount>0?`${R.deprecatedCount} deprecated API${R.deprecatedCount>1?"s":""}<br>`:""}\n ${R.styleIssueCount>0?`${R.styleIssueCount} style issue${R.styleIssueCount>1?"s":""}`:""}\n ${0===R.deprecatedCount&&0===R.styleIssueCount?"None detected":""}\n </div>\n </div>\n </div>\n</div>\n`}\n\n\x3c!-- AI Dependency Assessment --\x3e\n${"free"===e.tier?"":`\n<div class="section">\n <div class="section-header">\n <span class="icon">🤖</span>\n <h3>AI Dependency Assessment</h3>\n </div>\n <div class="ai-dep-bar">\n <div style="display:flex; justify-content:space-between; align-items:baseline; margin-bottom:0.5rem;">\n <span style="font-size:0.85rem; color:var(--dim)">AI-Generated Code Percentage</span>\n <span style="font-family:var(--mono); font-size:1.2rem; font-weight:700; color:${f.color}">${c}%</span>\n </div>\n <div class="ai-dep-meter">\n <div class="ai-dep-fill" style="width:${Math.min(c,100)}%; background:${f.color}; opacity:0.7"></div>\n </div>\n <div class="ai-dep-zones">\n <span><10% Minimal</span>\n <span>10-30% Moderate</span>\n <span>30-60% Heavy</span>\n <span>>60% Dominant</span>\n </div>\n <div class="ai-dep-assessment">\n <strong style="color:${f.color}">${f.level}:</strong> ${f.description}\n </div>\n ${l>0?`<div style="margin-top:0.75rem; font-size:0.8rem; color:var(--dim)">\n ${l} function${l>1?"s":""} flagged as high-confidence AI-generated, ${d} flagged as possible.\n These should be reviewed for correctness, edge-case handling, and adequate test coverage.\n </div>`:""}\n </div>\n</div>\n`}\n\n<div class="page-break"></div>\n\n\x3c!-- Remediation Estimate --\x3e\n${"full"!==e.tier?'\n<div class="section paywall-section">\n <div class="section-header">\n <span class="icon">💰</span>\n <h3>Remediation Cost Estimate</h3>\n </div>\n <div class="paywall-overlay">\n <div class="paywall-message">\n <div style="font-size:2rem;margin-bottom:0.75rem;">🔒</div>\n <h4 style="margin-bottom:0.5rem;color:var(--text);">Full Audit Required</h4>\n <p style="color:var(--dim);font-size:0.85rem;margin-bottom:1rem;">Remediation cost estimates, team competency analysis, and comparable benchmarks are available with a Full Audit report key ($399).</p>\n <div style="font-family:var(--mono);font-size:0.8rem;color:var(--cyan);background:rgba(0,246,255,0.05);padding:0.75rem 1rem;border-radius:8px;border:1px solid rgba(0,246,255,0.15);">\n Purchase at <a href="https://thuban.dev/#investors" style="color:var(--cyan)">thuban.dev</a> → run with <code>--key=YOUR_KEY</code>\n </div>\n </div>\n </div>\n</div>\n':`\n<div class="section">\n <div class="section-header">\n <span class="icon">💰</span>\n <h3>Remediation Cost Estimate</h3>\n </div>\n ${y.length>0?`\n <table>\n <thead>\n <tr>\n <th>Category</th>\n <th style="text-align:center">Issues</th>\n <th style="text-align:center">Est. Hours</th>\n <th style="text-align:right">Cost @ £80/hr</th>\n <th style="text-align:right">Cost @ £120/hr</th>\n <th>Priority</th>\n </tr>\n </thead>\n <tbody>\n ${S}\n <tr class="totals-row">\n <td style="font-family:var(--sans)"><strong>TOTAL</strong></td>\n <td style="text-align:center">${$}</td>\n <td style="text-align:center">${x}</td>\n <td style="text-align:right; color:var(--yellow)">£${C.toLocaleString()}</td>\n <td style="text-align:right; color:var(--red)">£${w.toLocaleString()}</td>\n <td></td>\n </tr>\n </tbody>\n </table>\n <div style="font-size:0.8rem; color:var(--dim); margin-top:0.5rem;">\n Estimates based on industry-average remediation times. Actual costs may vary based on team familiarity and codebase complexity.\n Rates shown reflect UK market mid-range (£80/hr) and senior (£120/hr) developer costs.\n </div>\n `:'\n <div style="font-size:0.85rem; color:var(--green); padding:1rem; background:rgba(0,255,136,0.05); border-radius:8px; border:1px solid rgba(0,255,136,0.15);">\n No significant remediation items detected. This codebase meets investment-grade quality standards.\n </div>\n '}\n</div>\n`}\n\n\x3c!-- Team Competency Signals --\x3e\n${"full"!==e.tier?"":`\n<div class="section">\n <div class="section-header">\n <span class="icon">👥</span>\n <h3>Team Competency Signals</h3>\n </div>\n <p style="font-size:0.8rem; color:var(--dim); margin-bottom:1rem;">\n Derived from automated code analysis patterns. These signals indicate engineering team capability\n based on observable code quality metrics, not individual performance.\n </p>\n <table class="competency-table">\n <thead>\n <tr><th>Signal</th><th style="text-align:center">Assessment</th></tr>\n </thead>\n <tbody>${z}</tbody>\n </table>\n</div>\n`}\n\n\x3c!-- Comparable Benchmarks --\x3e\n${"full"!==e.tier?"":`\n<div class="section">\n <div class="section-header">\n <span class="icon">📈</span>\n <h3>Comparable Benchmarks</h3>\n </div>\n <p style="font-size:0.8rem; color:var(--dim); margin-bottom:1.25rem;">\n How this codebase compares to typical trust scores at each funding stage.\n The <span style="color:var(--cyan)">cyan marker</span> indicates this codebase's score of <strong>${e.score}/100</strong>.\n </p>\n <div style="background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:1.5rem 2rem;">\n ${P}\n </div>\n</div>\n`}\n\n${r+o>0&&"free"!==e.tier?`\n<div class="page-break"></div>\n\x3c!-- Hallucination Detail --\x3e\n<div class="section">\n <div class="section-header">\n <span class="icon">🔮</span>\n <h3>AI Hallucination Detail</h3>\n </div>\n <p style="font-size:0.85rem; color:var(--dim); margin-bottom:1rem;">\n These API calls reference methods, modules, or endpoints that do not exist in the libraries being used.\n They were likely generated by an AI coding tool and will fail at runtime.\n </p>\n <table>\n <thead>\n <tr><th>Severity</th><th>Location</th><th>API Call</th><th>Impact</th></tr>\n </thead>\n <tbody>${I}</tbody>\n </table>\n</div>\n`:""}\n\n${a>0?`\n\x3c!-- Ghost Code Detail --\x3e\n<div class="section">\n <div class="section-header">\n <span class="icon">👻</span>\n <h3>Ghost Code — Dead Functions</h3>\n </div>\n <p style="font-size:0.85rem; color:var(--dim); margin-bottom:1rem;">\n ${a} function${a>1?"s":""} exist in the codebase but are never called.\n This represents ${i.toLocaleString()} wasted lines of code (${e.ghostResults.wastedPercent||"?"}% of the codebase).\n </p>\n <table>\n <thead>\n <tr><th>Location</th><th>Function</th><th>Size</th><th>References</th></tr>\n </thead>\n <tbody>${A}</tbody>\n </table>\n</div>\n`:""}\n\n\x3c!-- Technical Debt Cost --\x3e\n<div class="section">\n <div class="section-header">\n <span class="icon">📈</span>\n <h3>Technical Debt Cost Analysis</h3>\n </div>\n <div class="cost-box">\n <div class="cost-grid">\n <div class="cost-item cost-manual">\n <div class="cost-value">£${u.toLocaleString()}</div>\n <div class="cost-label">Manual fix cost (${m} dev-hours)</div>\n </div>\n <div class="cost-item cost-thuban">\n <div class="cost-value">${g}h</div>\n <div class="cost-label">Fix time with Thuban auto-fix</div>\n </div>\n <div class="cost-item cost-saving">\n <div class="cost-value">£${h.toLocaleString()}</div>\n <div class="cost-label">Potential saving (${p}%)</div>\n </div>\n </div>\n </div>\n</div>\n\n\x3c!-- Confidentiality Notice --\x3e\n<div class="confidentiality">\n <strong>CONFIDENTIAL</strong><br>\n This report was generated by Thuban Code Health Engine for investment due diligence purposes.\n Distribution should be limited to authorised investment committee members.\n Thuban does not provide investment advice. This report reflects automated code analysis only.\n</div>\n\n\x3c!-- Footer --\x3e\n<div class="report-footer">\n <div>\n <strong>Thuban</strong> — Code Health Engine<br>\n <a href="https://thuban.dev">thuban.dev</a> | A Silverwings product\n </div>\n <div style="text-align:right;">\n Report: ${e.reportId}<br>\n This report was generated automatically.<br>\n For full details, run: <code style="font-family:var(--mono); color:var(--cyan);">npx thuban scan .</code>\n </div>\n</div>\n\n</body>\n</html>`}_esc(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}save(e,n){const t=n||this.rootPath,s=path.resolve(t),r=path.resolve(this.rootPath);if(!s.startsWith(r+path.sep)&&s!==r)throw new Error(`Output directory must be within the project root: ${r}`);const o=`thuban-investor-report-${this.generatedAt.toISOString().split("T")[0]}.html`,a=path.join(s,o);return fs.writeFileSync(a,e,"utf-8"),a}}module.exports=InvestorReport;
|