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,277 @@
1
+ import { BaseToolHandler } from './chunk-SAMX3HJQ.js';
2
+ import './chunk-WIE3G5ES.js';
3
+ import { getGlobalContainer, getOrCreateAgent } from './chunk-3MQ7LRPN.js';
4
+ import './chunk-XK2NY7RB.js';
5
+ import './chunk-HEMJHRHZ.js';
6
+ import { toError } from './chunk-5WKPA33T.js';
7
+ import './chunk-GMVGCSNU.js';
8
+ import './chunk-VCCBEJQ5.js';
9
+ import './chunk-NAQKA54E.js';
10
+ import { z } from 'zod';
11
+
12
+ var SemanticMergeSchema = z.object({
13
+ sourceBranch: z.string().describe("Source branch name (where changes come from)"),
14
+ targetBranch: z.string().optional().describe("Target branch name (where to merge). Defaults to current branch."),
15
+ dryRun: z.boolean().optional().default(true).describe("Preview only, don't apply changes"),
16
+ autoResolve: z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts"),
17
+ includeAISuggestions: z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts")
18
+ });
19
+ var SemanticMergeToolHandler = class extends BaseToolHandler {
20
+ parseArgs(args) {
21
+ return SemanticMergeSchema.parse(args);
22
+ }
23
+ async execute(args) {
24
+ try {
25
+ const container = getGlobalContainer();
26
+ const conductor = this.context.getConductor();
27
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
28
+ const targetBranch = args.targetBranch || await this.getCurrentBranch();
29
+ const result = await mergeAgent.performSemanticMerge({
30
+ branchA: targetBranch,
31
+ branchB: args.sourceBranch,
32
+ dryRun: args.dryRun,
33
+ autoResolve: args.autoResolve,
34
+ includeAISuggestions: args.includeAISuggestions
35
+ });
36
+ return {
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: JSON.stringify(
41
+ {
42
+ success: result.success,
43
+ summary: {
44
+ sourceBranch: args.sourceBranch,
45
+ targetBranch,
46
+ dryRun: args.dryRun,
47
+ totalUnitsAnalyzed: result.stats.totalUnitsAnalyzed,
48
+ matchedUnits: result.stats.matchedUnits,
49
+ conflictsDetected: result.stats.conflictsDetected,
50
+ autoResolved: result.stats.autoResolved,
51
+ manualReviewRequired: result.stats.manualReviewRequired,
52
+ mergeTimeMs: result.stats.mergeTimeMs
53
+ },
54
+ conflicts: result.mergeResult?.conflicts.map(
55
+ (c) => ({
56
+ id: c.id,
57
+ type: c.type,
58
+ severity: c.severity,
59
+ description: c.description,
60
+ branchAUnit: {
61
+ name: c.branchAUnit.name,
62
+ filePath: c.branchAUnit.filePath
63
+ },
64
+ branchBUnit: {
65
+ name: c.branchBUnit.name,
66
+ filePath: c.branchBUnit.filePath
67
+ },
68
+ aiSuggestions: c.aiSuggestions
69
+ })
70
+ ),
71
+ actions: result.mergeResult?.mergeActions.slice(0, 20).map((a) => ({
72
+ type: a.type,
73
+ unitId: a.unitId,
74
+ description: a.description
75
+ })),
76
+ error: result.error
77
+ },
78
+ null,
79
+ 2
80
+ )
81
+ }
82
+ ]
83
+ };
84
+ } catch (error) {
85
+ const err = toError(error);
86
+ return {
87
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
88
+ };
89
+ }
90
+ }
91
+ async getCurrentBranch() {
92
+ const { execSync } = await import('child_process');
93
+ try {
94
+ return execSync("git symbolic-ref --short HEAD", {
95
+ encoding: "utf-8",
96
+ stdio: ["pipe", "pipe", "ignore"],
97
+ windowsHide: true
98
+ }).trim();
99
+ } catch {
100
+ return "HEAD";
101
+ }
102
+ }
103
+ };
104
+ var AnalyzeMergeConflictsSchema = z.object({
105
+ branchA: z.string().describe("First branch name"),
106
+ branchB: z.string().describe("Second branch name")
107
+ });
108
+ var AnalyzeMergeConflictsToolHandler = class extends BaseToolHandler {
109
+ parseArgs(args) {
110
+ return AnalyzeMergeConflictsSchema.parse(args);
111
+ }
112
+ async execute(args) {
113
+ try {
114
+ const container = getGlobalContainer();
115
+ const conductor = this.context.getConductor();
116
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
117
+ const result = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
118
+ return {
119
+ content: [
120
+ {
121
+ type: "text",
122
+ text: JSON.stringify(
123
+ {
124
+ branchA: args.branchA,
125
+ branchB: args.branchB,
126
+ totalConflicts: result.stats.totalConflicts,
127
+ bySeverity: result.stats.bySeverity,
128
+ byType: result.stats.byType,
129
+ conflicts: result.conflicts.map((c) => ({
130
+ id: c.id,
131
+ type: c.type,
132
+ severity: c.severity,
133
+ description: c.description,
134
+ branchAUnit: {
135
+ name: c.branchAUnit.name,
136
+ type: c.branchAUnit.type,
137
+ filePath: c.branchAUnit.filePath,
138
+ startLine: c.branchAUnit.startLine
139
+ },
140
+ branchBUnit: {
141
+ name: c.branchBUnit.name,
142
+ type: c.branchBUnit.type,
143
+ filePath: c.branchBUnit.filePath,
144
+ startLine: c.branchBUnit.startLine
145
+ }
146
+ }))
147
+ },
148
+ null,
149
+ 2
150
+ )
151
+ }
152
+ ]
153
+ };
154
+ } catch (error) {
155
+ const err = toError(error);
156
+ return {
157
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
158
+ };
159
+ }
160
+ }
161
+ };
162
+ var GetMergeSuggestionsSchema = z.object({
163
+ conflictId: z.string().describe("ID of the conflict to get suggestions for"),
164
+ branchA: z.string().describe("First branch name"),
165
+ branchB: z.string().describe("Second branch name")
166
+ });
167
+ var GetMergeSuggestionsToolHandler = class extends BaseToolHandler {
168
+ parseArgs(args) {
169
+ return GetMergeSuggestionsSchema.parse(args);
170
+ }
171
+ async execute(args) {
172
+ try {
173
+ const container = getGlobalContainer();
174
+ const conductor = this.context.getConductor();
175
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
176
+ const analysis = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
177
+ const conflict = analysis.conflicts.find((c) => c.id === args.conflictId);
178
+ if (!conflict) {
179
+ return {
180
+ content: [
181
+ {
182
+ type: "text",
183
+ text: JSON.stringify({
184
+ error: `Conflict ${args.conflictId} not found`,
185
+ availableConflicts: analysis.conflicts.map((c) => c.id)
186
+ })
187
+ }
188
+ ]
189
+ };
190
+ }
191
+ const suggestions = await mergeAgent.getSuggestions(conflict);
192
+ return {
193
+ content: [
194
+ {
195
+ type: "text",
196
+ text: JSON.stringify(
197
+ {
198
+ conflictId: args.conflictId,
199
+ conflict: {
200
+ type: conflict.type,
201
+ severity: conflict.severity,
202
+ description: conflict.description
203
+ },
204
+ suggestions,
205
+ suggestionsCount: suggestions.length
206
+ },
207
+ null,
208
+ 2
209
+ )
210
+ }
211
+ ]
212
+ };
213
+ } catch (error) {
214
+ const err = toError(error);
215
+ return {
216
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
217
+ };
218
+ }
219
+ }
220
+ };
221
+ var GetSemanticMergeInfoSchema = z.object({});
222
+ var GetSemanticMergeInfoToolHandler = class extends BaseToolHandler {
223
+ parseArgs(args) {
224
+ return GetSemanticMergeInfoSchema.parse(args);
225
+ }
226
+ async execute(_args) {
227
+ return {
228
+ content: [
229
+ {
230
+ type: "text",
231
+ text: JSON.stringify(
232
+ {
233
+ name: "Semantic Merge",
234
+ version: "1.0.0",
235
+ description: "AI-powered semantic merge for Git branches",
236
+ capabilities: [
237
+ "Fast Path matching (90%+ coverage via hashes)",
238
+ "Semantic matching for moved/refactored code",
239
+ "Intent classification (BugFix, Refactoring, FeatureAddition, APIChange)",
240
+ "Conflict detection and severity classification",
241
+ "AI-assisted conflict resolution suggestions"
242
+ ],
243
+ tools: [
244
+ {
245
+ name: "semantic_merge",
246
+ description: "Perform semantic merge of branches using AI",
247
+ parameters: ["sourceBranch", "targetBranch?", "dryRun?", "autoResolve?", "includeAISuggestions?"]
248
+ },
249
+ {
250
+ name: "analyze_merge_conflicts",
251
+ description: "Analyze merge conflicts between two branches",
252
+ parameters: ["branchA", "branchB"]
253
+ },
254
+ {
255
+ name: "get_merge_suggestions",
256
+ description: "Get AI suggestions for resolving a specific conflict",
257
+ parameters: ["conflictId", "branchA", "branchB"]
258
+ }
259
+ ],
260
+ metrics: {
261
+ fastPathCoverageTarget: ">90%",
262
+ semanticMatchingAccuracyTarget: ">80%",
263
+ autoMergeRateTarget: ">60%"
264
+ }
265
+ },
266
+ null,
267
+ 2
268
+ )
269
+ }
270
+ ]
271
+ };
272
+ }
273
+ };
274
+
275
+ export { AnalyzeMergeConflictsToolHandler, GetMergeSuggestionsToolHandler, GetSemanticMergeInfoToolHandler, SemanticMergeToolHandler };
276
+ //# sourceMappingURL=merge-tool-handlers-YH62ZLPJ.js.map
277
+ //# sourceMappingURL=merge-tool-handlers-YH62ZLPJ.js.map
@@ -0,0 +1,13 @@
1
+ import {a,b}from'./chunk-E4J4VT3N.js';import {d as d$1}from'./chunk-XG3ACLWR.js';import'./chunk-XJ2Z5QQO.js';import {a as a$2}from'./chunk-IFKMF76K.js';import'./chunk-SV3WKUNV.js';import'./chunk-PZF7YC35.js';import {a as a$1}from'./chunk-F3VMUQ7O.js';import {R,I as I$1}from'./chunk-4BI7EBPQ.js';import {d}from'./chunk-DXB73IDG.js';import {join}from'path';import {createHash}from'crypto';import {readdirSync,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import Pt from'yaml';import {z}from'zod';R();var k={};d(k,{checkDeepNesting:()=>pt,checkGodFunction:()=>mt,checkLargeClass:()=>ft,checkNoDocumentation:()=>dt,checkSmallFocusedFunction:()=>ht,checkTooManyParams:()=>ut});function mt(o){if((o.metadata?.modifiers??[]).includes("partial"))return {match:false,confidence:0};let i=o.metadata?.metrics,e=i?.cyclomaticComplexity??0,n=i?.linesOfCode??0,a=[];return e>20&&a.push(`cyclomatic=${e}`),n>200&&a.push(`LOC=${n}`),a.length===0?{match:false,confidence:0}:{match:true,confidence:a.length===2?.95:.8,matchedCriteria:a}}function pt(o){let i=o.metadata?.metrics?.nestingDepth??0;return i<=5?{match:false,confidence:0}:{match:true,confidence:Math.min(.5+(i-5)*.1,1),matchedCriteria:[`nestingDepth=${i}`]}}function ut(o){let t=o.metadata?.parameters??[];if(t.length<=7)return {match:false,confidence:0};let i=o.metadata?.modifiers??[];if(i.includes("constructor")||i.includes("partial"))return {match:false,confidence:0};let e=t.filter(n=>n.type&&/^I[A-Z]/.test(n.type)).length;return t.length>0&&e/t.length>=.7?{match:false,confidence:0}:{match:true,confidence:Math.min(.6+(t.length-7)*.05,1),matchedCriteria:[`paramCount=${t.length}`]}}function dt(o){let t=o.metadata?.modifiers??[];if(!(t.includes("public")||t.includes("export")||t.includes("exported")))return {match:false,confidence:0};if(t.includes("partial"))return {match:false,confidence:0};if(t.includes("internal"))return {match:false,confidence:0};let e=o.filePath;if(/[\\/](Minimal|Internal|Hosting|Kestrel|Middleware|Extensions)\b/i.test(e))return {match:false,confidence:0};let a=o.metadata?.signature?.includes("/**")??false,r=o.metadata?.documentation!=null||o.metadata?.description!=null;return a||r?{match:false,confidence:0}:{match:true,confidence:.7,matchedCriteria:["public-no-docs"]}}function ht(o){let t=o.metadata?.metrics,i=t?.cyclomaticComplexity??0,e=t?.linesOfCode??0;if(e<3)return {match:false,confidence:0};let n=[];return e<=30&&n.push(`LOC=${e}`),i<=5&&n.push(`cyclomatic=${i}`),n.length<2?{match:false,confidence:0}:{match:true,confidence:.85,matchedCriteria:n}}function ft(o){if(o.type!=="class")return {match:false,confidence:0};let i=o.metadata?.metrics?.linesOfCode??0,e=o.metadata?.metrics?.methodCount??0,n=[];return i>500&&n.push(`LOC=${i}`),e>20&&n.push(`methods=${e}`),i<=500?{match:false,confidence:0}:{match:true,confidence:n.length===2?.9:.7,matchedCriteria:n}}R();var $=class{constructor(t,i){this.exemplarsDir=t;this.cacheDir=i??join(process.cwd(),".cache");}exemplars=new Map;exemplarsByPattern=new Map;embeddings=new Map;loaded=false;embedded=false;cacheDir;async load(t){if(this.loaded)return;let i=t??this.exemplarsDir??join(import.meta.dirname,"exemplars"),e;try{e=readdirSync(i).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));}catch{I$1.w("EXEMPLAR_STORE","dir_not_found",{dir:i}),this.loaded=true;return}for(let n of e)try{let a=readFileSync(join(i,n),"utf-8"),r=Pt.parse(a);if(!r?.exemplars)continue;for(let s of r.exemplars){let m={id:s.id,patternId:s.patternId,language:s.language,code:s.code.slice(0,400),description:s.description};this.exemplars.set(s.id,m);let c=this.exemplarsByPattern.get(s.patternId)??[];c.push(m),this.exemplarsByPattern.set(s.patternId,c);}I$1.i("EXEMPLAR_STORE","loaded_file",{file:n,count:r.exemplars.length});}catch(a){I$1.e("EXEMPLAR_STORE","load_error",{file:n,error:String(a)});}this.loaded=true,I$1.i("EXEMPLAR_STORE","store_ready",{total:this.exemplars.size});}async ensureEmbeddings(t){if(this.embedded||this.exemplars.size===0)return;let i=this.computeHash(),e=join(this.cacheDir,"pattern-exemplar-embeddings.json");if(this.tryLoadCache(e,i)){this.embedded=true,I$1.i("EXEMPLAR_STORE","cache_hit",{exemplars:this.embeddings.size});return}I$1.i("EXEMPLAR_STORE","generating_embeddings",{count:this.exemplars.size});let n=Date.now();for(let[a,r]of this.exemplars)try{let s=await t.generateCodeEmbedding(r.code,r.language);this.embeddings.set(a,s);}catch(s){I$1.w("EXEMPLAR_STORE","embed_error",{id:a,error:String(s)});}I$1.i("EXEMPLAR_STORE","embeddings_generated",{count:this.embeddings.size,durationMs:Date.now()-n}),this.saveCache(e,i),this.embedded=true;}findSimilarExemplars(t,i,e=1){let n=this.exemplarsByPattern.get(i)??[];if(n.length===0)return [];let a=[];for(let r of n){let s=this.embeddings.get(r.id);if(!s)continue;let m=a$2(t,s);a.push({id:r.id,similarity:m,description:r.description});}return a.sort((r,s)=>s.similarity-r.similarity).slice(0,e)}get(t){return this.exemplars.get(t)}getForPattern(t){return this.exemplarsByPattern.get(t)??[]}get size(){return this.exemplars.size}computeHash(){let t=[...this.exemplars.values()].map(i=>i.code).sort().join("|");return createHash("sha256").update(t).digest("hex").slice(0,16)}tryLoadCache(t,i){try{if(!existsSync(t))return !1;let e=JSON.parse(readFileSync(t,"utf-8"));if(e.hash!==i)return !1;for(let[n,a]of Object.entries(e.embeddings)){if(!this.exemplars.has(n))continue;let r=Buffer.from(a,"base64");this.embeddings.set(n,new Float32Array(r.buffer,r.byteOffset,r.byteLength/4));}return this.embeddings.size>0}catch{return false}}saveCache(t,i){try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let e={hash:i,embeddings:{}};for(let[n,a]of this.embeddings){let r=Buffer.from(a.buffer,a.byteOffset,a.byteLength);e.embeddings[n]=r.toString("base64");}writeFileSync(t,JSON.stringify(e),"utf-8"),I$1.i("EXEMPLAR_STORE","cache_saved",{file:t,count:this.embeddings.size});}catch(e){I$1.w("EXEMPLAR_STORE","cache_save_error",{error:String(e)});}}};R();var Rt=z.object({type:z.string(),direction:z.enum(["incoming","outgoing"]),minCount:z.number().optional(),maxCount:z.number().optional(),crossFileRatio:z.object({min:z.number().optional(),max:z.number().optional()}).optional()}),Mt=z.object({entityTypes:z.array(z.string()).optional(),requiredModifiers:z.array(z.string()).optional(),forbiddenModifiers:z.array(z.string()).optional(),returnTypeMatch:z.string().optional(),returnTypeNotMatch:z.string().optional(),minParams:z.number().optional(),maxParams:z.number().optional(),paramTypeRequired:z.string().optional(),paramTypeAbsent:z.string().optional(),minCyclomatic:z.number().optional(),maxCyclomatic:z.number().optional(),minCognitive:z.number().optional(),minNesting:z.number().optional(),minLOC:z.number().optional(),maxLOC:z.number().optional(),hasLoops:z.boolean().optional(),hasExceptions:z.boolean().optional(),hasAwaits:z.boolean().optional(),minBranches:z.number().optional(),minCallCount:z.number().optional(),callsInclude:z.array(z.string()).optional(),callsExclude:z.array(z.string()).optional(),decoratorMatch:z.array(z.string()).optional(),hasNoInheritance:z.boolean().optional(),filePathNotMatch:z.string().optional(),nameMatch:z.string().optional(),nameNotMatch:z.string().optional(),relationships:z.array(Rt).optional()}),Tt=z.object({id:z.string(),language:z.string().optional(),category:z.enum(["anti-pattern","best-pattern","code-smell","optimization"]),severity:z.enum(["critical","high","medium","low","info"]),name:z.string(),description:z.string(),suggestion:z.string(),bigO:z.object({before:z.string(),after:z.string()}).optional(),benchmark:z.string().optional(),tags:z.array(z.string()).default([]),enabled:z.boolean().default(true),structural:Mt.optional(),customDetector:z.string().optional(),exemplarIds:z.array(z.string()).optional(),minSemanticSimilarity:z.number().default(0),minStructuralConfidence:z.number().default(.6)}),vt=z.object({patterns:z.array(Tt)}),N=class{constructor(t){this.rulesDir=t;}patterns=new Map;allPatterns=new Map;loaded=false;async load(t){if(this.loaded)return;let i=t??this.rulesDir??join(import.meta.dirname,"rules"),e;try{e=readdirSync(i).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));}catch{I$1.w("PATTERN_REGISTRY","rules_dir_not_found",{dir:i}),this.loaded=true;return}for(let n of e){let a=n.replace(/\.ya?ml$/,"");try{let r=readFileSync(join(i,n),"utf-8"),s=Pt.parse(r),c=vt.parse(s).patterns.map(p=>({...p,language:p.language??a})),h=this.patterns.get(a)??[];this.patterns.set(a,[...h,...c]);for(let p of c)this.allPatterns.has(p.id)&&I$1.w("PATTERN_REGISTRY","duplicate_pattern_id",{id:p.id}),this.allPatterns.set(p.id,p);I$1.i("PATTERN_REGISTRY","loaded_rules",{file:n,count:c.length});}catch(r){I$1.e("PATTERN_REGISTRY","load_error",{file:n,error:String(r)});}}this.loaded=true,I$1.i("PATTERN_REGISTRY","registry_ready",{languages:this.patterns.size,totalPatterns:this.allPatterns.size});}getPatterns(t){let{language:i,category:e="all",tags:n,enabledOnly:a=true}=t,r=[];return i?r=[...this.patterns.get(i)??[],...this.patterns.get("common")??[]]:r=[...this.allPatterns.values()],a&&(r=r.filter(s=>s.enabled)),e!=="all"&&(r=r.filter(s=>s.category===e)),n&&n.length>0&&(r=r.filter(s=>n.some(m=>s.tags.includes(m)))),r}getPattern(t){return this.allPatterns.get(t)}getLanguages(){return [...this.patterns.keys()]}get size(){return this.allPatterns.size}};R();var D=class{constructor(t,i){this.exemplarStore=t;this.embeddingGen=i;}async validate(t,i){let e=[],n=t.filter(r=>r.pattern.minSemanticSimilarity>0),a=t.filter(r=>r.pattern.minSemanticSimilarity===0);for(let r of a)e.push(this.createMatch(r,1,void 0));if(n.length>0){this.embeddingGen&&await this.exemplarStore.ensureEmbeddings(this.embeddingGen);for(let r of n){let s=await this.getEntityEmbedding(r);if(!s){r.confidence>=r.pattern.minStructuralConfidence&&e.push(this.createMatch(r,-1,void 0));continue}let c=this.exemplarStore.findSimilarExemplars(s,r.pattern.id,1)[0],h=c?.similarity??0;h>=r.pattern.minSemanticSimilarity&&e.push(this.createMatch(r,h,c));}}return I$1.i("SEMANTIC_VALIDATOR","validation_complete",{candidates:t.length,confirmed:e.length,structuralOnly:a.length,semanticValidated:n.length}),e}createMatch(t,i,e){let n=t.pattern.minSemanticSimilarity===0,a=i<0,r=n||a?t.confidence:t.confidence*.4+i*.6;return {patternId:t.pattern.id,pattern:t.pattern,entityId:t.entity.id,entityName:t.entity.name,entityType:t.entity.type,filePath:t.entity.filePath,line:t.entity.location?.start?.line??0,structuralConfidence:t.confidence,semanticSimilarity:n?1:a?0:i,combinedScore:r,matchedCriteria:t.matchedCriteria,closestExemplar:e?{id:e.id,similarity:e.similarity,description:e.description}:void 0}}async getEntityEmbedding(t){let i=t.entity.embeddingBase64;if(i)try{let e=Buffer.from(i,"base64");return new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}catch{}if(this.embeddingGen)try{let e=t.entity.embeddingText??t.entity.name,n=t.entity.language??t.entity.metadata?.language;return await this.embeddingGen.generateCodeEmbedding(e,n)}catch(e){I$1.w("SEMANTIC_VALIDATOR","embed_error",{entity:t.entity.id,error:String(e)});}return null}};R();var tt=new Map;function B(o){for(let[t,i]of Object.entries(o))tt.set(t,i);}var K=new WeakMap;function Z(o){let t=K.get(o);if(t)return t;let i=o.structural;return t={entityTypeSet:i?.entityTypes?new Set(i.entityTypes):null,returnTypeMatchRe:i?.returnTypeMatch?new RegExp(i.returnTypeMatch,"i"):null,returnTypeNotMatchRe:i?.returnTypeNotMatch?new RegExp(i.returnTypeNotMatch,"i"):null,paramTypeRequiredRe:i?.paramTypeRequired?new RegExp(i.paramTypeRequired,"i"):null,paramTypeAbsentRe:i?.paramTypeAbsent?new RegExp(i.paramTypeAbsent,"i"):null,callsIncludeRe:i?.callsInclude?i.callsInclude.map(e=>new RegExp(e,"i")):null,callsExcludeRe:i?.callsExclude?i.callsExclude.map(e=>new RegExp(e,"i")):null,decoratorMatchRe:i?.decoratorMatch?i.decoratorMatch.map(e=>new RegExp(e,"i")):null,nameMatchRe:i?.nameMatch?new RegExp(i.nameMatch,"i"):null,nameNotMatchRe:i?.nameNotMatch?new RegExp(i.nameNotMatch,"i"):null,filePathNotMatchRe:i?.filePathNotMatch?new RegExp(i.filePathNotMatch,"i"):null,totalCriteriaCount:$t(i??{})},K.set(o,t),t}var Q=new WeakMap;function wt(o){let t=Q.get(o);if(t)return t;let i=o.metadata,e=i?.metrics,n=i?.controlFlow,a=i?.calls??[],r=i?.decorators??[],s=i?.inheritance;return t={modifiers:i?.modifiers??[],returnType:i?.returnType,params:i?.parameters??[],metrics:{cyclomaticComplexity:e?.cyclomaticComplexity??0,cognitiveComplexity:e?.cognitiveComplexity??0,linesOfCode:e?.linesOfCode??0,nestingDepth:e?.nestingDepth??0},cf:{branches:n?.branches?.length??0,loops:n?.loops?.length??0,exceptions:n?.exceptions?.length??0,awaits:n?.awaits?.length??0},callNames:a.map(m=>`${m.target??""}.${m.name??""}`),decoratorNames:r.map(m=>m.name),hasInheritance:(s?.baseClasses?.length??0)>0||(s?.interfaces?.length??0)>0},Q.set(o,t),t}var S={confidence:0,matchedCriteria:[]},O=class{evalCache=new Map;clearEvalCache(){this.evalCache.clear();}async detect(t,i,e){let n=[],a=new Map;for(let c of t){let h=a.get(c.type);h?h.push(c):a.set(c.type,[c]);}let r=[];for(let c of i){let h=Z(c),p;if(h.entityTypeSet){p=[];for(let u of h.entityTypeSet){let g=a.get(u);g&&p.push(...g);}}else p=t;for(let u of p){let g=this.evaluateMetadataCriteria(u,c,h);g.confidence>0&&r.push({entity:u,pattern:c,confidence:g.confidence,matched:g.matchedCriteria});}}let s=r.filter(c=>c.pattern.structural?.relationships&&c.pattern.structural.relationships.length>0),m=r.filter(c=>!c.pattern.structural?.relationships||c.pattern.structural.relationships.length===0);for(let c of m)c.confidence>=c.pattern.minStructuralConfidence&&n.push({entity:c.entity,pattern:c.pattern,confidence:c.confidence,matchedCriteria:c.matched});if(s.length>0&&e){let c=[...new Set(s.map(u=>u.entity.id))],h=[];try{let[u,g]=await Promise.all([e.findRelationships({filters:{fromId:c},limit:1e4}),e.findRelationships({filters:{toId:c},limit:1e4})]);h=[...u,...g];}catch{}let p=new Map;for(let u of h){let g=p.get(u.fromId);if(g?g.push(u):p.set(u.fromId,[u]),u.fromId!==u.toId){let y=p.get(u.toId);y?y.push(u):p.set(u.toId,[u]);}}for(let u of s){let g=p.get(u.entity.id)??[],y=this.evaluateRelationshipCriteria(u.entity,g,u.pattern.structural.relationships);if(y.passed){let C=u.matched.length+y.matchedCriteria.length,R=Z(u.pattern),b=C/Math.max(R.totalCriteriaCount,1);b>=u.pattern.minStructuralConfidence&&n.push({entity:u.entity,pattern:u.pattern,confidence:Math.min(b,1),matchedCriteria:[...u.matched,...y.matchedCriteria]});}}}else if(s.length>0)for(let c of s)c.confidence>=c.pattern.minStructuralConfidence&&n.push({entity:c.entity,pattern:c.pattern,confidence:c.confidence,matchedCriteria:c.matched});return I$1.i("STRUCTURAL_DETECTOR","detection_complete",{entities:t.length,patterns:i.length,candidates:n.length}),n}evaluateMetadataCriteria(t,i,e){let n=`${t.id}::${i.id}`,a=this.evalCache.get(n);if(a)return a;let r=this.evaluateMetadataUncached(t,i,e);return this.evalCache.set(n,r),r}evaluateRequired(t,i,e,n){let a=[];if(i.entityTypeSet&&a.push(`entityType:${t.type}`),e.requiredModifiers){for(let r of e.requiredModifiers)if(!n.modifiers.includes(r))return null;a.push(`modifiers:${e.requiredModifiers.join(",")}`);}if(e.forbiddenModifiers){for(let r of e.forbiddenModifiers)if(n.modifiers.includes(r))return null;a.push("no-forbidden-modifiers");}if(e.hasNoInheritance){if(n.hasInheritance)return null;a.push("no-inheritance");}return i.filePathNotMatchRe&&t.filePath&&i.filePathNotMatchRe.test(t.filePath)||i.nameNotMatchRe&&i.nameNotMatchRe.test(t.name)?null:a}evaluateOptional(t,i,e,n,a){let r=0,s=0;if(i.returnTypeMatchRe&&(r++,typeof n.returnType=="string"&&i.returnTypeMatchRe.test(n.returnType)&&(s++,a.push(`returnType:~/${e.returnTypeMatch}/`))),i.returnTypeNotMatchRe&&(r++,typeof n.returnType=="string"&&!i.returnTypeNotMatchRe.test(n.returnType)&&(s++,a.push(`returnType:!~/${e.returnTypeNotMatch}/`))),e.minParams!=null&&(r++,n.params.length>=e.minParams&&(s++,a.push(`params>=${e.minParams}`))),e.maxParams!=null&&(r++,n.params.length<=e.maxParams&&(s++,a.push(`params<=${e.maxParams}`))),i.paramTypeRequiredRe&&(r++,n.params.some(m=>m.type&&i.paramTypeRequiredRe.test(m.type))&&(s++,a.push(`paramType:${e.paramTypeRequired}`))),i.paramTypeAbsentRe&&(r++,n.params.some(m=>m.type&&i.paramTypeAbsentRe.test(m.type))||(s++,a.push(`paramType:!${e.paramTypeAbsent}`))),e.minCyclomatic!=null&&(r++,n.metrics.cyclomaticComplexity>=e.minCyclomatic&&(s++,a.push(`cyclomatic>=${e.minCyclomatic}`))),e.maxCyclomatic!=null&&(r++,n.metrics.cyclomaticComplexity<=e.maxCyclomatic&&(s++,a.push(`cyclomatic<=${e.maxCyclomatic}`))),e.minCognitive!=null&&(r++,n.metrics.cognitiveComplexity>=e.minCognitive&&(s++,a.push(`cognitive>=${e.minCognitive}`))),e.minNesting!=null&&(r++,n.metrics.nestingDepth>=e.minNesting&&(s++,a.push(`nesting>=${e.minNesting}`))),e.minLOC!=null&&(r++,n.metrics.linesOfCode>=e.minLOC&&(s++,a.push(`LOC>=${e.minLOC}`))),e.maxLOC!=null&&(r++,n.metrics.linesOfCode<=e.maxLOC&&(s++,a.push(`LOC<=${e.maxLOC}`))),e.hasLoops!=null&&(r++,n.cf.loops>0===e.hasLoops&&(s++,a.push(e.hasLoops?"hasLoops":"noLoops"))),e.hasExceptions!=null&&(r++,n.cf.exceptions>0===e.hasExceptions&&(s++,a.push(e.hasExceptions?"hasExceptions":"noExceptions"))),e.hasAwaits!=null&&(r++,n.cf.awaits>0===e.hasAwaits&&(s++,a.push(e.hasAwaits?"hasAwaits":"noAwaits"))),e.minBranches!=null&&(r++,n.cf.branches>=e.minBranches&&(s++,a.push(`branches>=${e.minBranches}`))),e.minCallCount!=null&&(r++,n.callNames.length>=e.minCallCount&&(s++,a.push(`calls>=${e.minCallCount}`))),i.callsIncludeRe)for(let m=0;m<i.callsIncludeRe.length;m++)r++,n.callNames.some(c=>i.callsIncludeRe[m].test(c))&&(s++,a.push(`calls:~/${e.callsInclude[m]}/`));if(i.callsExcludeRe)for(let m=0;m<i.callsExcludeRe.length;m++)r++,n.callNames.some(c=>i.callsExcludeRe[m].test(c))||(s++,a.push(`calls:!~/${e.callsExclude[m]}/`));if(i.decoratorMatchRe)for(let m=0;m<i.decoratorMatchRe.length;m++)r++,n.decoratorNames.some(c=>i.decoratorMatchRe[m].test(c))&&(s++,a.push(`decorator:~/${e.decoratorMatch[m]}/`));return i.nameMatchRe&&(r++,i.nameMatchRe.test(t.name)&&(s++,a.push(`name:~/${e.nameMatch}/`))),i.nameNotMatchRe&&a.push(`name:!~/${e.nameNotMatch}/`),{optionalTotal:r,optionalPassed:s}}evaluateMetadataUncached(t,i,e){let n=i.structural;if(!n&&!i.customDetector)return S;let a=[],r=wt(t);if(n){let s=this.evaluateRequired(t,e,n,r);if(s===null)return S;a.push(...s);let{optionalTotal:m,optionalPassed:c}=this.evaluateOptional(t,e,n,r,a),h=s.length;if(m===0){if(a.length>0&&!i.customDetector)return {confidence:1,matchedCriteria:a}}else {let p=c/m;if((p>0||a.length>h)&&!i.customDetector)return {confidence:p,matchedCriteria:a}}}if(i.customDetector){let s=tt.get(i.customDetector);if(s)try{let m=s(t);if(m.match){let c=m.matchedCriteria??[`custom:${i.customDetector}`],h=[...a,...c],p=a.filter(y=>y.startsWith("entityType:")||y.startsWith("modifiers:")||y==="no-forbidden-modifiers").length;return {confidence:a.length>p?(m.confidence+a.length/Math.max(e.totalCriteriaCount,1))/2:m.confidence,matchedCriteria:h}}return S}catch(m){return I$1.w("STRUCTURAL_DETECTOR","custom_detector_error",{detector:i.customDetector,error:String(m)}),S}return S}return a.length>0&&!n?{confidence:.5,matchedCriteria:a}:{confidence:a.length>0?a.length/Math.max(e.totalCriteriaCount,1):0,matchedCriteria:a}}evaluateRelationshipCriteria(t,i,e){let n=[];for(let a of e){let r=i.filter(m=>{let c=m.type===a.type,h=a.direction==="outgoing"?m.fromId===t.id:m.toId===t.id;return c&&h}),s=r.length;if(a.minCount!=null&&s<a.minCount)return {passed:false,matchedCriteria:n};if(a.maxCount!=null&&s>a.maxCount)return {passed:false,matchedCriteria:n};if(a.crossFileRatio){let m=i.filter(c=>a.direction==="outgoing"?c.fromId===t.id:c.toId===t.id).length;if(m>0){let c=r.length/m;if(a.crossFileRatio.min!=null&&c<a.crossFileRatio.min)return {passed:false,matchedCriteria:n};if(a.crossFileRatio.max!=null&&c>a.crossFileRatio.max)return {passed:false,matchedCriteria:n}}}n.push(`rel:${a.direction}:${a.type}=${s}`);}return {passed:true,matchedCriteria:n}}};function $t(o){let t=0;return o.entityTypes&&t++,o.requiredModifiers&&t++,o.forbiddenModifiers&&t++,o.returnTypeMatch&&t++,o.returnTypeNotMatch&&t++,o.minParams!=null&&t++,o.maxParams!=null&&t++,o.paramTypeRequired&&t++,o.paramTypeAbsent&&t++,o.minCyclomatic!=null&&t++,o.maxCyclomatic!=null&&t++,o.minCognitive!=null&&t++,o.minNesting!=null&&t++,o.minLOC!=null&&t++,o.maxLOC!=null&&t++,o.hasLoops!=null&&t++,o.hasExceptions!=null&&t++,o.hasAwaits!=null&&t++,o.minBranches!=null&&t++,o.minCallCount!=null&&t++,o.callsInclude&&(t+=o.callsInclude.length),o.callsExclude&&(t+=o.callsExclude.length),o.decoratorMatch&&(t+=o.decoratorMatch.length),o.hasNoInheritance&&t++,o.filePathNotMatch&&t++,o.nameMatch&&t++,o.nameNotMatch&&t++,o.relationships&&(t+=o.relationships.length),t}var I={critical:4,high:3,medium:2,low:1,info:0},Nt={typescript:"./detectors/typescript.js",javascript:"./detectors/typescript.js",python:"./detectors/python.js",csharp:"./detectors/csharp.js",java:"./detectors/java.js",kotlin:"./detectors/java.js",go:"./detectors/go.js"},A=class{constructor(t){this.embeddingGen=t;}registry=new N;exemplarStore=new $;structuralDetector=new O;semanticValidator=null;initialized=false;loadedDetectorModules=new Set;async initialize(){if(this.initialized)return;let t=import.meta.dirname;await this.registry.load(join(t,"rules")),await this.exemplarStore.load(join(t,"exemplars")),B(k),this.semanticValidator=new D(this.exemplarStore,this.embeddingGen),this.initialized=true,I$1.i("PATTERN_ENGINE","initialized",{patterns:this.registry.size,exemplars:this.exemplarStore.size});}async ensureDetectorsForLanguage(t){if(!t)return;let i=Nt[t.toLowerCase()];if(!(!i||this.loadedDetectorModules.has(i)))try{let e=await import(i);B(e),this.loadedDetectorModules.add(i),I$1.i("PATTERN_ENGINE","loaded_detectors",{language:t,module:i});}catch{}}async scan(t,i){await this.initialize();let e=Date.now(),{filePath:n,language:a,category:r="all",tags:s,minConfidence:m=.5,severity:c="all",offset:h=0,limit:p=50,entityLimit:u=1e4,suppressPatterns:g}=t,y=u,C;if(n?(/[\\/]$/.test(n)||!/\.\w+$/.test(n.split(/[\\/]/).pop()??""))&&typeof i.searchEntitiesInDirectory=="function"?C=await i.searchEntitiesInDirectory(n):C=await i.findEntities({filters:{filePath:n},limit:y}):C=await i.findEntities({limit:y}),C.length===0)return this.emptyResult();let R=a??this.detectLanguage(C);await this.ensureDetectorsForLanguage(R);let b=this.registry.getPatterns({language:R,category:r,tags:s,enabledOnly:true});if(g?.length){let d=new Set(g);b=b.filter(z=>!d.has(z.id));}if(b.length===0)return this.emptyResult(C.length);let L=await this.structuralDetector.detect(C,b,i),rt=new Map(b.map(d=>[d.id,d])),J=this.semanticValidator?await this.semanticValidator.validate(L,rt):L.map(d=>({patternId:d.pattern.id,pattern:d.pattern,entityId:d.entity.id,entityName:d.entity.name,entityType:d.entity.type,filePath:d.entity.filePath,line:d.entity.location?.start?.line??0,structuralConfidence:d.confidence,semanticSimilarity:1,combinedScore:d.confidence,matchedCriteria:d.matchedCriteria})),P=J.filter(d=>d.combinedScore>=m);c!=="all"&&(P=P.filter(d=>d.pattern.severity===c)),P.sort((d,z)=>z.combinedScore-d.combinedScore);let M=P.filter(d=>d.pattern.category==="anti-pattern"),j=P.filter(d=>d.pattern.category==="best-pattern"),T=P.filter(d=>d.pattern.category==="code-smell"),_=P.filter(d=>d.pattern.category==="optimization"),st=this.computeHealthScore(M,j,T),ot=this.computeTopIssues([...M,...T,..._]),v=d=>d.slice(h,h+p),ct={antiPatterns:v(M),bestPatterns:v(j),codeSmells:v(T),optimizations:v(_),summary:{totalEntitiesScanned:C.length,antiPatternCount:M.length,bestPatternCount:j.length,codeSmellCount:T.length,optimizationCount:_.length,topIssues:ot,healthScore:st}};return I$1.i("PATTERN_ENGINE","scan_complete",{entities:C.length,patterns:b.length,candidates:L.length,confirmed:J.length,filtered:P.length,durationMs:Date.now()-e}),ct}async checkEntity(t,i,e="all"){await this.initialize();let n=await i.getEntity(t);if(!n)return [];let a=n.language??n.metadata?.language;await this.ensureDetectorsForLanguage(a);let r=this.registry.getPatterns({language:a,category:e,enabledOnly:true}),s=await this.structuralDetector.detect([n],r,i),m=new Map(r.map(c=>[c.id,c]));return this.semanticValidator?await this.semanticValidator.validate(s,m):s.map(c=>({patternId:c.pattern.id,pattern:c.pattern,entityId:c.entity.id,entityName:c.entity.name,entityType:c.entity.type,filePath:c.entity.filePath,line:c.entity.location?.start?.line??0,structuralConfidence:c.confidence,semanticSimilarity:1,combinedScore:c.confidence,matchedCriteria:c.matchedCriteria}))}detectLanguage(t){let i=new Map;for(let e of t){let n=e.language??e.metadata?.language;n&&i.set(n,(i.get(n)??0)+1);}if(i.size!==0)return [...i.entries()].sort((e,n)=>n[1]-e[1])[0][0]}computeHealthScore(t,i,e){let n=0;for(let s of t)n+=I[s.pattern.severity]??1;for(let s of e)n+=(I[s.pattern.severity]??1)*.5;let a=i.length,r=Math.round(100*(a+1)/(a+n+1));return Math.max(0,Math.min(100,r))}computeTopIssues(t){let i=new Map;for(let e of t){let n=i.get(e.patternId);n?n.count++:i.set(e.patternId,{count:1,severity:e.pattern.severity});}return [...i.entries()].map(([e,n])=>({patternId:e,...n})).sort((e,n)=>{let a=(I[n.severity]??0)-(I[e.severity]??0);return a!==0?a:n.count-e.count}).slice(0,10)}emptyResult(t=0){return {antiPatterns:[],bestPatterns:[],codeSmells:[],optimizations:[],summary:{totalEntitiesScanned:t,antiPatternCount:0,bestPatternCount:0,codeSmellCount:0,optimizationCount:0,topIssues:[],healthScore:100}}}};var x=class o{static format(t,i="summary"){return i==="json"?JSON.stringify(t,null,2):i==="detailed"?o.formatDetailed(t):o.formatSummary(t)}static formatSummary(t){let{summary:i}=t,e=[];if(e.push("## Pattern Scan Summary"),e.push(`- Entities scanned: ${i.totalEntitiesScanned}`),e.push(`- Health score: ${i.healthScore}/100`),e.push(""),i.antiPatternCount>0){e.push(`### Anti-patterns: ${i.antiPatternCount}`);for(let n of t.antiPatterns.slice(0,10))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line}) \u2014 score: ${n.combinedScore.toFixed(2)}`);e.push("");}if(i.codeSmellCount>0){e.push(`### Code smells: ${i.codeSmellCount}`);for(let n of t.codeSmells.slice(0,10))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line}) \u2014 score: ${n.combinedScore.toFixed(2)}`);e.push("");}if(i.optimizationCount>0){e.push(`### Optimizations: ${i.optimizationCount}`);for(let n of t.optimizations.slice(0,10)){let a=n.pattern.bigO?` [${n.pattern.bigO.before} \u2192 ${n.pattern.bigO.after}]`:"",r=n.pattern.benchmark?` (${n.pattern.benchmark})`:"";e.push(` - **${n.pattern.name}**${a}${r} in \`${n.entityName}\` (${n.filePath}:${n.line})`);}e.push("");}if(i.bestPatternCount>0){e.push(`### Best patterns: ${i.bestPatternCount}`);for(let n of t.bestPatterns.slice(0,5))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line})`);e.push("");}if(i.topIssues.length>0){e.push("### Top Issues");for(let n of i.topIssues.slice(0,5))e.push(` - \`${n.patternId}\` \u2014 ${n.count} occurrence(s), severity: ${n.severity}`);}return e.join(`
2
+ `)}static formatDetailed(t){let i=[...t.antiPatterns,...t.codeSmells,...t.optimizations,...t.bestPatterns],e=[];e.push(`## Pattern Scan \u2014 Detailed (${i.length} matches, health: ${t.summary.healthScore}/100)`),e.push("");for(let n of i){let a=n.pattern.category==="anti-pattern"?"\u{1F534}":n.pattern.category==="code-smell"?"\u{1F7E1}":n.pattern.category==="optimization"?"\u26A1":"\u{1F7E2}";e.push(`### ${a} ${n.pattern.name} [\`${n.patternId}\`]`),e.push(`- **Category**: ${n.pattern.category} | **Severity**: ${n.pattern.severity}`),e.push(`- **Entity**: \`${n.entityName}\` (${n.entityType}) at ${n.filePath}:${n.line}`),e.push(`- **Score**: combined=${n.combinedScore.toFixed(2)}, structural=${n.structuralConfidence.toFixed(2)}, semantic=${n.semanticSimilarity.toFixed(2)}`),e.push(`- **Description**: ${n.pattern.description}`),e.push(`- **Suggestion**: ${n.pattern.suggestion}`),n.pattern.bigO&&e.push(`- **Complexity**: ${n.pattern.bigO.before} \u2192 ${n.pattern.bigO.after}`),n.pattern.benchmark&&e.push(`- **Benchmark**: ${n.pattern.benchmark}`),n.closestExemplar&&e.push(`- **Closest exemplar**: ${n.closestExemplar.id} (similarity: ${n.closestExemplar.similarity.toFixed(2)}) \u2014 ${n.closestExemplar.description}`),n.matchedCriteria.length>0&&e.push(`- **Matched criteria**: ${n.matchedCriteria.join(", ")}`),e.push("");}return e.join(`
3
+ `)}static toJSON(t){return {summary:t.summary,antiPatterns:t.antiPatterns.map(o.matchToJSON),bestPatterns:t.bestPatterns.map(o.matchToJSON),codeSmells:t.codeSmells.map(o.matchToJSON),optimizations:t.optimizations.map(o.matchToJSON)}}static matchToJSON(t){return {patternId:t.patternId,category:t.pattern.category,severity:t.pattern.severity,name:t.pattern.name,description:t.pattern.description,suggestion:t.pattern.suggestion,bigO:t.pattern.bigO,benchmark:t.pattern.benchmark,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType,filePath:t.filePath,line:t.line,combinedScore:Number(t.combinedScore.toFixed(3)),structuralConfidence:Number(t.structuralConfidence.toFixed(3)),semanticSimilarity:Number(t.semanticSimilarity.toFixed(3)),matchedCriteria:t.matchedCriteria,closestExemplar:t.closestExemplar}}};R();var q=null;function at(o){return q||(q=new A(o)),q}var nt=class extends d$1{parseArgs(t){return a.parse(t)}async execute(t){try{let i=await this.ensureGraphStorageForProject(t.projectPath),e;try{let p=await this.context.getSemanticAgent();e=p.embeddingGenerator??p.getEmbeddingGenerator?.();}catch{}let n=at(e),a={projectPath:this.resolveProjectPath(t),filePath:t.filePath,language:t.language,category:t.category,tags:t.tags,minConfidence:t.minConfidence,severity:t.severity==="all"?"all":t.severity,offset:t.offset,limit:t.limit,entityLimit:t.entityLimit,suppressPatterns:t.suppressPatterns},r=await n.scan(a,i),s=[];[...r.antiPatterns,...r.bestPatterns,...r.codeSmells,...r.optimizations].some(p=>p.pattern.tags.some(u=>/security|injection|xss|auth/i.test(u)))&&s.push("taint_analysis() \u2014 deep security analysis of detected vulnerable patterns"),s.push("graph_metrics({metric:'pagerank'}) \u2014 rank affected entities by importance");let h;if(t.format==="json"){let p=x.toJSON(r);p.nextSteps=s,h=JSON.stringify(p,null,2);}else t.format==="detailed"?(h=x.format(r,"detailed"),h+=`
4
+
5
+ ---
6
+ Next steps:
7
+ ${s.map(p=>`- ${p}`).join(`
8
+ `)}`):(h=x.format(r,"summary"),h+=`
9
+
10
+ ---
11
+ Next steps:
12
+ ${s.map(p=>`- ${p}`).join(`
13
+ `)}`);return {content:[{type:"text",text:h}]}}catch(i){let e=a$1(i);return I$1.e("DETECT_PATTERNS","scan_error",{error:e.message}),{content:[{type:"text",text:`Error: ${e.message}`}]}}}},it=class extends d$1{parseArgs(t){return b.parse(t)}async execute(t){try{let i=await this.ensureGraphStorageForProject(t.projectPath),e;try{let s=await this.context.getSemanticAgent();e=s.embeddingGenerator??s.getEmbeddingGenerator?.();}catch{}let a=await at(e).checkEntity(t.entityId,i,t.category);if(a.length===0)return {content:[{type:"text",text:`No pattern matches found for entity ${t.entityId}`}]};let r={entityId:t.entityId,matchCount:a.length,matches:a.map(s=>({patternId:s.patternId,category:s.pattern.category,severity:s.pattern.severity,name:s.pattern.name,description:s.pattern.description,suggestion:s.pattern.suggestion,bigO:s.pattern.bigO,benchmark:s.pattern.benchmark,combinedScore:Number(s.combinedScore.toFixed(3)),structuralConfidence:Number(s.structuralConfidence.toFixed(3)),semanticSimilarity:Number(s.semanticSimilarity.toFixed(3)),matchedCriteria:s.matchedCriteria,closestExemplar:s.closestExemplar}))};return {content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(i){let e=a$1(i);return I$1.e("CHECK_ENTITY_PATTERNS","check_error",{error:e.message}),{content:[{type:"text",text:`Error: ${e.message}`}]}}}};export{it as CheckEntityPatternsToolHandler,nt as DetectPatternsToolHandler};