ultracode 5.4.0 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/chunks/analysis-tool-handlers-GH5FDEWW.js +817 -0
  2. package/dist/chunks/analysis-tool-handlers-IXP4MWZX.js +817 -0
  3. package/dist/chunks/analysis-tool-handlers-LC2BTQYK.js +13 -0
  4. package/dist/chunks/analysis-tool-handlers-QYFKQPFL.js +817 -0
  5. package/dist/chunks/autodoc-tool-handlers-2HF6ERYN.js +1112 -0
  6. package/dist/chunks/autodoc-tool-handlers-4OGQJ7C3.js +1112 -0
  7. package/dist/chunks/autodoc-tool-handlers-N736CB56.js +138 -0
  8. package/dist/chunks/autodoc-tool-handlers-NQYBY6U4.js +1112 -0
  9. package/dist/chunks/branch-tool-handlers-KW3H4FJK.js +276 -0
  10. package/dist/chunks/branch-tool-handlers-QOUDZKJ2.js +276 -0
  11. package/dist/chunks/branch-tool-handlers-RB2U36KI.js +2 -0
  12. package/dist/chunks/branch-tool-handlers-ZHJM6PDK.js +276 -0
  13. package/dist/chunks/chunk-2Z6OQPYC.js +656 -0
  14. package/dist/chunks/chunk-3MQ7LRPN.js +322 -0
  15. package/dist/chunks/chunk-4W6QYGXZ.js +10 -0
  16. package/dist/chunks/chunk-533NFGUG.js +1 -0
  17. package/dist/chunks/chunk-5NUPOPWM.js +1 -0
  18. package/dist/chunks/chunk-AK4HIPA2.js +322 -0
  19. package/dist/chunks/chunk-B3H5NS3I.js +656 -0
  20. package/dist/chunks/chunk-DPTZHDST.js +4 -0
  21. package/dist/chunks/chunk-E5HQWLU5.js +322 -0
  22. package/dist/chunks/chunk-EOH25B5P.js +572 -0
  23. package/dist/chunks/chunk-ESV6F6E3.js +3179 -0
  24. package/dist/chunks/chunk-FPELPFER.js +924 -0
  25. package/dist/chunks/chunk-G6J42I55.js +161 -0
  26. package/dist/chunks/chunk-GCQE7ZYW.js +1 -0
  27. package/dist/chunks/chunk-GTIF6MOX.js +1 -0
  28. package/dist/chunks/chunk-I6STSSAK.js +2 -0
  29. package/dist/chunks/chunk-J2WBGTK2.js +4697 -0
  30. package/dist/chunks/chunk-KAYOX5EB.js +4697 -0
  31. package/dist/chunks/chunk-KPMTACOT.js +656 -0
  32. package/dist/chunks/chunk-L376GZ44.js +3179 -0
  33. package/dist/chunks/chunk-LCTOTHDA.js +15 -0
  34. package/dist/chunks/chunk-LEDJ7GVQ.js +316 -0
  35. package/dist/chunks/chunk-LH4OUKNZ.js +277 -0
  36. package/dist/chunks/chunk-O6IE2MEZ.js +161 -0
  37. package/dist/chunks/chunk-OEXPCY3F.js +316 -0
  38. package/dist/chunks/chunk-OMXOLFDN.js +924 -0
  39. package/dist/chunks/chunk-PLPBXWOU.js +3179 -0
  40. package/dist/chunks/chunk-PWLE5DN2.js +572 -0
  41. package/dist/chunks/chunk-PY43JPWL.js +447 -0
  42. package/dist/chunks/chunk-Q3B4EB7A.js +15 -0
  43. package/dist/chunks/chunk-Q5LPVLXA.js +337 -0
  44. package/dist/chunks/chunk-QIRZHZK2.js +5 -0
  45. package/dist/chunks/chunk-ROQ27LSL.js +924 -0
  46. package/dist/chunks/chunk-S5Q7BD6J.js +572 -0
  47. package/dist/chunks/chunk-SAMX3HJQ.js +337 -0
  48. package/dist/chunks/chunk-SV3WKUNV.js +1 -0
  49. package/dist/chunks/chunk-TCHCDCDO.js +167 -0
  50. package/dist/chunks/chunk-TR3HS7U6.js +316 -0
  51. package/dist/chunks/chunk-TUWE6FCW.js +167 -0
  52. package/dist/chunks/chunk-TVOTA7EE.js +277 -0
  53. package/dist/chunks/chunk-VS44D772.js +337 -0
  54. package/dist/chunks/chunk-WIE3G5ES.js +167 -0
  55. package/dist/chunks/chunk-XG3ACLWR.js +5 -0
  56. package/dist/chunks/chunk-XJ2Z5QQO.js +1 -0
  57. package/dist/chunks/chunk-XK2NY7RB.js +277 -0
  58. package/dist/chunks/chunk-Y4F7NZFZ.js +4700 -0
  59. package/dist/chunks/chunk-YS75L3ZS.js +161 -0
  60. package/dist/chunks/chunk-ZVG5HHI3.js +15 -0
  61. package/dist/chunks/dev-agent-DDDIVWOF.js +1 -0
  62. package/dist/chunks/dev-agent-E2VCFKXN.js +1624 -0
  63. package/dist/chunks/dev-agent-KJNSU5KQ.js +1624 -0
  64. package/dist/chunks/dev-agent-NDERYIPV.js +1624 -0
  65. package/dist/chunks/faiss-provider-7R4BQDIV.js +12 -0
  66. package/dist/chunks/faiss-provider-7ZFRSDN5.js +12 -0
  67. package/dist/chunks/faiss-provider-SXB7FTLB.js +1 -0
  68. package/dist/chunks/faiss-provider-TKLBEUSH.js +12 -0
  69. package/dist/chunks/file-tool-handlers-5DODQXGF.js +1027 -0
  70. package/dist/chunks/file-tool-handlers-KGHLE4KR.js +1027 -0
  71. package/dist/chunks/file-tool-handlers-KTOQ4NFS.js +12 -0
  72. package/dist/chunks/file-tool-handlers-V4SFUDQB.js +1027 -0
  73. package/dist/chunks/graph-metrics-tool-handlers-3AV4X4ZY.js +65 -0
  74. package/dist/chunks/graph-metrics-tool-handlers-3VMDQHJ6.js +65 -0
  75. package/dist/chunks/graph-metrics-tool-handlers-BZ6E6YHF.js +1 -0
  76. package/dist/chunks/graph-metrics-tool-handlers-IYBGSXL7.js +65 -0
  77. package/dist/chunks/graph-storage-factory-2CQ2RPDV.js +13 -0
  78. package/dist/chunks/graph-storage-factory-C5SMMYL6.js +13 -0
  79. package/dist/chunks/graph-storage-factory-EEO2V3GJ.js +1 -0
  80. package/dist/chunks/graph-storage-factory-WBCTXP34.js +13 -0
  81. package/dist/chunks/history-tool-handlers-AS7OQFZI.js +1 -0
  82. package/dist/chunks/history-tool-handlers-FSNJYXV2.js +208 -0
  83. package/dist/chunks/history-tool-handlers-JZAH4EIQ.js +208 -0
  84. package/dist/chunks/history-tool-handlers-KCSCXZ7T.js +208 -0
  85. package/dist/chunks/incremental-updater-A2EL4QXU.js +14 -0
  86. package/dist/chunks/incremental-updater-EQIKBVY2.js +14 -0
  87. package/dist/chunks/incremental-updater-JFGRPH3B.js +14 -0
  88. package/dist/chunks/incremental-updater-S5BAAGHP.js +1 -0
  89. package/dist/chunks/indexer-agent-ASKY7JPG.js +1 -0
  90. package/dist/chunks/indexer-agent-NKAOF323.js +21 -0
  91. package/dist/chunks/indexer-agent-PJN5IOKQ.js +21 -0
  92. package/dist/chunks/indexer-agent-WRJFWKZX.js +21 -0
  93. package/dist/chunks/indexing-pipeline-D4P2O72Z.js +249 -0
  94. package/dist/chunks/indexing-pipeline-L7C543N4.js +1 -0
  95. package/dist/chunks/indexing-pipeline-NHPRN3AB.js +249 -0
  96. package/dist/chunks/indexing-pipeline-ZAXCZU22.js +249 -0
  97. package/dist/chunks/layered-faiss-provider-62CNW54X.js +1 -0
  98. package/dist/chunks/layered-faiss-provider-O7L77GFX.js +12 -0
  99. package/dist/chunks/layered-faiss-provider-RVHLHLPK.js +12 -0
  100. package/dist/chunks/layered-faiss-provider-YT7EDIJI.js +12 -0
  101. package/dist/chunks/merge-agent-3RF7VFF5.js +2481 -0
  102. package/dist/chunks/merge-agent-JCKTCBCE.js +2481 -0
  103. package/dist/chunks/merge-agent-VCL7OXPN.js +2481 -0
  104. package/dist/chunks/merge-agent-ZGK24WVF.js +11 -0
  105. package/dist/chunks/merge-tool-handlers-GV2LOIKU.js +277 -0
  106. package/dist/chunks/merge-tool-handlers-TYDWU5X2.js +277 -0
  107. package/dist/chunks/merge-tool-handlers-U7X2ZO2M.js +1 -0
  108. package/dist/chunks/merge-tool-handlers-YH62ZLPJ.js +277 -0
  109. package/dist/chunks/pattern-tool-handlers-76NF5JDS.js +13 -0
  110. package/dist/chunks/pattern-tool-handlers-IJAGEIVD.js +1549 -0
  111. package/dist/chunks/pattern-tool-handlers-VA5WYA62.js +1549 -0
  112. package/dist/chunks/pattern-tool-handlers-WQ6UBMJS.js +1549 -0
  113. package/dist/chunks/query-agent-36ADGCFZ.js +1 -0
  114. package/dist/chunks/query-agent-H22CR5N5.js +191 -0
  115. package/dist/chunks/query-agent-K2UGZS4M.js +191 -0
  116. package/dist/chunks/query-agent-YJCEHOXD.js +191 -0
  117. package/dist/chunks/semantic-agent-AC7CBEDE.js +6381 -0
  118. package/dist/chunks/semantic-agent-HK5X6CKU.js +6381 -0
  119. package/dist/chunks/semantic-agent-KONIKEGW.js +6381 -0
  120. package/dist/chunks/semantic-agent-LH6IZ2L7.js +137 -0
  121. package/dist/chunks/semantic-tool-handlers-5LMSH2U7.js +3 -0
  122. package/dist/chunks/semantic-tool-handlers-735UMO7Y.js +817 -0
  123. package/dist/chunks/semantic-tool-handlers-BNUYPP7X.js +817 -0
  124. package/dist/chunks/semantic-tool-handlers-MYZPEUD2.js +817 -0
  125. package/dist/chunks/snapshot-tool-handlers-6SIHZT2F.js +201 -0
  126. package/dist/chunks/snapshot-tool-handlers-DS4P3KOT.js +201 -0
  127. package/dist/chunks/snapshot-tool-handlers-JYHRFPC7.js +201 -0
  128. package/dist/chunks/snapshot-tool-handlers-YEHMAT3L.js +1 -0
  129. package/dist/chunks/storage-paths-A3C7WHHG.js +8 -0
  130. package/dist/chunks/storage-paths-HDYH7WPM.js +1 -0
  131. package/dist/chunks/storage-paths-IMFRHBWF.js +8 -0
  132. package/dist/chunks/storage-paths-P3PUSMUD.js +8 -0
  133. package/dist/chunks/taint-tool-handlers-CWESOOMQ.js +68 -0
  134. package/dist/chunks/taint-tool-handlers-OG3NVVP3.js +1 -0
  135. package/dist/chunks/taint-tool-handlers-ON3G3FA7.js +68 -0
  136. package/dist/chunks/taint-tool-handlers-P4P5J6DB.js +68 -0
  137. package/dist/chunks/tracing-tool-handlers-4BDCXTZZ.js +3935 -0
  138. package/dist/chunks/tracing-tool-handlers-6FPNM7HX.js +3935 -0
  139. package/dist/chunks/tracing-tool-handlers-LQTQ5SKK.js +89 -0
  140. package/dist/chunks/tracing-tool-handlers-XRQX2DTS.js +3935 -0
  141. package/dist/chunks/validation-tool-handlers-DZUG7KYY.js +2 -0
  142. package/dist/chunks/validation-tool-handlers-O6TGFSH5.js +555 -0
  143. package/dist/chunks/validation-tool-handlers-RREUYKIR.js +555 -0
  144. package/dist/chunks/validation-tool-handlers-XPWSMS37.js +555 -0
  145. package/dist/index.js +13 -13
  146. package/dist/roslyn-addon/.build-hash +1 -1
  147. package/dist/roslyn-addon/ILGPU.Algorithms.dll +0 -0
  148. package/dist/roslyn-addon/ILGPU.dll +0 -0
  149. package/dist/roslyn-addon/UltraCode.CSharp.deps.json +35 -0
  150. package/dist/roslyn-addon/UltraCode.CSharp.dll +0 -0
  151. package/package.json +1 -1
@@ -0,0 +1,89 @@
1
+ import {a as a$1}from'./chunk-VPT6ZBZV.js';import {a}from'./chunk-W5ZEGGQZ.js';import {d}from'./chunk-XG3ACLWR.js';import'./chunk-XJ2Z5QQO.js';import'./chunk-LESND2CW.js';import'./chunk-QUO46LUP.js';import'./chunk-SV3WKUNV.js';import'./chunk-PZF7YC35.js';import {R as R$1,I as I$1}from'./chunk-4BI7EBPQ.js';import'./chunk-DXB73IDG.js';import {z as z$1}from'zod';R$1();var mt=[/^if\s*\([^)]+\)\s*(return|throw)/,/^\s*(return|throw)\s+if/,/^guard\s+/,/^unless\s+/],yt=[/valid/i,/check/i,/verify/i,/assert/i,/ensure/i,/require/i],N=class{storage;decisionPointCache=new Map;constructor(t){this.storage=t;}async findDecisionPoints(t){let{scenario:e,includeGuards:n=true,includeEffects:i=true,groupBy:a="impact"}=t,o=`${e}:${n}:${i}`,s=this.decisionPointCache.get(o),r=await this.findEntryPoints(e),c=[];if(s){let f=s.filter(u=>r.some(y=>u.location.startsWith(y.filePath)));f.length>0&&c.push(...f);}if(c.length===0){let f=r.map(async y=>{let w=new Set;return this.collectDecisionPoints(y.id,w,n,i)}),u=await Promise.all(f);for(let y of u)c.push(...y);this.decisionPointCache.set(o,c);}let l=this.deduplicateDecisionPoints(c),d=this.sortDecisionPoints(l,a),p=this.generateFlowDiagram(d,r),g=this.calculateSummary(d);return {scenario:e,entryPoints:r.map(f=>({name:f.name,file:f.filePath})),decisionPoints:d,flowDiagram:{mermaid:p},summary:g}}async findEntryPoints(t){let e=await this.storage.searchEntities({namePattern:t});if(e.length>0)return e.slice(0,5);let n=t.split(/\s+/);for(let i of n){let a=await this.storage.searchEntities({namePattern:i});if(a.length>0)return a.slice(0,5)}return []}async collectDecisionPoints(t,e,n,i,a=0,o=10){if(e.has(t)||a>o)return [];e.add(t);let s=[],r=await this.storage.getEntity(t);if(!r)return s;let c=this.extractDecisionPoints(r,n,i);s.push(...c);let l=await this.storage.getRelationshipsForEntity(t,"calls");for(let d of l)if(d.fromId===t){let p=await this.collectDecisionPoints(d.toId,e,n,i,a+1,o);s.push(...p);}return s}extractDecisionPoints(t,e,n){let i=[],a=t.metadata,o=0;if(a.controlFlow?.branches&&Array.isArray(a.controlFlow.branches))for(let s of a.controlFlow.branches){let r=this.classifyConditionType(s.condition,t.name);if(r==="guard"&&!e)continue;let c={id:`dp-${t.id}-${o++}`,location:`${t.filePath}:${t.location.start.line}`,type:r,condition:s.condition,outcomes:this.buildOutcomes(s),impact:this.assessImpact(r,s),dataDepends:this.extractDataDependencies(s.condition),triggeredBy:t.name};n&&s.effects&&(c.effects=s.effects),i.push(c);}if(a.controlFlow?.loops&&Array.isArray(a.controlFlow.loops))for(let s of a.controlFlow.loops)i.push({id:`dp-${t.id}-${o++}`,location:`${t.filePath}:${t.location.start.line}`,type:"loop",condition:s.condition,outcomes:{continue:"Next iteration",break:"Exit loop"},impact:"medium",dataDepends:this.extractDataDependencies(s.condition||""),triggeredBy:t.name});if(a.controlFlow?.exceptions&&Array.isArray(a.controlFlow.exceptions))for(let s of a.controlFlow.exceptions)i.push({id:`dp-${t.id}-${o++}`,location:`${t.filePath}:${t.location.start.line}`,type:"error_handling",action:`catch ${s.type||"Error"}`,outcomes:{caught:"Handle error",rethrown:"Propagate error"},impact:"high",dataDepends:[],triggeredBy:t.name});return i}classifyConditionType(t,e){return yt.some(n=>n.test(t)||n.test(e))?"validation":mt.some(n=>n.test(t))?"guard":t.includes("set")||t.includes("update")||t.includes("=")?"state_mutation":t.includes("response")||t.includes("status")||t.includes("error")?"api_response":t.includes("feature")||t.includes("flag")||t.includes("enabled")?"feature_flag":"guard"}buildOutcomes(t){let e={};if(e.true=t.target||"continue",e.false="skip",t.condition.includes("===")||t.condition.includes("==")){let n=t.condition.split(/===?/);n.length===2&&(e[`${n[1]?.trim()}`]=t.target||"match");}return e}assessImpact(t,e){return t==="validation"&&e.target==="throw"||t==="api_response"&&e.condition.includes("error")?"critical":t==="guard"||t==="error_handling"?"high":t==="state_mutation"||t==="feature_flag"?"medium":"low"}extractDataDependencies(t){if(!t)return [];let e=[],n=/\b([a-z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*)\b/g,i=new Set(["if","else","true","false","null","undefined","and","or","not","in","of","typeof","instanceof","return","throw","new","this","super"]),a;for(;(a=n.exec(t))!==null;){let o=a[1];!i.has(o)&&!i.has(o.split(".")[0])&&e.push(o);}return [...new Set(e)]}analyzeConditions(t){let e=0,n=0,i=new Set;for(let a of t)for(let o of a.steps)o.action==="condition"&&(n++,o.branches&&Object.values(o.branches).some(r=>r==="return"||r==="throw")&&e++,o.condition&&i.add(o.condition)),o.action==="guard"&&e++;return {guards:e,branches:n,criticalConditions:Array.from(i)}}deduplicateDecisionPoints(t){let e=new Map;for(let n of t){let i=`${n.location}:${n.condition||n.action}`;e.has(i)||e.set(i,n);}return Array.from(e.values())}sortDecisionPoints(t,e){let n={critical:0,high:1,medium:2,low:3};switch(e){case "impact":return t.sort((i,a)=>n[i.impact]-n[a.impact]);case "type":return t.sort((i,a)=>i.type.localeCompare(a.type));default:return t.sort((i,a)=>i.location.localeCompare(a.location))}}calculateSummary(t){let e=0,n=new Set;for(let i of t)if(e+=Object.keys(i.outcomes).length,i.type==="state_mutation"&&i.dataDepends)for(let a of i.dataDepends)n.add(a);return {totalDecisionPoints:t.length,criticalPoints:t.filter(i=>i.impact==="critical").length,possibleOutcomes:e,statesModified:Array.from(n)}}generateFlowDiagram(t,e){let n=["flowchart TD"];for(let s=0;s<e.length;s++){let r=e[s];n.push(` E${s}[${this.sanitizeMermaidLabel(r.name)}]`);}let i=new Map;for(let s of t){let r=s.triggeredBy||"unknown";i.has(r)||i.set(r,[]),i.get(r).push(s);}let a=0,o=new Map;for(let[s,r]of i){n.push(` subgraph ${this.sanitizeMermaidLabel(s)}`);for(let c of r){let l=`D${a++}`;o.set(c.id,l);let d=this.getNodeShape(c.type),p=c.condition?this.sanitizeMermaidLabel(c.condition.substring(0,30)):c.action||c.type;n.push(` ${l}${d.open}${p}${d.close}`);for(let[g,f]of Object.entries(c.outcomes))n.push(` ${l} -->|${g}| ${l}_${this.sanitizeMermaidLabel(f)}`);}n.push(" end");}for(let s=0;s<e.length;s++){let r=e[s].name,c=i.get(r)?.[0];if(c){let l=o.get(c.id);l&&n.push(` E${s} --> ${l}`);}}return n.join(`
2
+ `)}getNodeShape(t){switch(t){case "validation":case "guard":return {open:"{",close:"}"};case "error_handling":return {open:"[[",close:"]]"};case "loop":return {open:"((",close:"))"};case "state_mutation":return {open:"[/",close:"/]"};case "feature_flag":return {open:"{{",close:"}}"};default:return {open:"[",close:"]"}}}sanitizeMermaidLabel(t){return t.replace(/["\n\r]/g," ").replace(/[{}[\]<>|]/g,"").trim().substring(0,50)}clearCache(){this.decisionPointCache.clear();}};var G={SETTER:/^set[A-Z]/,BOOLEAN:/^(is|has|should|can|will)[A-Z]/},I=class{storage;constructor(t){this.storage=t;}async detectStateChanges(t){let e=[],n=t.metadata;if(Array.isArray(n.stateModifications))for(let i of n.stateModifications)e.push({variable:i,isMutation:true});if(Array.isArray(n.assignments))for(let i of n.assignments)e.push({variable:i.target,from:i.from,to:i.to,isMutation:i.isMutation??false});if(Array.isArray(n.calls)){for(let i of n.calls)if(this.isMutatingCall(i.name)){let a=this.extractMutationTarget(i);a&&e.push({variable:a,isMutation:true});}}return e}async detectStateReads(t){let e=new Set,n=t.metadata;if(Array.isArray(n.stateReads))for(let i of n.stateReads)e.add(i);if(Array.isArray(n.parameters))for(let i of n.parameters)e.add(i.name);if(n.controlFlow?.branches&&Array.isArray(n.controlFlow.branches))for(let i of n.controlFlow.branches){let a=this.extractStatesFromCondition(i.condition);for(let o of a)e.add(o);}return Array.from(e)}isMutatingCall(t){let e=["push","pop","shift","unshift","splice","set","delete","clear","add","remove","assign","extend","update","modify"],n=t.toLowerCase();return e.some(i=>n.includes(i))||G.SETTER.test(t)}extractMutationTarget(t){if(t.target)return t.target;let e=t.name.match(/^set([A-Z]\w*)/);return e?e[1].charAt(0).toLowerCase()+e[1].slice(1):null}extractStatesFromCondition(t){if(!t)return [];let e=[],n=/\b([a-z_][a-zA-Z0-9_]*)\b/g,i=new Set(["if","else","true","false","null","undefined","and","or","not","in","of","typeof","instanceof"]),a;for(;(a=n.exec(t))!==null;)i.has(a[1])||e.push(a[1]);return e}async analyzeStateImpact(t){let{state:e,scenarios:n}=t,i=await this.findStateUsages(e),a={};for(let r of n)a[r.label]=await this.analyzeScenario(e,r.value,i);let o=this.detectConflicts(e,i),s=await this.calculateRippleEffects(e,i);return {state:e,usages:i,scenarioAnalysis:a,conflicts:o,rippleEffects:s}}async findStateUsages(t){let e=[],n=await this.storage.getAllEntities();for(let i of n){let a=i.metadata;if(Array.isArray(a.stateReads)&&a.stateReads.includes(t)&&e.push({location:`${i.filePath}:${i.location.start.line}`,usage:"read",code:i.name,entityName:i.name}),Array.isArray(a.stateModifications)&&a.stateModifications.includes(t)&&e.push({location:`${i.filePath}:${i.location.start.line}`,usage:"assignment",code:i.name,entityName:i.name}),a.controlFlow?.branches&&Array.isArray(a.controlFlow.branches))for(let o of a.controlFlow.branches)o.condition?.includes(t)&&e.push({location:`${i.filePath}:${i.location.start.line}`,usage:"condition",code:o.condition,entityName:i.name});Array.isArray(a.parameters)&&a.parameters.some(o=>o!==null&&typeof o=="object"&&"name"in o&&o.name===t)&&e.push({location:`${i.filePath}:${i.location.start.line}`,usage:"parameter",code:i.name,entityName:i.name});}return e}async analyzeScenario(t,e,n){let i=[],a=[],o=[],s=[];for(let r of n)r.usage==="condition"&&(this.simulateCondition(r.code,e)?i.push(`${r.entityName}: ${r.code} \u2192 true`):a.push(`${r.entityName}: ${r.code} \u2192 false`)),r.usage==="assignment"&&s.push(`${r.entityName} modifies state`);for(let r of i){let c=this.inferFeatureFromPath(r);c&&o.push(c);}return {reachablePaths:i,blockedPaths:a,enabledFeatures:o,stateChanges:s}}simulateCondition(t,e){return t.includes("=== true")||t.includes("== true")?e===true:t.includes("=== false")||t.includes("== false")?e===false:t.includes("!")?!e:!!e}inferFeatureFromPath(t){let e=t.match(/^(\w+):/);return e?e[1]:null}detectConflicts(t,e){let n=[],i=e.filter(s=>s.usage==="assignment");i.length>1&&n.push({description:`Multiple assignment points for '${t}'`,location:i.map(s=>s.location).join(", "),risk:"medium",recommendation:"Ensure clear assignment order or use single source of truth"});let a=e.filter(s=>s.usage==="condition"),o=i.length>0;return a.length>0&&!o&&n.push({description:`State '${t}' read but never set in analyzed scope`,location:a[0].location,risk:"high",recommendation:"Verify state is initialized before use"}),n}async calculateRippleEffects(t,e){let n=new Set;for(let o of e)o.entityName&&n.add(o.entityName);let i=n.size,a=0;for(let o of n){let s=await this.storage.searchEntities({namePattern:o});if(s.length>0){let r=await this.storage.getRelationshipsForEntity(s[0].id,"calls");a+=r.length;}}return {directEffects:i,indirectEffects:a,affectedComponents:Array.from(n)}}async buildStateDependencies(t){let e=await this.storage.getEntity(t);if(!e)return [];let n=[],i=await this.detectStateReads(e);for(let a of i){let o=await this.findModifiers(a);n.push({state:a,modifiedBy:o,stateType:this.inferType(a)});}return n}async findModifiers(t){let e=[],n=await this.storage.getAllEntities();for(let i of n){let a=i.metadata;Array.isArray(a.stateModifications)&&a.stateModifications.includes(t)&&e.push(i.name),G.SETTER.test(i.name)&&i.name.replace(/^set/,"").toLowerCase()===t.toLowerCase()&&e.push(i.name);}return e}inferType(t){return G.BOOLEAN.test(t)?"boolean":t.endsWith("Count")||t.endsWith("Index")?"number":t.endsWith("List")||t.endsWith("Array")?"array":t.endsWith("Map")||t.endsWith("Dict")?"object":"unknown"}clearCache(){}};var wt=15,St={API:/fetch|axios|http|request|api/i,STORAGE:/localStorage|sessionStorage|cookie|database|db/i,PROPS:/props|input|param/i,STATE:/state|store|redux|context/i,CONFIG:/config|settings|env|options/i,USER_INPUT:/input|form|event|click/i},bt={PARSE:/parse|decode|deserialize|from(JSON|XML|YAML)/i,MAP:/\.map\(|\.reduce\(|\.filter\(|transform/i,VALIDATE:/valid|check|verify|assert|ensure/i,NORMALIZE:/normaliz|sanitiz|clean|format/i,MERGE:/merge|combine|assign|spread/i},j=class{storage;semanticSearch;stateTracker;constructor(t,e){this.storage=t,this.semanticSearch=e,this.stateTracker=new I(t);}async traceDataFlow(t){let{entryPoint:e,targetState:n,dataSources:i,trackTransformations:a=true}=t,o=await this.findEntity(e);if(!o)throw new Error(`Entry point not found: ${e}`);let s=i&&i.length>0?i:await this.identifyDataSources(o),r=[],c=new Set;for(let p of s){let g=await this.traceSourceToTarget(p,n,o,a);if(g){r.push(g);for(let f of g.criticalConditions)c.add(f);}}let l=await this.buildBehaviorMatrix(r,n),d={dataSourcesAnalyzed:s.length,branchingPoints:r.reduce((p,g)=>p+g.flow.filter(f=>f.action==="branch").length,0),possibleOutcomes:l.combinations.length,criticalDecisions:Array.from(c)};return {entryPoint:e,targetState:n,dataFlows:r,behaviorMatrix:l,summary:d}}async identifyDataSources(t){let e=[],n=t.metadata;if(Array.isArray(n.parameters))for(let i of n.parameters)e.push(i.name);if(Array.isArray(n.calls))for(let i of n.calls){let a=this.classifyDataSource(i.name);a&&e.push(`${a}:${i.name}`);}if(Array.isArray(n.stateReads))for(let i of n.stateReads)e.push(`state:${i}`);return e}classifyDataSource(t){for(let[e,n]of Object.entries(St))if(n.test(t))return e.toLowerCase();return null}async traceSourceToTarget(t,e,n,i){let a=[],o=[],s=new Set,r=n,c=1,l=t;for(;r&&c<=wt&&!s.has(r.id);){s.add(r.id);let p=r.metadata;if(i&&Array.isArray(p.calls))for(let f of p.calls){let u=this.classifyTransformation(f.name);u&&(a.push({step:c++,location:`${r.filePath}:${r.location.start.line}`,action:u,input:l,output:`transformed(${l})`,transformation:f.name}),l=`transformed(${l})`);}if(p.controlFlow?.branches&&Array.isArray(p.controlFlow.branches))for(let f of p.controlFlow.branches)this.conditionInvolvesData(f.condition,t)&&(a.push({step:c++,location:`${r.filePath}:${r.location.start.line}`,action:"branch",condition:f.condition,branches:{true:f.target||"continue",false:"skip"}}),o.push(f.condition));if(Array.isArray(p.stateModifications)&&p.stateModifications.includes(e)){a.push({step:c++,location:`${r.filePath}:${r.location.start.line}`,action:"setState",input:l,output:e});break}r=await this.findNextInFlow(r,l);}let d=a.some(p=>p.action==="setState"&&p.output===e);return a.length===0?null:{source:t,flow:a,affectsTarget:d,criticalConditions:o}}classifyTransformation(t){for(let[e,n]of Object.entries(bt))if(n.test(t))switch(e){case "PARSE":return "parse";case "MAP":return "transform";case "VALIDATE":return "validate";default:return "transform"}return null}conditionInvolvesData(t,e){if(!t||!e)return false;let n=e.split(":").pop()||e;return t.toLowerCase().includes(n.toLowerCase())}async findNextInFlow(t,e){let n=await this.storage.getRelationshipsForEntity(t.id,"calls");for(let i of n)if(i.fromId===t.id){let a=await this.storage.getEntity(i.toId);if(a){let o=i.metadata;if(Array.isArray(o?.arguments)&&o.arguments.includes(e)||this.entityHandlesData(a,e))return a}}return null}entityHandlesData(t,e){let n=t.metadata,i=e.split(":").pop()||e;return !!(Array.isArray(n.parameters)&&n.parameters.some(a=>a!==null&&typeof a=="object"&&"name"in a&&typeof a.name=="string"&&a.name.toLowerCase().includes(i.toLowerCase()))||Array.isArray(n.stateReads)&&n.stateReads.some(a=>a.toLowerCase().includes(i.toLowerCase())))}async buildBehaviorMatrix(t,e){let n=[],i=[];for(let o of t)for(let s of o.flow)s.action==="branch"&&s.condition&&i.push({source:o.source,condition:s.condition});let a=Math.min(2**i.length,16);for(let o=0;o<a;o++){let s={},r=[];for(let d=0;d<i.length;d++){let p=i[d],g=(o&1<<d)!==0;s[`${p.source}:${p.condition}`]=g,r.push(`${p.condition}=${g}`);}let c={},l=false;for(let d of t)d.affectsTarget&&this.evaluateFlowWithConditions(d,s)&&(c[e]=`from ${d.source}`,l=true);l||(c[e]="unchanged"),n.push({inputs:s,result:c,path:r.join(" \u2192 ")});}return {combinations:n}}evaluateFlowWithConditions(t,e){for(let n of t.flow)if(n.action==="branch"&&n.condition){let i=`${t.source}:${n.condition}`;if(e[i]===false&&(n.branches?.false==="skip"||n.branches?.false==="return"))return false}return true}async findEntity(t){let e=await this.storage.searchEntities({namePattern:t});if(e.length>0)return e[0];if(this.semanticSearch)try{let n=await this.semanticSearch.search(t,{limit:1,minSimilarity:.6});if(n.length>0)return this.storage.getEntity(n[0].entityId)}catch{}return null}clearCache(){this.stateTracker.clearCache();}};var C=class{formatTraceFlowAsText(t){let e=[];if(e.push(`\u2550\u2550\u2550 Trace Flow: ${t.from} \u2192 ${t.to} \u2550\u2550\u2550`),e.push(""),t.paths.length===0){if(e.push("\u274C No paths found between these points."),t._debug&&typeof t._debug=="object"){let n=t._debug;e.push(""),e.push("--- Debug Info ---"),e.push(`Source: ${n.sourceEntityName} (${n.sourceEntityId})`),e.push(`Target: ${n.targetEntityName} (${n.targetEntityId})`);let i=n.graphStats;e.push(`Graph: ${i?.nodes} nodes, ${i?.edges} edges`),e.push(`Linear trace: ${n.linearTraceSummary}`),e.push(`Nodes visited: ${n.nodesVisited}`);}return e.join(`
3
+ `)}e.push(`Found ${t.paths.length} path(s):`),e.push("");for(let n=0;n<t.paths.length;n++){let i=t.paths[n];e.push(`\u2500\u2500\u2500 Path ${n+1} (confidence: ${Math.round(i.confidence*100)}%) \u2500\u2500\u2500`),e.push(`Summary: ${i.summary}`),e.push("");for(let a of i.steps){let o=this.formatStep(a);e.push(o);}if(i.warnings&&i.warnings.length>0){e.push(""),e.push("\u26A0\uFE0F Warnings:");for(let a of i.warnings)e.push(` \u2022 ${a}`);}e.push("");}return (t.statesSummary.modified.length>0||t.statesSummary.read.length>0)&&(e.push("\u2500\u2500\u2500 States \u2500\u2500\u2500"),t.statesSummary.modified.length>0&&e.push(`Modified: ${t.statesSummary.modified.join(", ")}`),t.statesSummary.read.length>0&&e.push(`Read: ${t.statesSummary.read.join(", ")}`),t.statesSummary.critical.length>0&&e.push(`Critical: ${t.statesSummary.critical.join(", ")}`),e.push("")),t.conditionsSummary.branches>0&&(e.push("\u2500\u2500\u2500 Conditions \u2500\u2500\u2500"),e.push(`Guards: ${t.conditionsSummary.guards}`),e.push(`Branches: ${t.conditionsSummary.branches}`),t.conditionsSummary.criticalConditions.length>0&&e.push(`Critical: ${t.conditionsSummary.criticalConditions.join("; ")}`),e.push("")),e.join(`
4
+ `)}formatStep(t){let e=` ${t.order}. `,n=this.getStepIcon(t.action),i=`${e}${n} ${t.entity}`;if(i+=` (${t.file}:${t.line})`,t.condition&&(i+=`
5
+ \u2514\u2500 if: ${t.condition}`),t.awaits&&(i+=`
6
+ \u2514\u2500 await: ${t.awaitTarget||"async"}`),t.stateChanges&&t.stateChanges.length>0)for(let a of t.stateChanges)i+=`
7
+ \u2514\u2500 ${a.variable}`,a.from&&a.to&&(i+=`: ${a.from} \u2192 ${a.to}`);return i}getStepIcon(t){return {call:"\u2192",condition:"\u25C7",setState:"\u25CF",await:"\u23F3",return:"\u21A9",throw:"\u26A1",loop:"\u21BB",guard:"\u{1F6E1}"}[t]||"\u2022"}formatTraceFlowAsMermaid(t){if(t.mermaid)return t.mermaid;let e=["sequenceDiagram"],n=new Set;for(let o of t.paths)for(let s of o.steps)n.add(s.entity);let i=0,a=new Map;for(let o of n){let s=`P${i++}`;a.set(o,s),e.push(` participant ${s} as ${this.sanitize(o)}`);}for(let o=0;o<Math.min(t.paths.length,2);o++){let s=t.paths[o];e.push(` Note right of P0: Path ${o+1}`);for(let r=0;r<s.steps.length-1;r++){let c=s.steps[r],l=s.steps[r+1],d=a.get(c.entity)||"P0",p=a.get(l.entity)||"P0",g=c.awaits?"-->>":"->>",f=c.condition||c.action;e.push(` ${d}${g}${p}: ${this.sanitize(f)}`);}}return e.join(`
8
+ `)}formatTraceBackwardsAsText(t){let e=[];if(e.push(`\u2550\u2550\u2550 Trace Backwards: ${t.target.name} \u2550\u2550\u2550`),e.push(`Location: ${t.target.file}`),e.push(`Signature: ${t.target.signature}`),e.push(""),e.push(`\u2500\u2500\u2500 Callers (${t.callers.length}) \u2500\u2500\u2500`),t.callers.length===0)e.push("\u274C No callers found - this may be dead code");else for(let n of t.callers){let i=this.getProbabilityIcon(n.probability);e.push(` ${i} ${n.name} (${n.file}:${n.line})`),n.condition&&e.push(` \u2514\u2500 when: ${n.condition}`);}if(e.push(""),t.blockingConditions.length>0){e.push(`\u2500\u2500\u2500 Blocking Conditions (${t.blockingConditions.length}) \u2500\u2500\u2500`);for(let n of t.blockingConditions)e.push(` \u26D4 ${n.condition}`),e.push(` Location: ${n.location}`),e.push(` Recommendation: ${n.recommendation}`);e.push("");}if(t.statesDependencies.length>0){e.push(`\u2500\u2500\u2500 State Dependencies (${t.statesDependencies.length}) \u2500\u2500\u2500`);for(let n of t.statesDependencies)e.push(` \u{1F4CA} ${n.state} (${n.stateType||"unknown"})`),n.modifiedBy.length>0?e.push(` Modified by: ${n.modifiedBy.join(", ")}`):e.push(" \u26A0\uFE0F No known modifiers"),n.requiredValue&&e.push(` Required: ${n.requiredValue}`);e.push("");}if(t.callChains.length>0){e.push(`\u2500\u2500\u2500 Call Chains (${t.callChains.length}) \u2500\u2500\u2500`);for(let n=0;n<t.callChains.length;n++){let i=t.callChains[n],a=this.getLikelihoodIcon(i.likelihood);e.push(` ${n+1}. ${a} ${i.chain.join(" \u2192 ")}`),i.guards.length>0&&e.push(` Guards: ${i.guards.join("; ")}`),i.entryPoint&&e.push(` Entry: ${i.entryPoint}`);}e.push("");}if(e.push("\u2500\u2500\u2500 Diagnosis \u2500\u2500\u2500"),t.diagnosis.mostLikely&&e.push(`\u{1F3AF} Most likely: ${t.diagnosis.mostLikely}`),t.diagnosis.possibleReasons.length>0){e.push("Possible reasons:");for(let n of t.diagnosis.possibleReasons)e.push(` \u2022 ${n}`);}if(t.diagnosis.suggestedDebugPoints.length>0){e.push("Debug points:");for(let n of t.diagnosis.suggestedDebugPoints)e.push(` \u{1F50D} ${n}`);}return e.join(`
9
+ `)}getProbabilityIcon(t){switch(t){case "always":return "\u2705";case "conditional":return "\u2753";case "rare":return "\u26A0\uFE0F";default:return "\u2022"}}getLikelihoodIcon(t){switch(t){case "high":return "\u{1F7E2}";case "medium":return "\u{1F7E1}";case "low":return "\u{1F534}";default:return "\u26AA"}}formatDataFlowAsText(t){let e=[];e.push(`\u2550\u2550\u2550 Data Flow: ${t.entryPoint} \u2192 ${t.targetState} \u2550\u2550\u2550`),e.push(""),e.push(`Data sources analyzed: ${t.summary.dataSourcesAnalyzed}`),e.push(`Branching points: ${t.summary.branchingPoints}`),e.push(`Possible outcomes: ${t.summary.possibleOutcomes}`),e.push("");for(let n=0;n<t.dataFlows.length;n++){let i=t.dataFlows[n],a=i.affectsTarget?"\u2705":"\u274C";e.push(`\u2500\u2500\u2500 Flow ${n+1}: ${i.source} ${a} \u2500\u2500\u2500`);for(let o of i.flow){let s=this.getDataFlowIcon(o.action),r=` ${o.step}. ${s} ${o.action}`;o.input&&o.output&&(r+=`: ${o.input} \u2192 ${o.output}`),o.transformation&&(r+=` [${o.transformation}]`),e.push(r),o.condition&&e.push(` \u2514\u2500 if: ${o.condition}`);}i.criticalConditions.length>0&&e.push(` Critical: ${i.criticalConditions.join("; ")}`),e.push("");}if(t.behaviorMatrix.combinations.length>0){e.push("\u2500\u2500\u2500 Behavior Matrix \u2500\u2500\u2500");for(let n of t.behaviorMatrix.combinations.slice(0,8)){let i=Object.entries(n.inputs).map(([o,s])=>`${o.split(":").pop()}=${s}`).join(", "),a=Object.entries(n.result).map(([o,s])=>`${o}=${s}`).join(", ");e.push(` ${i} \u2192 ${a}`);}t.behaviorMatrix.combinations.length>8&&e.push(` ... and ${t.behaviorMatrix.combinations.length-8} more combinations`);}return e.join(`
10
+ `)}getDataFlowIcon(t){return {parse:"\u{1F4E5}",transform:"\u{1F504}",branch:"\u25C7",setState:"\u{1F4BE}",fetch:"\u{1F310}",validate:"\u2713",emit:"\u{1F4E4}"}[t]||"\u2022"}formatStateImpactAsText(t){let e=[];e.push(`\u2550\u2550\u2550 State Impact: ${t.state} \u2550\u2550\u2550`),e.push(""),e.push(`\u2500\u2500\u2500 Usages (${t.usages.length}) \u2500\u2500\u2500`);let n=this.groupBy(t.usages,"usage");for(let[i,a]of Object.entries(n)){e.push(` ${i}: ${a.length}`);for(let o of a.slice(0,3))e.push(` \u2022 ${o.entityName||o.location}`);a.length>3&&e.push(` ... and ${a.length-3} more`);}e.push(""),e.push("\u2500\u2500\u2500 Scenario Analysis \u2500\u2500\u2500");for(let[i,a]of Object.entries(t.scenarioAnalysis))e.push(` ${i}:`),e.push(` Reachable: ${a.reachablePaths.length} paths`),e.push(` Blocked: ${a.blockedPaths.length} paths`),a.enabledFeatures.length>0&&e.push(` Features: ${a.enabledFeatures.join(", ")}`);if(e.push(""),t.conflicts.length>0){e.push(`\u2500\u2500\u2500 Conflicts (${t.conflicts.length}) \u2500\u2500\u2500`);for(let i of t.conflicts)e.push(` \u26A0\uFE0F ${i.description}`),e.push(` Risk: ${i.risk}`),e.push(` Fix: ${i.recommendation}`);e.push("");}return e.push("\u2500\u2500\u2500 Ripple Effects \u2500\u2500\u2500"),e.push(` Direct: ${t.rippleEffects.directEffects} components`),e.push(` Indirect: ${t.rippleEffects.indirectEffects} dependencies`),t.rippleEffects.affectedComponents.length>0&&e.push(` Components: ${t.rippleEffects.affectedComponents.join(", ")}`),e.join(`
11
+ `)}formatDecisionPointsAsText(t){let e=[];e.push(`\u2550\u2550\u2550 Decision Points: ${t.scenario} \u2550\u2550\u2550`),e.push(""),e.push(`Entry points: ${t.entryPoints.map(i=>i.name).join(", ")}`),e.push(`Total: ${t.summary.totalDecisionPoints} | Critical: ${t.summary.criticalPoints}`),e.push(`Possible outcomes: ${t.summary.possibleOutcomes}`),e.push("");let n=this.groupBy(t.decisionPoints,"type");for(let[i,a]of Object.entries(n)){e.push(`\u2500\u2500\u2500 ${i.toUpperCase()} (${a.length}) \u2500\u2500\u2500`);for(let o of a){let s=this.getImpactIcon(o.impact);e.push(` ${s} ${o.condition||o.action||o.type}`),e.push(` Location: ${o.location}`),e.push(` Outcomes: ${Object.keys(o.outcomes).join(", ")}`),o.dataDepends.length>0&&e.push(` Depends on: ${o.dataDepends.join(", ")}`);}e.push("");}return e.join(`
12
+ `)}getImpactIcon(t){switch(t){case "critical":return "\u{1F534}";case "high":return "\u{1F7E0}";case "medium":return "\u{1F7E1}";case "low":return "\u{1F7E2}";default:return "\u26AA"}}sanitize(t){return t.replace(/["\n\r]/g," ").replace(/[{}[\]<>|]/g,"").trim().substring(0,40)}groupBy(t,e){return t.reduce((n,i)=>{let a=String(i[e]);return n[a]||(n[a]=[]),n[a].push(i),n},{})}};var q=new Set(["listens_to_action","handles_action","selects_state","dispatches_action","modifies_state"]);function z(h){let t=Math.max(h.lastIndexOf("/"),h.lastIndexOf("\\"));return t>=0?h.slice(0,t):""}function nt(h){let e=(h.split(/[/\\]/).pop()||"").match(/^([a-z0-9-]+)\.(reducer|selector|reducers|selectors|state)/i);return e?e[1]:null}function it(h){let t=h.match(/^([a-z]+)Reducer$/i);return t||(t=h.match(/^select([A-Z][a-z]+)Feature$/),t)||(t=h.match(/^select([A-Z][a-z]+)State$/),t)?t[1]:null}async function at(h){let t=[],e=await h.findEntities({filters:{entityType:["ngrx_reducer"]},limit:500}),i=(await h.findEntities({filters:{entityType:["ngrx_selector"]},limit:500})).filter(a=>!!(a.name.includes("Feature")||a.name.endsWith("State")||a.metadata?.ngrxSelector?.featureName));for(let a of e){let o=z(a.filePath),s=nt(a.filePath);for(let r of i){let c=z(r.filePath),l=nt(r.filePath),d=0;o===c&&(d+=.5);let p=z(o),g=z(c);p===g&&p!==""&&(d+=.3),s&&l&&s===l&&(d+=.4);let f=it(a.name),u=it(r.name);f&&u&&f.toLowerCase()===u.toLowerCase()&&(d+=.3),d>=.5&&t.push({reducerId:a.id,selectorId:r.id,confidence:Math.min(1,d)});}}return t}async function ot(h,t){let e=await h.getEntity(t);if(!e)return null;let n=e.name,i=n.lastIndexOf(":"),a=i>=0?n.slice(i+1):n,o=await h.searchEntities({namePattern:a});for(let s of o)if(s.name===a&&s.id!==t)return s.id;return null}async function st(h,t){let e=Array.from(q);return h.findIncomingRelationshipsByName(t,e)}function rt(h){return h==="handles_action"||h==="listens_to_action"}function Pt(h,t,e){return t===e-1?"return":h.controlFlow?.branches&&h.controlFlow.branches.length>0?"condition":h.controlFlow?.awaits&&h.controlFlow.awaits.length>0?"await":h.controlFlow?.loops&&h.controlFlow.loops.length>0?"loop":h.controlFlow?.exceptions&&h.controlFlow.exceptions.length>0?"throw":"call"}function Tt(h){let t=1;return t-=h.entityIds.length*.02,t-=h.conditionCount*.1,t-=h.weight*.05,Math.max(.1,Math.min(1,t))}function Et(h){if(h.length===0)return "Empty path";if(h.length===1)return `Direct call to ${h[0].entity}`;let t=h[0],e=h[h.length-1],n=h.filter(o=>o.action==="condition").length,i=h.filter(o=>o.awaits).length,a=`${t.entity} \u2192 ${e.entity} (${h.length} steps)`;return n>0&&(a+=`, ${n} condition${n>1?"s":""}`),i>0&&(a+=`, ${i} await${i>1?"s":""}`),a}function Ct(h,t){let e=[];h.entityIds.length>10&&e.push("Long call chain - may indicate design issues"),h.conditionCount>5&&e.push("Many conditional branches - path may be rarely executed");let n=0;for(let i of h.entityIds){let a=t.nodes.get(i);a?.controlFlow?.awaits&&a.controlFlow.awaits.length>0&&n++;}return n>3&&e.push("Multiple async boundaries - consider timing issues"),e}function ct(h){return h>=.7?"high":h>=.4?"medium":"low"}function At(h,t,e){let n=[];for(let a=0;a<h.entityIds.length;a++){let o=h.entityIds[a],s=t.nodes.get(o);if(!s)continue;let r={order:a+1,entity:s.name,entityId:o,file:s.file,line:s.line,action:Pt(s,a,h.entityIds.length)};if(s.controlFlow?.branches&&s.controlFlow.branches.length>0){r.condition=s.controlFlow.branches[0]?.condition,r.branches={};for(let c of s.controlFlow.branches)r.branches[c.condition]=c.target||"continue";}s.controlFlow?.awaits&&s.controlFlow.awaits.length>0&&(r.awaits=true,r.awaitTarget=s.controlFlow.awaits[0]?.target),n.push(r);}let i=Tt(h);return {id:`path-${e+1}`,confidence:i,steps:n,summary:Et(n),warnings:Ct(h,t)}}function lt(h,t){return h.map((e,n)=>At(e,t,n))}var W=15,dt=10,$t=.3,L=.1,xt=.2,_=class{storage;adjacencyCache=new Map;nodeCache=new Map;constructor(t){this.storage=t;}async buildAdjacencyGraph(t,e=W){let n=`${t.sort().join(",")}:${e}`,i=this.adjacencyCache.get(n);if(i)return i;let a=new Map,o=new Map,s=new Map,r=new Map,c=new Set,l=t.map(u=>({id:u,depth:0}));for(;l.length>0;){let y=l.splice(0,Math.min(16,l.length)).filter(({id:b,depth:T})=>!c.has(b)&&T<=e);if(y.length===0)continue;for(let{id:b}of y)c.add(b);let w=y.map(({id:b})=>b),P=await this.storage.getEntitiesBatch(w);for(let{id:b,depth:T}of y){let E=P.get(b);if(!E)continue;let O=this.entityToNode(E);a.set(b,O);let ft=await this.storage.getRelationshipsForEntity(b),F=[],v=[];for(let S of ft){let Q=this.calculateEdgeWeight(S,E),D=`${S.fromId}:${S.toId}`;if(r.set(D,Q),S.fromId===b){let M=S.toId;if(q.has(S.type)){let Y=await ot(this.storage,S.toId);Y&&(M=Y);}F.push(M),T<e&&!c.has(M)&&l.push({id:M,depth:T+1});}else v.push(S.fromId),T<e&&!c.has(S.fromId)&&l.push({id:S.fromId,depth:T+1});}let gt=await st(this.storage,E.name);for(let S of gt)if(rt(S.type)){if(!F.includes(S.fromId)){F.push(S.fromId);let D=this.calculateEdgeWeight(S,E);r.set(`${b}:${S.fromId}`,D),T<e&&!c.has(S.fromId)&&l.push({id:S.fromId,depth:T+1});}}else if(!v.includes(S.fromId)){v.push(S.fromId);let D=this.calculateEdgeWeight(S,E);r.set(`${S.fromId}:${b}`,D),T<e&&!c.has(S.fromId)&&l.push({id:S.fromId,depth:T+1});}o.set(b,F),s.set(b,v),O.outgoing=F,O.incoming=v;}}let d=await at(this.storage),p=new Set;for(let u of d)(a.has(u.reducerId)||a.has(u.selectorId))&&(a.has(u.reducerId)||p.add(u.reducerId),a.has(u.selectorId)||p.add(u.selectorId));let g=p.size>0?await this.storage.getEntitiesBatch([...p]):new Map;for(let u of d)if(a.has(u.reducerId)||a.has(u.selectorId)){if(!a.has(u.reducerId)){let E=g.get(u.reducerId);E&&(a.set(u.reducerId,this.entityToNode(E)),o.set(u.reducerId,[]),s.set(u.reducerId,[]));}if(!a.has(u.selectorId)){let E=g.get(u.selectorId);E&&(a.set(u.selectorId,this.entityToNode(E)),o.set(u.selectorId,[]),s.set(u.selectorId,[]));}let y=o.get(u.reducerId)||[];y.includes(u.selectorId)||(y.push(u.selectorId),o.set(u.reducerId,y));let w=s.get(u.selectorId)||[];w.includes(u.reducerId)||(w.push(u.reducerId),s.set(u.selectorId,w));let P=`${u.reducerId}:${u.selectorId}`;r.set(P,L*(2-u.confidence));let b=a.get(u.reducerId),T=a.get(u.selectorId);b&&!b.outgoing.includes(u.selectorId)&&b.outgoing.push(u.selectorId),T&&!T.incoming.includes(u.reducerId)&&T.incoming.push(u.reducerId);}let f={nodes:a,forward:o,backward:s,weights:r};return a.size<1e4&&this.adjacencyCache.set(n,f),f}entityToNode(t){let e=this.nodeCache.get(t.id);if(e)return e;let n={id:t.id,name:t.name,type:t.type,file:t.filePath,line:t.location.start.line,outgoing:[],incoming:[]},i=t.metadata;return i.controlFlow&&(n.controlFlow={branches:i.controlFlow.branches,loops:i.controlFlow.loops,awaits:i.controlFlow.awaits,exceptions:i.controlFlow.exceptions}),i.calls&&(n.calls=i.calls),i.complexity&&(n.complexity=i.complexity),this.nodeCache.set(t.id,n),n}calculateEdgeWeight(t,e){let n=L;return t.metadata?.conditional&&(n+=$t),(t.metadata?.isAwait||t.metadata?.isAsync)&&(n+=xt),t.weight&&(n*=t.weight),n}async findPathsForward(t,e,n={}){let i=n.maxDepth??W,a=n.maxPaths??dt,o=await this.buildAdjacencyGraph([t],i);if(!o.nodes.has(t))return [];let s=[],r=[{path:[t],relationships:[],weight:0,conditionCount:0}],c=new Map;for(c.set(t,0);r.length>0&&s.length<a;){let l=r.shift(),d=l.path[l.path.length-1];if(d===e){s.push({entityIds:l.path,relationships:l.relationships,weight:l.weight,conditionCount:l.conditionCount});continue}if(l.path.length>=i)continue;let p=o.forward.get(d)||[],g=p.length-p.length%4;for(let f=0;f<g;f+=4)this.processNeighbor(p[f],l,o,c,r,n),this.processNeighbor(p[f+1],l,o,c,r,n),this.processNeighbor(p[f+2],l,o,c,r,n),this.processNeighbor(p[f+3],l,o,c,r,n);for(let f=g;f<p.length;f++)this.processNeighbor(p[f],l,o,c,r,n);r.sort((f,u)=>f.weight-u.weight);}return s.sort((l,d)=>l.weight-d.weight)}processNeighbor(t,e,n,i,a,o){if(e.path.includes(t))return;let r=`${e.path[e.path.length-1]}:${t}`,c=n.weights.get(r)??L,l=e.weight+c,d=i.get(t);if(d!==void 0&&d<=l||o.weightThreshold&&l>o.weightThreshold)return;i.set(t,l);let p=n.nodes.get(t),g=p?.controlFlow?.branches&&p.controlFlow.branches.length>0;a.push({path:[...e.path,t],relationships:[...e.relationships,r],weight:l,conditionCount:e.conditionCount+(g?1:0)});}async findPathsBackward(t,e={}){let n=e.maxDepth??W,i=e.maxPaths??dt,a=await this.buildAdjacencyGraph([t],n);if(!a.nodes.has(t))return [];let o=[],s=[],r=[],c=(l,d,p,g)=>{if(d>n||o.length>=i)return;s.push(l);let f=a.backward.get(l)||[];if(f.length===0&&s.length>1)o.push({entityIds:[...s].reverse(),relationships:[...r].reverse(),weight:p,conditionCount:g});else {let u={depth:d,weight:p,conditionCount:g},y={currentPath:s,currentRels:r,graph:a,dfs:c},w=f.length-f.length%4;for(let P=0;P<w;P+=4)this.processCallerDFS(f[P],l,u,y),this.processCallerDFS(f[P+1],l,u,y),this.processCallerDFS(f[P+2],l,u,y),this.processCallerDFS(f[P+3],l,u,y);for(let P=w;P<f.length;P++)this.processCallerDFS(f[P],l,u,y);}s.pop();};return c(t,0,0,0),o.sort((l,d)=>l.weight-d.weight)}processCallerDFS(t,e,n,i){if(i.currentPath.includes(t))return;let a=`${t}:${e}`,o=i.graph.weights.get(a)??L,s=n.weight+o,r=i.graph.nodes.get(t),c=r?.controlFlow?.branches&&r.controlFlow.branches.length>0;i.currentRels.push(a),i.dfs(t,n.depth+1,s,n.conditionCount+(c?1:0)),i.currentRels.pop();}async enrichPaths(t,e){return lt(t,e)}clearCache(){this.adjacencyCache.clear(),this.nodeCache.clear();}getCallProbability(t){return !t.controlFlow?.branches||t.controlFlow.branches.length===0?"always":t.controlFlow.branches.some(n=>n.target==="return"||n.target==="throw")?"rare":"conditional"}getConfidenceLevel(t){return ct(t)}async findEntityByName(t,e,n){let i=await this.storage.searchEntities({namePattern:t,types:e?[e]:void 0,filePath:n,limit:n?1e3:100});if(i.length>0){if(n){let o=n.replace(/\\/g,"/").toLowerCase(),s=i.filter(r=>{let c=(r.filePath||"").replace(/\\/g,"/").toLowerCase();return c.includes(o)||c.endsWith(o)});if(s.length>0)return s.find(c=>c.name===t||c.name.endsWith(`.${t}`))||s[0]}return i.find(o=>o.name===t||o.name.endsWith(`.${t}`))||i[0]}return null}async getCallers(t){let n=(await this.storage.getRelationshipsForEntity(t,"calls")).filter(o=>o.toId===t).map(o=>o.fromId);if(n.length===0)return [];let i=await this.storage.getEntitiesBatch(n),a=[];for(let o of n){let s=i.get(o);if(s){let r=this.entityToNode(s);a.push({entity:s,probability:this.getCallProbability(r)});}}return a}async getCallees(t){let n=(await this.storage.getRelationshipsForEntity(t,"calls")).filter(a=>a.fromId===t).map(a=>a.toId);if(n.length===0)return [];let i=await this.storage.getEntitiesBatch(n);return n.map(a=>i.get(a)).filter(a=>a!=null)}};R$1();var pt=15,U=5,ut=new Set(["method","function","async_function","class","interface","property"]);function ht(h){return !(h.id.startsWith("external:")||h.filePath?.includes("external://")||h.type==="import")}var R=class{storage;semanticSearch;pathBuilder;graphologyBuilder;useOptimized;resolveEntityCache=new Map;constructor(t,e,n=true){this.storage=t,this.semanticSearch=e,this.pathBuilder=new _(t),this.graphologyBuilder=new a$1(t),this.useOptimized=n;}setOptimizedMode(t){this.useOptimized=t;}isOptimizedMode(){return this.useOptimized}async getGraphStats(){return this.graphologyBuilder.isLoaded()||await this.graphologyBuilder.loadGraph(),this.graphologyBuilder.getStats()}async traceFlow(t){let e=t.maxDepth??pt;return this.useOptimized?this.traceFlowOptimized(t,e):this.traceFlowLegacy(t,e)}async traceFlowOptimized(t,e){let n=performance.now(),i=await this.graphologyBuilder.loadGraph();I$1.i("TRACEENGINE","graph_loaded",{nodes:i.nodes,edges:i.edges,timeMs:+i.loadTimeMs.toFixed(0)});let a=await this.resolveEntity(t.from),o=await this.resolveEntity(t.to);if(!a)throw new Error(`Could not find source entity: ${t.from}`);if(!o)throw new Error(`Could not find target entity: ${t.to}`);I$1.d("TRACEENGINE","resolved",{from:t.from,srcId:a.id,srcName:a.name,to:t.to,tgtId:o.id,tgtName:o.name});let s=await this.graphologyBuilder.traceLinearFlow(a.id,o.id,e),r=[];if(s.found&&r.push(this.linearTraceToTracePath(s)),t.trackConditions&&s.found){let g=await this.graphologyBuilder.findPaths(a.id,o.id,U-1,e),f=this.graphologyBuilder.enrichPaths(g);for(let u of f)u.steps.length!==r[0]?.steps.length&&r.push(u);}let c={modified:[],read:[],critical:[]};t.trackStates&&r.length>0&&(c=await this.analyzeStatesInPaths(r));let l={guards:0,branches:0,criticalConditions:[]};t.trackConditions&&r.length>0&&(l=this.analyzeConditionsInPaths(r));let d;t.format==="mermaid"&&r.length>0&&(d=this.generateMermaidDiagram(r,a.name,o.name)),await this.annotateApiContractBoundaries(r);let p=performance.now()-n;return I$1.i("TRACEENGINE","trace_done",{timeMs:+p.toFixed(0),visited:s.nodesVisited}),{from:t.from,to:t.to,paths:r,statesSummary:c,conditionsSummary:l,mermaid:d,_debug:{sourceEntityId:a.id,sourceEntityName:a.name,targetEntityId:o.id,targetEntityName:o.name,graphStats:i,linearTraceSummary:s.summary,nodesVisited:s.nodesVisited,found:s.found,timeMs:p}}}linearTraceToTracePath(t){return {id:"path-1",confidence:t.found?.9:.1,steps:t.steps.map(e=>({order:e.order,entity:e.entity,entityId:e.entityId,file:e.file,line:e.line,action:e.action,condition:e.branches?.[0]?.condition,branches:e.branches?.reduce((n,i)=>(n[i.condition]=i.target,n),{})})),summary:t.summary,warnings:[]}}async annotateApiContractBoundaries(t){let e=new Set;for(let a of t)for(let o of a.steps)o.entityId&&e.add(o.entityId);if(e.size===0)return;let n=await this.storage.getEntitiesBatch(Array.from(e)),i=0;for(let a of t){for(let o of a.steps){if(!o.entityId)continue;let s=n.get(o.entityId);if(s?.metadata?.isApiContract){let r=s.metadata.swaggerType;o.crossesApiContract=true,o.contractInfo={type:"swagger",swaggerType:r,endpoint:r==="endpoint"?`${s.metadata.httpMethod||""} ${s.metadata.path||""}`.trim():void 0,schemaName:r==="schema"?s.name:void 0},i++;}}i>0&&a.warnings&&a.warnings.push("Path crosses API contract boundary \u2014 changes may affect external consumers");}}async traceFlowLegacy(t,e){let n=await this.resolveEntity(t.from),i=await this.resolveEntity(t.to);if(!n)throw new Error(`Could not find source entity: ${t.from}`);if(!i)throw new Error(`Could not find target entity: ${t.to}`);let a=await this.pathBuilder.findPathsForward(n.id,i.id,{maxDepth:e,maxPaths:U});if(a.length===0)return {from:t.from,to:t.to,paths:[],statesSummary:{modified:[],read:[],critical:[]},conditionsSummary:{guards:0,branches:0,criticalConditions:[]}};let o=await this.pathBuilder.buildAdjacencyGraph([n.id,i.id],e),s=await this.pathBuilder.enrichPaths(a,o),r={modified:[],read:[],critical:[]};t.trackStates&&(r=await this.analyzeStatesInPaths(s));let c={guards:0,branches:0,criticalConditions:[]};t.trackConditions&&(c=this.analyzeConditionsInPaths(s));let l;return t.format==="mermaid"&&(l=this.generateMermaidDiagram(s,n.name,i.name)),{from:t.from,to:t.to,paths:s,statesSummary:r,conditionsSummary:c,mermaid:l}}async traceBackwards(t){let e=t.depth??pt,n=await this.resolveEntity(t.target);if(!n)throw new Error(`Could not find target entity: ${t.target}`);if(this.useOptimized){let d=performance.now();await this.graphologyBuilder.loadGraph();let p=await this.graphologyBuilder.traceBackwards(n.id,e),g=p.callers.map(w=>({name:w.name,entityId:w.id,file:"",line:0,probability:w.probability})),f=g.filter(w=>w.probability==="conditional"||w.probability==="rare").map(w=>({condition:`Conditional call from ${w.name}`,location:w.file?`${w.file}:${w.line}`:w.name,currentValue:"unknown",recommendation:`Check conditions in ${w.name}`})),u=p.entryPoints.map(w=>({chain:[w.name,"...",n.name],guards:[],likelihood:"medium",entryPoint:w.name})),y=performance.now()-d;return I$1.i("TRACEENGINE","back_trace_done",{timeMs:+y.toFixed(0)}),{target:{name:n.name,entityId:n.id,file:n.filePath,signature:this.getEntitySignature(n)},callers:g,blockingConditions:f,statesDependencies:t.includeStates?await this.findStateDependencies(n):[],callChains:u,diagnosis:this.generateDiagnosis(t.question,g,f,t.includeStates?await this.findStateDependencies(n):[],u)}}let i=await this.pathBuilder.getCallers(n.id),a=await Promise.all(i.map(async({entity:d,probability:p})=>{let g={name:d.name,entityId:d.id,file:d.filePath,line:d.location.start.line,probability:p},f=d.metadata;if(f.controlFlow?.branches){let u=f.controlFlow.branches;u.length>0&&(g.condition=u[0]?.condition);}return g})),o=await this.findBlockingConditions(n,a),s=[];t.includeStates&&(s=await this.findStateDependencies(n));let c=(await this.pathBuilder.findPathsBackward(n.id,{maxDepth:e,maxPaths:U})).map(d=>{let p=this.pathBuilder.adjacencyCache.values().next().value,g=[];for(let u of d.entityIds){let y=p?.nodes.get(u);if(y?.controlFlow?.branches)for(let w of y.controlFlow.branches)(w.target==="return"||w.target==="throw")&&g.push(`${y.name}: ${w.condition}`);}let f;if(p){let u=d.entityIds[0],y=p.nodes.get(u);y&&(!p.backward.get(u)||p.backward.get(u).length===0)&&(f=y.name);}return {chain:d.entityIds.map(u=>p?.nodes.get(u)?.name||u),guards:g,likelihood:this.pathBuilder.getConfidenceLevel(1-d.weight),entryPoint:f}}),l=this.generateDiagnosis(t.question,a,o,s,c);return {target:{name:n.name,entityId:n.id,file:n.filePath,signature:this.getEntitySignature(n)},callers:a,blockingConditions:o,statesDependencies:s,callChains:c,diagnosis:l}}async resolveEntity(t){let e=this.resolveEntityCache.get(t);if(e!==void 0)return e;let n=await this.resolveEntityUncached(t);return this.resolveEntityCache.set(t,n),n}async resolveEntityUncached(t){let e=t.match(/^(.+?\.(?:ts|js|tsx|jsx|py|go|rs|java|kt|kts|c|cs|csx|cpp|h|hpp)):(.+)$/i),n=t,i;e&&(i=e[1],n=e[2]);let a=i?i.replace(/\\/g,"/").toLowerCase():void 0,o=c=>{if(!a)return null;for(let l of c){let d=(l.filePath||"").replace(/\\/g,"/").toLowerCase();if(d.includes(a)||d.endsWith(a))return l}return null},s=await this.pathBuilder.findEntityByName(n,void 0,i);if(s&&ht(s))return s;let r=await this.storage.searchEntities({namePattern:n});if(r.length>0){if(a){let c=o(r);if(c)return c}return r[0]}if(!n.includes(".")){let c=`.${n}`,p=(await this.storage.searchEntities({})).filter(g=>g.name.endsWith(c)&&ht(g)).sort((g,f)=>{let u=ut.has(g.type)?0:1,y=ut.has(f.type)?0:1;return u-y});if(p.length===1)return p[0];if(p.length>1&&a){let g=o(p);if(g)return g}else if(p.length>1)return I$1.d("TRACEENGINE","multiple_suffix_matches",{name:n,count:p.length,first:p[0]?.name}),p[0]}if(this.semanticSearch)try{let c=await this.semanticSearch.search(n,{limit:i?10:1,minSimilarity:.6});if(c.length>0){let l=c.map(p=>p.entityId),d=await this.storage.getEntitiesBatch(l);if(a)for(let p of c){let g=d.get(p.entityId);if(g){let f=(g.filePath||"").replace(/\\/g,"/").toLowerCase();if(f.includes(a)||f.endsWith(a))return g}}return d.get(c[0].entityId)||null}}catch{}return null}async analyzeStatesInPaths(t){let e=new Set,n=new Set,i=new Set,a=new Set;for(let s of t)for(let r of s.steps)a.add(r.entityId);let o=a.size>0?await this.storage.getEntitiesBatch([...a]):new Map;for(let s of t)for(let r of s.steps){let c=o.get(r.entityId);if(!c?.metadata)continue;let l=c.metadata;if(Array.isArray(l.stateModifications))for(let d of l.stateModifications)e.add(d);if(Array.isArray(l.stateReads))for(let d of l.stateReads)n.add(d);if(r.condition&&Array.isArray(l.stateReads))for(let d of l.stateReads)i.add(d);}return {modified:Array.from(e),read:Array.from(n),critical:Array.from(i)}}async findStateDependencies(t){let e=[],n=t.metadata,i=Array.isArray(n.stateReads)?n.stateReads:[];for(let a of i){let o=await this.findStateModifiers(a);e.push({state:a,modifiedBy:o.map(s=>s.name),stateType:this.inferStateType(a)});}return e}async findStateModifiers(t){return (await this.storage.searchEntities({namePattern:t})).filter(n=>{let i=n.metadata;return (Array.isArray(i.stateModifications)?i.stateModifications:[]).includes(t)||n.name.toLowerCase().includes("set")})}inferStateType(t){return t.startsWith("is")||t.startsWith("has")||t.startsWith("should")?"boolean":t.endsWith("Count")||t.endsWith("Index")||t.endsWith("Id")?"number":t.endsWith("List")||t.endsWith("Array")||t.endsWith("s")?"array":"unknown"}analyzeConditionsInPaths(t){let e=0,n=0,i=new Set;for(let a of t)for(let o of a.steps)o.action==="condition"&&(n++,o.branches&&Object.values(o.branches).some(r=>r==="return"||r==="throw")&&e++,o.condition&&i.add(o.condition)),o.action==="guard"&&e++;return {guards:e,branches:n,criticalConditions:Array.from(i)}}async findBlockingConditions(t,e){let n=[];for(let a of e)a.condition&&a.probability==="conditional"&&n.push({condition:a.condition,location:`${a.file}:${a.line}`,currentValue:"unknown (static analysis)",recommendation:`Check if condition '${a.condition}' evaluates to true`});let i=t.metadata;if(Array.isArray(i.preconditions))for(let a of i.preconditions)n.push({condition:a,location:`${t.filePath}:${t.location.start.line}`,currentValue:"required",recommendation:`Ensure precondition '${a}' is satisfied`});return n}generateDiagnosis(t,e,n,i,a){let o=[],s=[],r;switch(t){case "why_not_called":if(e.length===0)o.push("No callers found - method may be unused"),o.push("Target may be behind an API contract boundary \u2014 check swagger consumers"),r="Dead code - no call sites exist (or called via API contract)";else {let c=e.filter(l=>l.probability!=="always");if(c.length===e.length){o.push("All call sites are conditional"),r="Conditions not met at runtime";for(let l of c)s.push(`${l.file}:${l.line} - ${l.condition||"check condition"}`);}if(n.length>0){o.push(`${n.length} blocking condition(s) detected`);for(let l of n)s.push(`${l.location} - ${l.condition}`);}if(i.length>0){o.push(`Depends on ${i.length} state(s)`);for(let l of i)l.modifiedBy.length===0&&o.push(`State '${l.state}' has no known modifiers`);}}break;case "what_affects":if(i.length>0&&o.push(`Direct state dependencies: ${i.map(c=>c.state).join(", ")}`),n.length>0&&o.push(`Guard conditions: ${n.map(c=>c.condition).join(", ")}`),a.length>0){let c=a.filter(l=>l.entryPoint).map(l=>l.entryPoint);c.length>0&&o.push(`Entry points: ${c.join(", ")}`);}break;case "dependencies":for(let c of a)o.push(`Call chain: ${c.chain.join(" \u2192 ")}`),c.guards.length>0&&o.push(` Guards: ${c.guards.join("; ")}`);break}return s.length===0&&e.length>0&&s.push(`${e[0].file}:${e[0].line} - First caller`),{possibleReasons:o,suggestedDebugPoints:s,mostLikely:r}}generateMermaidDiagram(t,e,n){let i=["sequenceDiagram"];i.push(` participant S as ${this.sanitizeMermaidId(e)}`),i.push(` participant T as ${this.sanitizeMermaidId(n)}`);let a=new Set;for(let r of t)for(let c of r.steps)c.entity!==e&&c.entity!==n&&a.add(c.entity);let o=1,s=new Map;s.set(e,"S"),s.set(n,"T");for(let r of a){let c=`P${o++}`;s.set(r,c),i.push(` participant ${c} as ${this.sanitizeMermaidId(r)}`);}for(let r=0;r<Math.min(t.length,3);r++){let c=t[r];i.push(` Note over S,T: Path ${r+1} (confidence: ${Math.round(c.confidence*100)}%)`);for(let l=0;l<c.steps.length-1;l++){let d=c.steps[l],p=c.steps[l+1],g=s.get(d.entity)||"S",f=s.get(p.entity)||"T",u="->>";d.awaits&&(u="-->>");let y=d.condition?`${d.action}[${d.condition}]`:d.action;i.push(` ${g}${u}${f}: ${y}`);}}return i.join(`
13
+ `)}sanitizeMermaidId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").substring(0,30)}getEntitySignature(t){let n=(t.metadata.parameters||[]).map(a=>`${a.name}: ${a.type||"any"}`).join(", "),i=t.metadata.returnType||"void";return `${t.name}(${n}): ${i}`}clearCache(){this.pathBuilder.clearCache(),this.graphologyBuilder.clear(),this.resolveEntityCache.clear();}};var B=class{storage;constructor(t){this.storage=t;}async traceNgRxFlow(t){let e=t.maxDepth??20,n=await this.resolveNgRxEntity(t.from);if(!n)throw new Error(`Could not find NgRx source entity: ${t.from}`);let i=await this.resolveNgRxEntity(t.to);if(!i)throw new Error(`Could not find NgRx target entity: ${t.to}`);let a=await this.findNgRxPaths(n,i,e),o=this.analyzeActionFlow(a),s;return t.format==="mermaid"&&(s=this.generateMermaidDiagram(a,n.name,i.name)),{from:t.from,to:t.to,paths:a,actionFlow:o,mermaid:s}}async findNgRxPaths(t,e,n){let i=[],a=new Set,o=[{entityId:t.id,path:[this.entityToStep(t,1,"dispatch")],actionChain:[],depth:0}];for(;o.length>0&&i.length<5;){let s=o.shift();if(s.depth>n)continue;if(s.entityId===e.id){i.push({id:`ngrx-path-${i.length+1}`,confidence:1-s.depth*.05,steps:s.path,summary:this.generatePathSummary(s.path),actionChain:s.actionChain});continue}let r=`${s.entityId}:${s.depth}`;if(a.has(r))continue;a.add(r);let c=await this.getNgRxRelationships(s.entityId);for(let l of c){let d=l.fromId===s.entityId?l.toId:l.fromId,p=await this.storage.getEntity(d);if(!p)continue;let g=this.determineStepType(l.type,p),f=this.entityToStep(p,s.path.length+1,g),u=[...s.actionChain],y=l.metadata;y?.actionType&&u.push(y.actionType),o.push({entityId:d,path:[...s.path,f],actionChain:u,depth:s.depth+1});}}return i}async getNgRxRelationships(t){return (await this.storage.getRelationshipsForEntity(t)).filter(n=>["dispatches_action","listens_to_action","handles_action","selects_state","modifies_state","depends_on"].includes(n.type))}async resolveNgRxEntity(t){let e=await this.storage.searchEntities({namePattern:t});if(e.length>0)return e.find(a=>a.metadata?.ngrxType)||e[0];let n=await this.storage.searchEntities({namePattern:`*${t}*`});return n.length>0?n[0]:null}entityToStep(t,e,n){let i=t.metadata;return {order:e,type:n,entityName:t.name,entityId:t.id,file:t.filePath,line:t.location.start.line,actionType:i?.actionType||i?.ngrxType,stateProperty:i?.statePath,description:this.generateStepDescription(n,t.name,i)}}determineStepType(t,e){let i=e.metadata?.ngrxType;if(i==="effect")return "effect";if(i==="reducer")return "reducer";if(i==="selector")return "selector";if(i==="action")return "dispatch";switch(t){case "dispatches_action":return "dispatch";case "listens_to_action":return "effect";case "handles_action":return "reducer";case "modifies_state":return "state";case "selects_state":return "subscribe";default:return "dispatch"}}generateStepDescription(t,e,n){switch(t){case "dispatch":return `Dispatches action: ${n?.actionType||e}`;case "effect":return `Effect ${e} handles action via ofType()`;case "reducer":return `Reducer ${e} processes action via on()`;case "state":return `State modified: ${n?.stateChanges?.join(", ")||"unknown"}`;case "selector":return `Selector ${e} reads state`;case "subscribe":return `Component subscribes to ${e}`;default:return e}}generatePathSummary(t){return t.map(n=>{switch(n.type){case "dispatch":return `dispatch(${n.entityName})`;case "effect":return `\u2192 Effect.${n.entityName}`;case "reducer":return "\u2192 Reducer.on()";case "state":return `\u2192 state.${n.stateProperty||"?"}`;case "selector":return `\u2192 ${n.entityName}`;case "subscribe":return "\u2192 select()";default:return `\u2192 ${n.entityName}`}}).join(" ")}analyzeActionFlow(t){let e=new Set,n=new Set,i=new Set;for(let a of t){for(let o of a.actionChain)e.add(o);for(let o of a.steps)o.type==="reducer"&&o.actionType&&n.add(o.actionType),o.type==="state"&&o.stateProperty&&i.add(o.stateProperty);}return {dispatched:Array.from(e),handled:Array.from(n),stateChanges:Array.from(i)}}generateMermaidDiagram(t,e,n){let i=["sequenceDiagram"];i.push(" participant C as Component"),i.push(" participant A as Action"),i.push(" participant E as Effect"),i.push(" participant R as Reducer"),i.push(" participant S as Store"),i.push(" participant SEL as Selector"),i.push(` Note over C,SEL: ${this.sanitize(e)} \u2192 ${this.sanitize(n)}`);for(let a=0;a<Math.min(t.length,2);a++){let o=t[a];i.push(` Note over C,SEL: Path ${a+1}`);for(let s of o.steps)switch(s.type){case "dispatch":i.push(` C->>A: dispatch(${this.sanitize(s.entityName)})`);break;case "effect":i.push(" A->>E: ofType()"),i.push(" E->>A: dispatch new action");break;case "reducer":i.push(" A->>R: on(action)"),i.push(" R->>S: update state");break;case "selector":i.push(" S->>SEL: state change");break;case "subscribe":i.push(" SEL->>C: select()");break}}return i.join(`
14
+ `)}sanitize(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").substring(0,20)}};var It=z$1.object({from:z$1.string().describe("Starting point (function/method name or semantic query)"),to:z$1.string().describe("Ending point (function/method name or semantic query)"),projectPath:a,trackStates:z$1.boolean().optional().default(true).describe("Track state changes along paths"),trackConditions:z$1.boolean().optional().default(true).describe("Track conditions/branches"),maxDepth:z$1.number().optional().default(15).describe("Maximum traversal depth"),format:z$1.enum(["sequence","tree","graph","mermaid"]).optional().default("sequence").describe("Output format"),highlightRecentChanges:z$1.boolean().optional().default(false).describe("Annotate trace nodes with recently-changed status (Prolly Tree)"),recentCommitsCount:z$1.number().optional().default(10).describe("Number of recent commits to consider for highlighting")}),Rt=z$1.object({target:z$1.string().describe("Target method/function to analyze"),question:z$1.enum(["why_not_called","what_affects","dependencies"]).describe("Type of analysis: why_not_called, what_affects, or dependencies"),projectPath:a,depth:z$1.number().optional().default(15).describe("Backward traversal depth"),includeStates:z$1.boolean().optional().default(true).describe("Include state dependencies"),includeEffects:z$1.boolean().optional().default(true).describe("Include side effects"),highlightRecentChanges:z$1.boolean().optional().default(false).describe("Annotate trace nodes with recently-changed status (Prolly Tree)"),recentCommitsCount:z$1.number().optional().default(10).describe("Number of recent commits to consider for highlighting")}),Ft=z$1.object({entryPoint:z$1.string().describe("Entry point function (e.g., 'AppInit()')"),targetState:z$1.string().describe("Target state to trace (e.g., 'startPage')"),projectPath:a,dataSources:z$1.array(z$1.string()).optional().describe("Data sources to analyze (auto-detected if not specified)"),trackTransformations:z$1.boolean().optional().default(true).describe("Track data transformations")}),vt=z$1.object({state:z$1.string().describe("State variable to analyze (e.g., 'user.isAuthenticated')"),scenarios:z$1.array(z$1.object({value:z$1.any().describe("Value for this scenario"),label:z$1.string().describe("Human-readable label")})).min(1).describe("Scenarios to analyze"),projectPath:a,scope:z$1.string().optional().describe("Scope of analysis (semantic query)")}),Dt=z$1.object({scenario:z$1.string().describe("Scenario to analyze (semantic query or function name)"),projectPath:a,includeGuards:z$1.boolean().optional().default(true).describe("Include guard conditions"),includeEffects:z$1.boolean().optional().default(true).describe("Include side effects"),groupBy:z$1.enum(["impact","location","type"]).optional().default("impact").describe("How to group results")}),Nt=z$1.object({from:z$1.string().describe("Starting point (component method, effect name, or action)"),to:z$1.string().describe("Ending point (component property, selector, or state property)"),projectPath:a,maxDepth:z$1.number().optional().default(20).describe("Maximum traversal depth"),includeActions:z$1.boolean().optional().default(true).describe("Include intermediate action details"),format:z$1.enum(["sequence","mermaid","json"]).optional().default("sequence").describe("Output format")}),H=class extends d{traceEngine=null;formatter=new C;parseArgs(t){return It.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath),n=e.getProjectContext?.();I$1.d("TRACEFLOW","storage_ctx",{ctx:JSON.stringify(n)}),this.traceEngine=new R(e,void 0);let i={from:t.from,to:t.to,trackStates:t.trackStates,trackConditions:t.trackConditions,maxDepth:t.maxDepth,format:t.format},a=await this.traceEngine.traceFlow(i),o;if(t.highlightRecentChanges){let{getRecentlyChangedEntities:r}=await import('./recently-changed-277BN4MZ.js'),c=e.getLibSQLAdapter?.();if(c){let l=await r(c,{lastCommits:t.recentCommitsCount});if(l){let d=[];for(let p of a.paths)for(let g of p.steps)g.entityId&&l.changedIds.has(g.entityId)&&(d.push(g.entityId),g.recentlyChanged=true);o={recentlyChangedNodes:[...new Set(d)],totalAnnotated:new Set(d).size,commitsAnalyzed:l.commitsAnalyzed};}}}let s;return t.format==="mermaid"?s=JSON.stringify({success:true,...a,...o?{recentlyChangedAnnotation:o}:{},formatted:a.mermaid||this.formatter.formatTraceFlowAsMermaid(a)},null,2):s=JSON.stringify({success:true,...a,...o?{recentlyChangedAnnotation:o}:{},formatted:this.formatter.formatTraceFlowAsText(a),_debug:a._debug},null,2),{content:[{type:"text",text:s}]}}},V=class extends d{traceEngine=null;formatter=new C;parseArgs(t){return Rt.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath);this.traceEngine=new R(e,void 0);let n={target:t.target,question:t.question,depth:t.depth,includeStates:t.includeStates,includeEffects:t.includeEffects},i=await this.traceEngine.traceBackwards(n),a;if(t.highlightRecentChanges){let{getRecentlyChangedEntities:s}=await import('./recently-changed-277BN4MZ.js'),r=e.getLibSQLAdapter?.();if(r){let c=await s(r,{lastCommits:t.recentCommitsCount});if(c){let l=[];for(let d of i.callers)d.entityId&&c.changedIds.has(d.entityId)&&(l.push(d.entityId),d.recentlyChanged=true);a={recentlyChangedNodes:[...new Set(l)],totalAnnotated:new Set(l).size,commitsAnalyzed:c.commitsAnalyzed};}}}return {content:[{type:"text",text:JSON.stringify({success:true,...i,...a?{recentlyChangedAnnotation:a}:{},formatted:this.formatter.formatTraceBackwardsAsText(i)},null,2)}]}}},Z=class extends d{dataFlowAnalyzer=null;formatter=new C;parseArgs(t){return Ft.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath);this.dataFlowAnalyzer=new j(e,void 0);let n={entryPoint:t.entryPoint,targetState:t.targetState,dataSources:t.dataSources,trackTransformations:t.trackTransformations},i=await this.dataFlowAnalyzer.traceDataFlow(n);return {content:[{type:"text",text:JSON.stringify({success:true,...i,formatted:this.formatter.formatDataFlowAsText(i),nextSteps:["taint_analysis() \u2014 security-focused analysis of the same data flows","analyze_state_chaos() \u2014 detect state management issues in traced flow"]},null,2)}]}}},J=class extends d{stateTracker=null;formatter=new C;parseArgs(t){return vt.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath);this.stateTracker=new I(e);let n={state:t.state,scenarios:t.scenarios,scope:t.scope},i=await this.stateTracker.analyzeStateImpact(n);return {content:[{type:"text",text:JSON.stringify({success:true,...i,formatted:this.formatter.formatStateImpactAsText(i)},null,2)}]}}},X=class extends d{conditionAnalyzer=null;formatter=new C;parseArgs(t){return Dt.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath);this.conditionAnalyzer=new N(e);let n={scenario:t.scenario,includeGuards:t.includeGuards,includeEffects:t.includeEffects,groupBy:t.groupBy},i=await this.conditionAnalyzer.findDecisionPoints(n);return {content:[{type:"text",text:JSON.stringify({success:true,...i,formatted:this.formatter.formatDecisionPointsAsText(i)},null,2)}]}}},K=class extends d{ngrxEngine=null;parseArgs(t){return Nt.parse(t)}async execute(t){let e=await this.ensureGraphStorageForProject(t.projectPath);this.ngrxEngine=new B(e);let n=await this.ngrxEngine.traceNgRxFlow({from:t.from,to:t.to,maxDepth:t.maxDepth,includeActions:t.includeActions,format:t.format}),i;if(t.format==="mermaid")i=JSON.stringify({success:true,...n,formatted:n.mermaid||"No paths found"},null,2);else {let a=[];a.push(`NgRx Flow: ${t.from} \u2192 ${t.to}`),a.push(`Found ${n.paths.length} path(s)
15
+ `);for(let o of n.paths){a.push(`Path ${o.id} (confidence: ${Math.round(o.confidence*100)}%)`),a.push(`Summary: ${o.summary}`),a.push("Steps:");for(let s of o.steps)a.push(` ${s.order}. [${s.type}] ${s.description}`),a.push(` File: ${s.file}:${s.line}`);a.push("");}a.push("Action Flow:"),a.push(` Dispatched: ${n.actionFlow.dispatched.join(", ")||"none"}`),a.push(` Handled: ${n.actionFlow.handled.join(", ")||"none"}`),a.push(` State Changes: ${n.actionFlow.stateChanges.join(", ")||"none"}`),i=JSON.stringify({success:true,...n,formatted:a.join(`
16
+ `)},null,2);}return {content:[{type:"text",text:i}]}}};function me(h){let t=new Map;return t.set("trace_flow",new H(h)),t.set("trace_backwards",new V(h)),t.set("trace_data_flow",new Z(h)),t.set("analyze_state_impact",new J(h)),t.set("find_decision_points",new X(h)),t.set("trace_ngrx_flow",new K(h)),t}var ye=[{name:"trace_flow",description:`Trace execution flow from point A to point B in the codebase.
17
+
18
+ Finds all possible paths and analyzes:
19
+ - State changes along each path
20
+ - Conditions and branches
21
+ - Async boundaries
22
+ - Call sequences
23
+
24
+ Example: trace_flow(from: "handleLogin", to: "redirectToHome")
25
+
26
+ Returns paths with confidence scores, state changes, and Mermaid diagrams.`,inputSchema:{type:"object",properties:{from:{type:"string",description:"Starting point (function/method name or semantic query)"},to:{type:"string",description:"Ending point (function/method name or semantic query)"},trackStates:{type:"boolean",description:"Track state changes along paths",default:true},trackConditions:{type:"boolean",description:"Track conditions/branches",default:true},maxDepth:{type:"number",description:"Maximum traversal depth",default:15},format:{type:"string",enum:["sequence","tree","graph","mermaid"],description:"Output format",default:"sequence"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["from","to"]}},{name:"trace_backwards",description:`Trace backwards from a method to find why it might not be called.
27
+
28
+ Analysis types:
29
+ - why_not_called: Find blocking conditions and missing callers
30
+ - what_affects: Identify all dependencies
31
+ - dependencies: Full dependency graph
32
+
33
+ Example: trace_backwards(target: "FinishTask", question: "why_not_called")
34
+
35
+ Returns callers, blocking conditions, state dependencies, and diagnosis.`,inputSchema:{type:"object",properties:{target:{type:"string",description:"Target method/function to analyze"},question:{type:"string",enum:["why_not_called","what_affects","dependencies"],description:"Type of analysis"},depth:{type:"number",description:"Backward traversal depth",default:15},includeStates:{type:"boolean",description:"Include state dependencies",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["target","question"]}},{name:"trace_data_flow",description:`Trace how data flows from sources to affect a target state.
36
+
37
+ Identifies:
38
+ - Data sources (API, storage, props, config)
39
+ - Transformations (parse, map, validate)
40
+ - Branching based on data values
41
+ - Behavior matrix for different inputs
42
+
43
+ Example: trace_data_flow(entryPoint: "AppInit", targetState: "startPage")
44
+
45
+ Returns data flows, critical conditions, and behavior combinations.`,inputSchema:{type:"object",properties:{entryPoint:{type:"string",description:"Entry point function"},targetState:{type:"string",description:"Target state to trace"},dataSources:{type:"array",items:{type:"string"},description:"Data sources to analyze (auto-detected if not specified)"},trackTransformations:{type:"boolean",description:"Track data transformations",default:true},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["entryPoint","targetState"]}},{name:"analyze_state_impact",description:`Analyze the impact of a state variable across different scenarios.
46
+
47
+ Analyzes:
48
+ - All usages of the state
49
+ - Reachable/blocked paths per scenario
50
+ - Enabled features
51
+ - Conflicts and race conditions
52
+ - Ripple effects
53
+
54
+ Example: analyze_state_impact(state: "isAuthenticated", scenarios: [{value: true, label: "logged in"}, {value: false, label: "logged out"}])
55
+
56
+ Returns usage analysis, scenario comparisons, and conflict detection.`,inputSchema:{type:"object",properties:{state:{type:"string",description:"State variable to analyze"},scenarios:{type:"array",items:{type:"object",properties:{value:{description:"Value for this scenario"},label:{type:"string",description:"Human-readable label"}},required:["value","label"]},description:"Scenarios to analyze",minItems:1},scope:{type:"string",description:"Scope of analysis (semantic query)"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["state","scenarios"]}},{name:"find_decision_points",description:`Find all decision points in a scenario's execution flow.
57
+
58
+ Decision point types:
59
+ - validation: Input validation
60
+ - api_response: API response handling
61
+ - state_mutation: State changes
62
+ - guard: Guard conditions
63
+ - loop: Loop control
64
+ - error_handling: try-catch
65
+ - feature_flag: Feature toggles
66
+
67
+ Example: find_decision_points(scenario: "user checkout flow")
68
+
69
+ Returns decision points grouped by impact with Mermaid flowchart.`,inputSchema:{type:"object",properties:{scenario:{type:"string",description:"Scenario to analyze"},includeGuards:{type:"boolean",description:"Include guard conditions",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},groupBy:{type:"string",enum:["impact","location","type"],description:"How to group results",default:"impact"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["scenario"]}},{name:"trace_ngrx_flow",description:`Trace NgRx/Redux event-driven flow from action dispatch to state subscription.
70
+
71
+ **IMPORTANT**: Use this for Angular projects with NgRx state management instead of trace_flow.
72
+ Standard trace_flow cannot follow NgRx event-driven relationships.
73
+
74
+ Follows the NgRx chain:
75
+ 1. Component/Effect dispatches action
76
+ 2. Effect listens via ofType()
77
+ 3. Effect dispatches new action
78
+ 4. Reducer handles action via on()
79
+ 5. Reducer modifies state
80
+ 6. Selector reads state
81
+ 7. Component subscribes via select()
82
+
83
+ Example: trace_ngrx_flow(from: "MobileTaskEffects.postMessages2$", to: "TestEndComponent.setCompleteContent")
84
+
85
+ Returns:
86
+ - Flow paths through NgRx entities
87
+ - Action chain (all actions traversed)
88
+ - State changes made
89
+ - Mermaid sequence diagram`,inputSchema:{type:"object",properties:{from:{type:"string",description:"Starting point (component method, effect name, or action)"},to:{type:"string",description:"Ending point (component property, selector, or state property)"},maxDepth:{type:"number",description:"Maximum traversal depth",default:20},includeActions:{type:"boolean",description:"Include intermediate action details",default:true},format:{type:"string",enum:["sequence","mermaid","json"],description:"Output format",default:"sequence"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project."}},required:["from","to"]}}];export{J as AnalyzeStateImpactToolHandler,X as FindDecisionPointsToolHandler,ye as TRACING_TOOL_DEFINITIONS,V as TraceBackwardsToolHandler,Z as TraceDataFlowToolHandler,H as TraceFlowToolHandler,K as TraceNgRxFlowToolHandler,me as createTracingToolHandlers};