mcp-adr-analysis-server 2.0.21 → 2.1.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 (263) hide show
  1. package/README.md +94 -839
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/src/config/ai-config.d.ts.map +1 -1
  4. package/dist/src/config/ai-config.js +9 -9
  5. package/dist/src/config/ai-config.js.map +1 -1
  6. package/dist/src/index.d.ts +15 -0
  7. package/dist/src/index.d.ts.map +1 -1
  8. package/dist/src/index.js +1594 -837
  9. package/dist/src/index.js.map +1 -1
  10. package/dist/src/prompts/analysis-prompts.d.ts +4 -1
  11. package/dist/src/prompts/analysis-prompts.d.ts.map +1 -1
  12. package/dist/src/prompts/analysis-prompts.js +61 -30
  13. package/dist/src/prompts/analysis-prompts.js.map +1 -1
  14. package/dist/src/prompts/index.d.ts +17 -1
  15. package/dist/src/prompts/index.d.ts.map +1 -1
  16. package/dist/src/prompts/index.js +325 -1
  17. package/dist/src/prompts/index.js.map +1 -1
  18. package/dist/src/prompts/rule-generation-prompts.d.ts +5 -1
  19. package/dist/src/prompts/rule-generation-prompts.d.ts.map +1 -1
  20. package/dist/src/prompts/rule-generation-prompts.js +5 -1
  21. package/dist/src/prompts/rule-generation-prompts.js.map +1 -1
  22. package/dist/src/prompts/security-prompts.d.ts +6 -1
  23. package/dist/src/prompts/security-prompts.d.ts.map +1 -1
  24. package/dist/src/prompts/security-prompts.js +6 -1
  25. package/dist/src/prompts/security-prompts.js.map +1 -1
  26. package/dist/src/prompts/todo-prompts.d.ts +49 -0
  27. package/dist/src/prompts/todo-prompts.d.ts.map +1 -0
  28. package/dist/src/prompts/todo-prompts.js +824 -0
  29. package/dist/src/prompts/todo-prompts.js.map +1 -0
  30. package/dist/src/resources/index.d.ts.map +1 -1
  31. package/dist/src/resources/index.js +9 -7
  32. package/dist/src/resources/index.js.map +1 -1
  33. package/dist/src/tools/adr-bootstrap-validation-tool.d.ts +47 -0
  34. package/dist/src/tools/adr-bootstrap-validation-tool.d.ts.map +1 -0
  35. package/dist/src/tools/adr-bootstrap-validation-tool.js +979 -0
  36. package/dist/src/tools/adr-bootstrap-validation-tool.js.map +1 -0
  37. package/dist/src/tools/adr-suggestion-tool.d.ts +1 -0
  38. package/dist/src/tools/adr-suggestion-tool.d.ts.map +1 -1
  39. package/dist/src/tools/adr-suggestion-tool.js +330 -32
  40. package/dist/src/tools/adr-suggestion-tool.js.map +1 -1
  41. package/dist/src/tools/content-masking-tool.d.ts +5 -0
  42. package/dist/src/tools/content-masking-tool.d.ts.map +1 -1
  43. package/dist/src/tools/content-masking-tool.js +631 -28
  44. package/dist/src/tools/content-masking-tool.js.map +1 -1
  45. package/dist/src/tools/deployment-readiness-tool.d.ts +8 -5
  46. package/dist/src/tools/deployment-readiness-tool.d.ts.map +1 -1
  47. package/dist/src/tools/deployment-readiness-tool.js +1017 -93
  48. package/dist/src/tools/deployment-readiness-tool.js.map +1 -1
  49. package/dist/src/tools/environment-analysis-tool.d.ts +4 -0
  50. package/dist/src/tools/environment-analysis-tool.d.ts.map +1 -1
  51. package/dist/src/tools/environment-analysis-tool.js +568 -24
  52. package/dist/src/tools/environment-analysis-tool.js.map +1 -1
  53. package/dist/src/tools/interactive-adr-planning-tool.d.ts.map +1 -1
  54. package/dist/src/tools/interactive-adr-planning-tool.js +270 -108
  55. package/dist/src/tools/interactive-adr-planning-tool.js.map +1 -1
  56. package/dist/src/tools/mcp-planning-tool.d.ts.map +1 -1
  57. package/dist/src/tools/mcp-planning-tool.js +316 -183
  58. package/dist/src/tools/mcp-planning-tool.js.map +1 -1
  59. package/dist/src/tools/memory-loading-tool.d.ts +60 -0
  60. package/dist/src/tools/memory-loading-tool.d.ts.map +1 -0
  61. package/dist/src/tools/memory-loading-tool.js +457 -0
  62. package/dist/src/tools/memory-loading-tool.js.map +1 -0
  63. package/dist/src/tools/research-integration-tool.d.ts +4 -1
  64. package/dist/src/tools/research-integration-tool.d.ts.map +1 -1
  65. package/dist/src/tools/research-integration-tool.js +5 -1
  66. package/dist/src/tools/research-integration-tool.js.map +1 -1
  67. package/dist/src/tools/review-existing-adrs-tool.d.ts +19 -0
  68. package/dist/src/tools/review-existing-adrs-tool.d.ts.map +1 -0
  69. package/dist/src/tools/review-existing-adrs-tool.js +1204 -0
  70. package/dist/src/tools/review-existing-adrs-tool.js.map +1 -0
  71. package/dist/src/tools/rule-generation-tool.d.ts +2 -0
  72. package/dist/src/tools/rule-generation-tool.d.ts.map +1 -1
  73. package/dist/src/tools/rule-generation-tool.js +274 -33
  74. package/dist/src/tools/rule-generation-tool.js.map +1 -1
  75. package/dist/src/tools/smart-git-push-tool-v2.d.ts +4 -0
  76. package/dist/src/tools/smart-git-push-tool-v2.d.ts.map +1 -1
  77. package/dist/src/tools/smart-git-push-tool-v2.js +423 -229
  78. package/dist/src/tools/smart-git-push-tool-v2.js.map +1 -1
  79. package/dist/src/tools/smart-git-push-tool.d.ts +3 -0
  80. package/dist/src/tools/smart-git-push-tool.d.ts.map +1 -1
  81. package/dist/src/tools/smart-git-push-tool.js +241 -235
  82. package/dist/src/tools/smart-git-push-tool.js.map +1 -1
  83. package/dist/src/tools/tool-chain-orchestrator.d.ts +2 -2
  84. package/dist/src/tools/tool-chain-orchestrator.d.ts.map +1 -1
  85. package/dist/src/tools/tool-chain-orchestrator.js +152 -93
  86. package/dist/src/tools/tool-chain-orchestrator.js.map +1 -1
  87. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts +22 -13
  88. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts.map +1 -1
  89. package/dist/src/tools/troubleshoot-guided-workflow-tool.js +660 -28
  90. package/dist/src/tools/troubleshoot-guided-workflow-tool.js.map +1 -1
  91. package/dist/src/types/ape-framework.d.ts +93 -0
  92. package/dist/src/types/ape-framework.d.ts.map +1 -1
  93. package/dist/src/types/ape-framework.js +10 -10
  94. package/dist/src/types/ape-framework.js.map +1 -1
  95. package/dist/src/types/enhanced-errors.d.ts +173 -0
  96. package/dist/src/types/enhanced-errors.d.ts.map +1 -0
  97. package/dist/src/types/enhanced-errors.js +668 -0
  98. package/dist/src/types/enhanced-errors.js.map +1 -0
  99. package/dist/src/types/index.d.ts +129 -3
  100. package/dist/src/types/index.d.ts.map +1 -1
  101. package/dist/src/types/index.js +15 -0
  102. package/dist/src/types/index.js.map +1 -1
  103. package/dist/src/types/knowledge-generation.d.ts +78 -0
  104. package/dist/src/types/knowledge-generation.d.ts.map +1 -1
  105. package/dist/src/types/knowledge-generation.js +10 -6
  106. package/dist/src/types/knowledge-generation.js.map +1 -1
  107. package/dist/src/types/knowledge-graph-schemas.d.ts +92 -0
  108. package/dist/src/types/knowledge-graph-schemas.d.ts.map +1 -1
  109. package/dist/src/types/knowledge-graph-schemas.js +45 -17
  110. package/dist/src/types/knowledge-graph-schemas.js.map +1 -1
  111. package/dist/src/types/memory-entities.d.ts +7209 -0
  112. package/dist/src/types/memory-entities.d.ts.map +1 -0
  113. package/dist/src/types/memory-entities.js +395 -0
  114. package/dist/src/types/memory-entities.js.map +1 -0
  115. package/dist/src/types/reflexion-framework.d.ts +44 -0
  116. package/dist/src/types/reflexion-framework.d.ts.map +1 -1
  117. package/dist/src/types/reflexion-framework.js +7 -7
  118. package/dist/src/types/reflexion-framework.js.map +1 -1
  119. package/dist/src/types/todo-json-schemas.d.ts +7 -653
  120. package/dist/src/types/todo-json-schemas.d.ts.map +1 -1
  121. package/dist/src/types/todo-json-schemas.js +6 -110
  122. package/dist/src/types/todo-json-schemas.js.map +1 -1
  123. package/dist/src/types/tool-arguments.d.ts +224 -0
  124. package/dist/src/types/tool-arguments.d.ts.map +1 -0
  125. package/dist/src/types/tool-arguments.js +6 -0
  126. package/dist/src/types/tool-arguments.js.map +1 -0
  127. package/dist/src/utils/actual-file-operations.d.ts.map +1 -1
  128. package/dist/src/utils/actual-file-operations.js +25 -9
  129. package/dist/src/utils/actual-file-operations.js.map +1 -1
  130. package/dist/src/utils/adr-discovery.d.ts +33 -1
  131. package/dist/src/utils/adr-discovery.d.ts.map +1 -1
  132. package/dist/src/utils/adr-discovery.js +14 -9
  133. package/dist/src/utils/adr-discovery.js.map +1 -1
  134. package/dist/src/utils/adr-suggestions.d.ts +72 -0
  135. package/dist/src/utils/adr-suggestions.d.ts.map +1 -1
  136. package/dist/src/utils/adr-suggestions.js +6 -0
  137. package/dist/src/utils/adr-suggestions.js.map +1 -1
  138. package/dist/src/utils/cache.d.ts.map +1 -1
  139. package/dist/src/utils/cache.js +22 -19
  140. package/dist/src/utils/cache.js.map +1 -1
  141. package/dist/src/utils/chain-of-thought-template.d.ts +13 -1
  142. package/dist/src/utils/chain-of-thought-template.d.ts.map +1 -1
  143. package/dist/src/utils/chain-of-thought-template.js +31 -22
  144. package/dist/src/utils/chain-of-thought-template.js.map +1 -1
  145. package/dist/src/utils/config.d.ts.map +1 -1
  146. package/dist/src/utils/config.js +1 -0
  147. package/dist/src/utils/config.js.map +1 -1
  148. package/dist/src/utils/directory-compat.js +1 -1
  149. package/dist/src/utils/directory-compat.js.map +1 -1
  150. package/dist/src/utils/enhanced-logging.d.ts +195 -0
  151. package/dist/src/utils/enhanced-logging.d.ts.map +1 -0
  152. package/dist/src/utils/enhanced-logging.js +449 -0
  153. package/dist/src/utils/enhanced-logging.js.map +1 -0
  154. package/dist/src/utils/file-system.d.ts +182 -34
  155. package/dist/src/utils/file-system.d.ts.map +1 -1
  156. package/dist/src/utils/file-system.js +648 -774
  157. package/dist/src/utils/file-system.js.map +1 -1
  158. package/dist/src/utils/gitleaks-detector.d.ts +50 -0
  159. package/dist/src/utils/gitleaks-detector.d.ts.map +1 -0
  160. package/dist/src/utils/gitleaks-detector.js +334 -0
  161. package/dist/src/utils/gitleaks-detector.js.map +1 -0
  162. package/dist/src/utils/interactive-approval.d.ts +1 -1
  163. package/dist/src/utils/interactive-approval.d.ts.map +1 -1
  164. package/dist/src/utils/interactive-approval.js +22 -17
  165. package/dist/src/utils/interactive-approval.js.map +1 -1
  166. package/dist/src/utils/json-safe.d.ts.map +1 -1
  167. package/dist/src/utils/json-safe.js +9 -6
  168. package/dist/src/utils/json-safe.js.map +1 -1
  169. package/dist/src/utils/knowledge-graph-manager.d.ts +37 -1
  170. package/dist/src/utils/knowledge-graph-manager.d.ts.map +1 -1
  171. package/dist/src/utils/knowledge-graph-manager.js +315 -70
  172. package/dist/src/utils/knowledge-graph-manager.js.map +1 -1
  173. package/dist/src/utils/location-filter.d.ts +35 -10
  174. package/dist/src/utils/location-filter.d.ts.map +1 -1
  175. package/dist/src/utils/location-filter.js +360 -94
  176. package/dist/src/utils/location-filter.js.map +1 -1
  177. package/dist/src/utils/mcp-response-validator.d.ts.map +1 -1
  178. package/dist/src/utils/mcp-response-validator.js +34 -19
  179. package/dist/src/utils/mcp-response-validator.js.map +1 -1
  180. package/dist/src/utils/memory-entity-manager.d.ts +134 -0
  181. package/dist/src/utils/memory-entity-manager.d.ts.map +1 -0
  182. package/dist/src/utils/memory-entity-manager.js +851 -0
  183. package/dist/src/utils/memory-entity-manager.js.map +1 -0
  184. package/dist/src/utils/memory-health-scoring.d.ts +125 -0
  185. package/dist/src/utils/memory-health-scoring.d.ts.map +1 -0
  186. package/dist/src/utils/memory-health-scoring.js +277 -0
  187. package/dist/src/utils/memory-health-scoring.js.map +1 -0
  188. package/dist/src/utils/memory-migration-manager.d.ts +93 -0
  189. package/dist/src/utils/memory-migration-manager.d.ts.map +1 -0
  190. package/dist/src/utils/memory-migration-manager.js +842 -0
  191. package/dist/src/utils/memory-migration-manager.js.map +1 -0
  192. package/dist/src/utils/memory-relationship-mapper.d.ts +87 -0
  193. package/dist/src/utils/memory-relationship-mapper.d.ts.map +1 -0
  194. package/dist/src/utils/memory-relationship-mapper.js +482 -0
  195. package/dist/src/utils/memory-relationship-mapper.js.map +1 -0
  196. package/dist/src/utils/memory-rollback-manager.d.ts +105 -0
  197. package/dist/src/utils/memory-rollback-manager.d.ts.map +1 -0
  198. package/dist/src/utils/memory-rollback-manager.js +575 -0
  199. package/dist/src/utils/memory-rollback-manager.js.map +1 -0
  200. package/dist/src/utils/memory-transformation.d.ts +59 -0
  201. package/dist/src/utils/memory-transformation.d.ts.map +1 -0
  202. package/dist/src/utils/memory-transformation.js +742 -0
  203. package/dist/src/utils/memory-transformation.js.map +1 -0
  204. package/dist/src/utils/output-masking.d.ts +12 -0
  205. package/dist/src/utils/output-masking.d.ts.map +1 -1
  206. package/dist/src/utils/output-masking.js +5 -0
  207. package/dist/src/utils/output-masking.js.map +1 -1
  208. package/dist/src/utils/prompt-execution.d.ts.map +1 -1
  209. package/dist/src/utils/prompt-execution.js +72 -51
  210. package/dist/src/utils/prompt-execution.js.map +1 -1
  211. package/dist/src/utils/release-readiness-detector.d.ts.map +1 -1
  212. package/dist/src/utils/release-readiness-detector.js +43 -42
  213. package/dist/src/utils/release-readiness-detector.js.map +1 -1
  214. package/dist/src/utils/research-integration.d.ts.map +1 -1
  215. package/dist/src/utils/research-integration.js +73 -44
  216. package/dist/src/utils/research-integration.js.map +1 -1
  217. package/dist/src/utils/research-questions.d.ts.map +1 -1
  218. package/dist/src/utils/research-questions.js +40 -14
  219. package/dist/src/utils/research-questions.js.map +1 -1
  220. package/dist/src/utils/ripgrep-wrapper.d.ts +84 -0
  221. package/dist/src/utils/ripgrep-wrapper.d.ts.map +1 -0
  222. package/dist/src/utils/ripgrep-wrapper.js +255 -0
  223. package/dist/src/utils/ripgrep-wrapper.js.map +1 -0
  224. package/dist/src/utils/rule-generation.d.ts.map +1 -1
  225. package/dist/src/utils/rule-generation.js +26 -15
  226. package/dist/src/utils/rule-generation.js.map +1 -1
  227. package/dist/src/utils/todo-file-watcher.d.ts +11 -23
  228. package/dist/src/utils/todo-file-watcher.d.ts.map +1 -1
  229. package/dist/src/utils/todo-file-watcher.js +18 -156
  230. package/dist/src/utils/todo-file-watcher.js.map +1 -1
  231. package/dist/src/utils/tree-sitter-analyzer.d.ts +185 -0
  232. package/dist/src/utils/tree-sitter-analyzer.d.ts.map +1 -0
  233. package/dist/src/utils/tree-sitter-analyzer.js +885 -0
  234. package/dist/src/utils/tree-sitter-analyzer.js.map +1 -0
  235. package/package.json +51 -10
  236. package/dist/src/tools/smart-score-tool.d.ts +0 -173
  237. package/dist/src/tools/smart-score-tool.d.ts.map +0 -1
  238. package/dist/src/tools/smart-score-tool.js +0 -681
  239. package/dist/src/tools/smart-score-tool.js.map +0 -1
  240. package/dist/src/tools/todo-management-tool-v2.d.ts +0 -368
  241. package/dist/src/tools/todo-management-tool-v2.d.ts.map +0 -1
  242. package/dist/src/tools/todo-management-tool-v2.js +0 -922
  243. package/dist/src/tools/todo-management-tool-v2.js.map +0 -1
  244. package/dist/src/utils/enhanced-sensitive-detector.d.ts +0 -61
  245. package/dist/src/utils/enhanced-sensitive-detector.d.ts.map +0 -1
  246. package/dist/src/utils/enhanced-sensitive-detector.js +0 -437
  247. package/dist/src/utils/enhanced-sensitive-detector.js.map +0 -1
  248. package/dist/src/utils/project-health-scoring.d.ts +0 -177
  249. package/dist/src/utils/project-health-scoring.d.ts.map +0 -1
  250. package/dist/src/utils/project-health-scoring.js +0 -370
  251. package/dist/src/utils/project-health-scoring.js.map +0 -1
  252. package/dist/src/utils/todo-json-manager.d.ts +0 -71
  253. package/dist/src/utils/todo-json-manager.d.ts.map +0 -1
  254. package/dist/src/utils/todo-json-manager.js +0 -396
  255. package/dist/src/utils/todo-json-manager.js.map +0 -1
  256. package/dist/src/utils/todo-markdown-converter.d.ts +0 -16
  257. package/dist/src/utils/todo-markdown-converter.d.ts.map +0 -1
  258. package/dist/src/utils/todo-markdown-converter.js +0 -362
  259. package/dist/src/utils/todo-markdown-converter.js.map +0 -1
  260. package/dist/src/utils/todo-migration.d.ts +0 -47
  261. package/dist/src/utils/todo-migration.d.ts.map +0 -1
  262. package/dist/src/utils/todo-migration.js +0 -261
  263. package/dist/src/utils/todo-migration.js.map +0 -1
@@ -2,21 +2,415 @@
2
2
  * MCP Tool for content masking and sensitive information detection
3
3
  * Implements prompt-driven security analysis
4
4
  * Enhanced with Generated Knowledge Prompting (GKP) for security and privacy expertise
5
+ * Now includes memory integration for security pattern learning and institutional knowledge building
5
6
  */
6
7
  import { McpAdrError } from '../types/index.js';
8
+ import { MemoryEntityManager } from '../utils/memory-entity-manager.js';
9
+ import { EnhancedLogger } from '../utils/enhanced-logging.js';
10
+ import { TreeSitterAnalyzer } from '../utils/tree-sitter-analyzer.js';
11
+ /**
12
+ * Security Memory Manager for tracking security patterns and masking effectiveness
13
+ */
14
+ class SecurityMemoryManager {
15
+ memoryManager;
16
+ logger;
17
+ constructor() {
18
+ this.memoryManager = new MemoryEntityManager();
19
+ this.logger = new EnhancedLogger();
20
+ }
21
+ async initialize() {
22
+ await this.memoryManager.initialize();
23
+ }
24
+ /**
25
+ * Store security pattern detection results as memory entity
26
+ */
27
+ async storeSecurityPattern(contentType, detectedPatterns, maskingResults, analysisMetadata) {
28
+ try {
29
+ const securityData = {
30
+ contentType: contentType,
31
+ detectedPatterns: detectedPatterns.map(pattern => ({
32
+ patternType: pattern.type || 'unknown',
33
+ severity: pattern.severity,
34
+ description: pattern.description || 'Detected sensitive pattern',
35
+ location: pattern.context || undefined,
36
+ recommendation: `Review and mask ${pattern.type || 'unknown'} patterns`,
37
+ })),
38
+ maskingResults: {
39
+ effectiveness: maskingResults?.securityScore || 0.8,
40
+ method: maskingResults?.strategy || 'analysis-only',
41
+ preservedUtility: maskingResults?.preservedContext || 0.7,
42
+ falsePositives: 0, // Simplified - could be enhanced with actual analysis
43
+ falseNegatives: 0, // Simplified - could be enhanced with actual analysis
44
+ },
45
+ riskAssessment: {
46
+ overallRisk: calculateOverallRisk(detectedPatterns),
47
+ specificRisks: detectedPatterns.map(p => `${p.type || 'unknown'} exposure risk`),
48
+ mitigationStrategies: [
49
+ 'Implement content masking',
50
+ 'Review data handling policies',
51
+ 'Enhance detection patterns',
52
+ 'Train team on security awareness',
53
+ ],
54
+ complianceImpact: assessComplianceImpact(detectedPatterns),
55
+ },
56
+ evolutionTracking: {
57
+ patternChanges: [
58
+ {
59
+ timestamp: new Date().toISOString(),
60
+ change: `Initial detection of ${detectedPatterns.length} patterns`,
61
+ impact: `Security analysis baseline established`,
62
+ },
63
+ ],
64
+ effectivenessHistory: [
65
+ {
66
+ timestamp: new Date().toISOString(),
67
+ effectiveness: maskingResults?.securityScore || 0.8,
68
+ method: maskingResults?.strategy || 'analysis-only',
69
+ },
70
+ ],
71
+ },
72
+ };
73
+ const entity = await this.memoryManager.upsertEntity({
74
+ type: 'security_pattern',
75
+ title: `Security Pattern Analysis: ${contentType} - ${detectedPatterns.length} patterns detected`,
76
+ description: `Security analysis for ${contentType} content with ${detectedPatterns.length} sensitive patterns detected and masking effectiveness of ${Math.round((maskingResults?.securityScore || 0.8) * 100)}%`,
77
+ tags: [
78
+ 'security',
79
+ 'content-masking',
80
+ contentType.toLowerCase(),
81
+ `patterns-${detectedPatterns.length}`,
82
+ `confidence-${this.getConfidenceCategory(detectedPatterns)}`,
83
+ `security-score-${Math.floor((maskingResults?.securityScore || 0.8) * 10) * 10}`,
84
+ ...(detectedPatterns.some(p => p.severity === 'critical') ? ['critical-patterns'] : []),
85
+ ...(detectedPatterns.length > 10 ? ['high-volume'] : []),
86
+ ],
87
+ securityData,
88
+ relationships: [],
89
+ context: {
90
+ projectPhase: 'security-analysis',
91
+ technicalStack: this.extractTechnicalStack(contentType, analysisMetadata),
92
+ environmentalFactors: [contentType, analysisMetadata?.environment || 'unknown'].filter(Boolean),
93
+ stakeholders: ['security-team', 'development-team', 'compliance-team'],
94
+ },
95
+ accessPattern: {
96
+ lastAccessed: new Date().toISOString(),
97
+ accessCount: 1,
98
+ accessContext: ['security-analysis'],
99
+ },
100
+ evolution: {
101
+ origin: 'created',
102
+ transformations: [
103
+ {
104
+ timestamp: new Date().toISOString(),
105
+ type: 'security_analysis',
106
+ description: `Security pattern analysis completed for ${contentType} content`,
107
+ agent: 'content-masking-tool',
108
+ },
109
+ ],
110
+ },
111
+ validation: {
112
+ isVerified: maskingResults?.securityScore > 0.7,
113
+ verificationMethod: 'automated-security-analysis',
114
+ verificationTimestamp: new Date().toISOString(),
115
+ },
116
+ });
117
+ this.logger.info(`Security pattern stored for ${contentType}`, 'SecurityMemoryManager', {
118
+ contentType,
119
+ entityId: entity.id,
120
+ patternsDetected: detectedPatterns.length,
121
+ securityScore: maskingResults?.securityScore,
122
+ criticalPatterns: detectedPatterns.filter(p => p.severity === 'critical').length,
123
+ });
124
+ return entity.id;
125
+ }
126
+ catch (error) {
127
+ this.logger.error('Failed to store security pattern', 'SecurityMemoryManager', error);
128
+ throw error;
129
+ }
130
+ }
131
+ /**
132
+ * Track masking evolution and effectiveness over time
133
+ */
134
+ async trackMaskingEvolution(previousPatternId, currentResults) {
135
+ try {
136
+ if (!previousPatternId || !currentResults) {
137
+ return {
138
+ improvements: [],
139
+ degradations: [],
140
+ recommendations: ['No previous patterns to compare with - establishing baseline'],
141
+ };
142
+ }
143
+ // Get recent security patterns for comparison
144
+ const recentPatterns = await this.memoryManager.queryEntities({
145
+ entityTypes: ['security_pattern'],
146
+ limit: 10,
147
+ sortBy: 'lastModified',
148
+ });
149
+ if (recentPatterns.entities.length === 0) {
150
+ return {
151
+ improvements: [],
152
+ degradations: [],
153
+ recommendations: ['No historical patterns found - establishing baseline'],
154
+ };
155
+ }
156
+ const analysis = this.compareSecurityPatterns(recentPatterns.entities, currentResults);
157
+ return {
158
+ improvements: analysis.improvements,
159
+ degradations: analysis.degradations,
160
+ recommendations: analysis.recommendations,
161
+ };
162
+ }
163
+ catch (error) {
164
+ this.logger.error('Failed to track masking evolution', 'SecurityMemoryManager', error);
165
+ return {
166
+ improvements: [],
167
+ degradations: [],
168
+ recommendations: ['Evolution tracking failed - continuing with current analysis'],
169
+ };
170
+ }
171
+ }
172
+ /**
173
+ * Analyze security patterns across all stored entities
174
+ */
175
+ async analyzeInstitutionalSecurity() {
176
+ try {
177
+ const allPatterns = await this.memoryManager.queryEntities({
178
+ entityTypes: ['security_pattern'],
179
+ limit: 100,
180
+ sortBy: 'lastModified',
181
+ });
182
+ if (allPatterns.entities.length === 0) {
183
+ return {
184
+ commonPatterns: [],
185
+ emergingThreats: [],
186
+ effectivenessMetrics: { overallScore: 0, totalAnalyses: 0 },
187
+ complianceStatus: { gdpr: 'unknown', hipaa: 'unknown', pci: 'unknown' },
188
+ recommendations: [
189
+ 'No security patterns in memory - start analyzing content to build knowledge',
190
+ ],
191
+ };
192
+ }
193
+ return this.performInstitutionalAnalysis(allPatterns.entities);
194
+ }
195
+ catch (error) {
196
+ this.logger.error('Failed to analyze institutional security', 'SecurityMemoryManager', error);
197
+ return {
198
+ commonPatterns: [],
199
+ emergingThreats: [],
200
+ effectivenessMetrics: { overallScore: 0, totalAnalyses: 0 },
201
+ complianceStatus: { gdpr: 'unknown', hipaa: 'unknown', pci: 'unknown' },
202
+ recommendations: ['Security analysis failed - review system configuration'],
203
+ };
204
+ }
205
+ }
206
+ // Private helper methods
207
+ getConfidenceCategory(detectedPatterns) {
208
+ const avgConfidence = detectedPatterns.reduce((sum, p) => sum + (p.confidence || 0.5), 0) / detectedPatterns.length;
209
+ if (avgConfidence >= 0.9)
210
+ return 'high';
211
+ if (avgConfidence >= 0.7)
212
+ return 'medium';
213
+ return 'low';
214
+ }
215
+ extractTechnicalStack(contentType, metadata) {
216
+ const stack = [contentType];
217
+ if (metadata?.language)
218
+ stack.push(metadata.language);
219
+ if (metadata?.framework)
220
+ stack.push(metadata.framework);
221
+ if (metadata?.environment)
222
+ stack.push(metadata.environment);
223
+ return stack;
224
+ }
225
+ compareSecurityPatterns(historicalPatterns, currentResults) {
226
+ // Simplified comparison - could be enhanced with more sophisticated analysis
227
+ const improvements = [];
228
+ const degradations = [];
229
+ const recommendations = [];
230
+ if (historicalPatterns.length > 0) {
231
+ const lastPattern = historicalPatterns[0];
232
+ const lastScore = lastPattern.securityData?.maskingEffectiveness?.securityScore || 0;
233
+ const currentScore = currentResults?.securityScore || 0;
234
+ if (currentScore > lastScore) {
235
+ improvements.push(`Security score improved from ${(lastScore * 100).toFixed(1)}% to ${(currentScore * 100).toFixed(1)}%`);
236
+ }
237
+ else if (currentScore < lastScore) {
238
+ degradations.push(`Security score decreased from ${(lastScore * 100).toFixed(1)}% to ${(currentScore * 100).toFixed(1)}%`);
239
+ }
240
+ recommendations.push('Continue monitoring security patterns for trends');
241
+ }
242
+ return { improvements, degradations, recommendations };
243
+ }
244
+ performInstitutionalAnalysis(patterns) {
245
+ // Simplified institutional analysis
246
+ const totalPatterns = patterns.length;
247
+ const avgScore = patterns.reduce((sum, p) => sum + (p.securityData?.maskingEffectiveness?.securityScore || 0), 0) / totalPatterns;
248
+ return {
249
+ commonPatterns: this.extractCommonPatterns(patterns),
250
+ emergingThreats: this.identifyEmergingThreats(patterns),
251
+ effectivenessMetrics: {
252
+ overallScore: avgScore,
253
+ totalAnalyses: totalPatterns,
254
+ averageConfidence: 0.8, // Simplified
255
+ },
256
+ complianceStatus: {
257
+ gdpr: avgScore > 0.8 ? 'likely-compliant' : 'needs-review',
258
+ hipaa: avgScore > 0.9 ? 'likely-compliant' : 'needs-review',
259
+ pci: avgScore > 0.95 ? 'likely-compliant' : 'needs-review',
260
+ },
261
+ recommendations: [
262
+ 'Continue building security knowledge through regular content analysis',
263
+ 'Monitor emerging threat patterns',
264
+ 'Maintain high masking effectiveness standards',
265
+ ],
266
+ };
267
+ }
268
+ extractCommonPatterns(patterns) {
269
+ // Extract most frequently occurring pattern types
270
+ const patternCounts = {};
271
+ patterns.forEach((p) => {
272
+ const detectedPatterns = p.securityData?.patternAnalysis?.detectedPatterns || [];
273
+ detectedPatterns.forEach((dp) => {
274
+ patternCounts[dp.type] = (patternCounts[dp.type] || 0) + 1;
275
+ });
276
+ });
277
+ return Object.entries(patternCounts)
278
+ .sort(([, a], [, b]) => b - a)
279
+ .slice(0, 5)
280
+ .map(([type, count]) => ({ type, frequency: count }));
281
+ }
282
+ identifyEmergingThreats(patterns) {
283
+ // Identify patterns that are appearing more frequently in recent analyses
284
+ const recentPatterns = patterns.slice(0, Math.min(10, patterns.length));
285
+ const threats = [];
286
+ // This is a simplified implementation
287
+ if (recentPatterns.length > 0) {
288
+ threats.push({
289
+ type: 'increasing-pattern-complexity',
290
+ description: 'Pattern detection complexity may be increasing',
291
+ trend: 'emerging',
292
+ });
293
+ }
294
+ return threats;
295
+ }
296
+ }
7
297
  /**
8
298
  * Analyze content for sensitive information
9
299
  * Enhanced with Generated Knowledge Prompting for security and privacy expertise
10
300
  */
11
301
  export async function analyzeContentSecurity(args) {
12
302
  const { content, contentType = 'general', userDefinedPatterns, knowledgeEnhancement = true, // Default to GKP enabled
13
- enhancedMode = true // Default to enhanced mode
303
+ enhancedMode = true, // Default to enhanced mode
304
+ enableMemoryIntegration = true, // Default to memory integration enabled
305
+ enableTreeSitterAnalysis = true, // Default to tree-sitter enabled
14
306
  } = args;
15
307
  try {
16
308
  const { analyzeSensitiveContent } = await import('../utils/content-masking.js');
17
309
  if (!content || content.trim().length === 0) {
18
310
  throw new McpAdrError('Content is required for security analysis', 'INVALID_INPUT');
19
311
  }
312
+ // Initialize memory manager if enabled
313
+ let securityMemoryManager = null;
314
+ if (enableMemoryIntegration) {
315
+ securityMemoryManager = new SecurityMemoryManager();
316
+ await securityMemoryManager.initialize();
317
+ }
318
+ // Perform tree-sitter analysis for enhanced security detection
319
+ const treeSitterFindings = [];
320
+ let treeSitterContext = '';
321
+ if (enableTreeSitterAnalysis && contentType === 'code') {
322
+ try {
323
+ const analyzer = new TreeSitterAnalyzer();
324
+ // Create a temporary file to analyze the content
325
+ const { writeFileSync, unlinkSync } = await import('fs');
326
+ const { join } = await import('path');
327
+ const { tmpdir } = await import('os');
328
+ // Determine file extension based on content patterns
329
+ let extension = '.txt';
330
+ if (content.includes('import ') ||
331
+ content.includes('export ') ||
332
+ content.includes('function ')) {
333
+ extension =
334
+ content.includes('interface ') || content.includes(': string') ? '.ts' : '.js';
335
+ }
336
+ else if (content.includes('def ') || content.includes('import ')) {
337
+ extension = '.py';
338
+ }
339
+ else if (content.includes('apiVersion:') || content.includes('kind:')) {
340
+ extension = '.yaml';
341
+ }
342
+ else if (content.includes('resource ') || content.includes('provider ')) {
343
+ extension = '.tf';
344
+ }
345
+ const tempFile = join(tmpdir(), `content-analysis-${Date.now()}${extension}`);
346
+ writeFileSync(tempFile, content);
347
+ try {
348
+ const analysis = await analyzer.analyzeFile(tempFile);
349
+ // Extract security-relevant findings
350
+ if (analysis.hasSecrets && analysis.secrets.length > 0) {
351
+ analysis.secrets.forEach(secret => {
352
+ treeSitterFindings.push({
353
+ type: 'secret',
354
+ category: secret.type,
355
+ content: secret.value,
356
+ confidence: secret.confidence,
357
+ severity: secret.confidence > 0.8 ? 'high' : secret.confidence > 0.6 ? 'medium' : 'low',
358
+ location: secret.location,
359
+ context: secret.context,
360
+ source: 'tree-sitter',
361
+ });
362
+ });
363
+ }
364
+ // Security issues
365
+ if (analysis.securityIssues && analysis.securityIssues.length > 0) {
366
+ analysis.securityIssues.forEach(issue => {
367
+ treeSitterFindings.push({
368
+ type: 'security_issue',
369
+ category: issue.type,
370
+ content: issue.message,
371
+ confidence: 0.9,
372
+ severity: issue.severity,
373
+ location: issue.location,
374
+ context: issue.suggestion,
375
+ source: 'tree-sitter',
376
+ });
377
+ });
378
+ }
379
+ // Dangerous imports
380
+ if (analysis.imports) {
381
+ analysis.imports.forEach(imp => {
382
+ if (imp.isDangerous) {
383
+ treeSitterFindings.push({
384
+ type: 'dangerous_import',
385
+ category: 'import',
386
+ content: imp.module,
387
+ confidence: 0.8,
388
+ severity: 'medium',
389
+ location: imp.location,
390
+ context: imp.reason || 'Potentially dangerous import detected',
391
+ source: 'tree-sitter',
392
+ });
393
+ }
394
+ });
395
+ }
396
+ if (treeSitterFindings.length > 0) {
397
+ treeSitterContext = `\n## 🔍 Tree-sitter Enhanced Analysis\n\n**Detected ${treeSitterFindings.length} security findings:**\n${treeSitterFindings.map(f => `- **${f.type}**: ${f.content} (${f.severity} confidence)`).join('\n')}\n\n---\n`;
398
+ }
399
+ }
400
+ finally {
401
+ // Clean up temp file
402
+ try {
403
+ unlinkSync(tempFile);
404
+ }
405
+ catch {
406
+ // Ignore cleanup errors
407
+ }
408
+ }
409
+ }
410
+ catch (error) {
411
+ console.warn('Tree-sitter analysis failed, continuing with standard analysis:', error);
412
+ }
413
+ }
20
414
  let enhancedPrompt = '';
21
415
  let knowledgeContext = '';
22
416
  // Generate security and privacy knowledge if enabled
@@ -27,11 +421,11 @@ export async function analyzeContentSecurity(args) {
27
421
  projectPath: process.cwd(),
28
422
  technologies: [],
29
423
  patterns: [],
30
- projectType: 'security-content-analysis'
424
+ projectType: 'security-content-analysis',
31
425
  }, {
32
426
  domains: ['security-patterns'],
33
427
  depth: 'intermediate',
34
- cacheEnabled: true
428
+ cacheEnabled: true,
35
429
  });
36
430
  knowledgeContext = `\n## Security & Privacy Knowledge Enhancement\n\n${knowledgeResult.prompt}\n\n---\n`;
37
431
  }
@@ -53,9 +447,90 @@ Leverage the provided cybersecurity and data privacy knowledge to create compreh
53
447
  Provide detailed findings with confidence scores and practical remediation recommendations.
54
448
  Consider regulatory compliance requirements, data classification standards, and modern security practices.
55
449
  Focus on actionable security insights that can prevent data exposure and ensure compliance.`,
56
- responseFormat: 'text'
450
+ responseFormat: 'text',
57
451
  });
58
452
  if (executionResult.isAIGenerated) {
453
+ // Memory integration: store security patterns and analysis results
454
+ let memoryIntegrationInfo = '';
455
+ if (securityMemoryManager) {
456
+ try {
457
+ // Extract patterns from AI analysis (simplified parsing)
458
+ const detectedPatterns = parseDetectedPatterns(executionResult.content, userDefinedPatterns);
459
+ const maskingResults = {
460
+ strategy: 'analysis-only',
461
+ securityScore: calculateSecurityScore(detectedPatterns, content),
462
+ successRate: 1.0,
463
+ preservedContext: 1.0, // Analysis doesn't mask, so context is preserved
464
+ complianceLevel: 'analysis-complete',
465
+ };
466
+ // Store security pattern
467
+ const patternId = await securityMemoryManager.storeSecurityPattern(contentType, detectedPatterns, maskingResults, {
468
+ contentLength: content.length,
469
+ method: 'ai-powered-analysis',
470
+ userDefinedPatterns: userDefinedPatterns?.length || 0,
471
+ });
472
+ // Track evolution
473
+ const evolution = await securityMemoryManager.trackMaskingEvolution(undefined, maskingResults);
474
+ // Get institutional insights
475
+ const institutionalAnalysis = await securityMemoryManager.analyzeInstitutionalSecurity();
476
+ memoryIntegrationInfo = `
477
+
478
+ ## 🧠 Security Memory Integration
479
+
480
+ - **Pattern Stored**: ✅ Security analysis saved (ID: ${patternId.substring(0, 8)}...)
481
+ - **Content Type**: ${contentType}
482
+ - **Patterns Detected**: ${detectedPatterns.length}
483
+ - **Security Score**: ${Math.round(maskingResults.securityScore * 100)}%
484
+
485
+ ${evolution.improvements.length > 0
486
+ ? `### Security Improvements
487
+ ${evolution.improvements.map(improvement => `- ${improvement}`).join('\n')}
488
+ `
489
+ : ''}
490
+
491
+ ${evolution.recommendations.length > 0
492
+ ? `### Evolution Recommendations
493
+ ${evolution.recommendations.map(rec => `- ${rec}`).join('\n')}
494
+ `
495
+ : ''}
496
+
497
+ ${institutionalAnalysis.commonPatterns.length > 0
498
+ ? `### Institutional Security Patterns
499
+ ${institutionalAnalysis.commonPatterns
500
+ .slice(0, 3)
501
+ .map(pattern => `- **${pattern.type}**: ${pattern.frequency} occurrences`)
502
+ .join('\n')}
503
+ `
504
+ : ''}
505
+
506
+ ${institutionalAnalysis.complianceStatus
507
+ ? `### Compliance Status
508
+ - **GDPR**: ${institutionalAnalysis.complianceStatus.gdpr}
509
+ - **HIPAA**: ${institutionalAnalysis.complianceStatus.hipaa}
510
+ - **PCI**: ${institutionalAnalysis.complianceStatus.pci}
511
+ `
512
+ : ''}
513
+
514
+ ${institutionalAnalysis.recommendations.length > 0
515
+ ? `### Security Recommendations
516
+ ${institutionalAnalysis.recommendations
517
+ .slice(0, 3)
518
+ .map(rec => `- ${rec}`)
519
+ .join('\n')}
520
+ `
521
+ : ''}
522
+ `;
523
+ }
524
+ catch (memoryError) {
525
+ memoryIntegrationInfo = `
526
+
527
+ ## 🧠 Security Memory Integration Status
528
+
529
+ - **Status**: ⚠️ Memory integration failed - analysis completed without persistence
530
+ - **Error**: ${memoryError instanceof Error ? memoryError.message : 'Unknown error'}
531
+ `;
532
+ }
533
+ }
59
534
  // AI execution successful - return actual security analysis results
60
535
  return formatMCPResponse({
61
536
  ...executionResult,
@@ -64,15 +539,20 @@ Focus on actionable security insights that can prevent data exposure and ensure
64
539
  ## Enhancement Features
65
540
  - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
66
541
  - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
542
+ - **Memory Integration**: ${enableMemoryIntegration ? '✅ Enabled' : '❌ Disabled'}
543
+ - **Tree-sitter Analysis**: ${enableTreeSitterAnalysis ? '✅ Enabled' : '❌ Disabled'}
67
544
  - **Knowledge Domains**: Cybersecurity, data privacy, regulatory compliance, secret management
68
545
 
69
546
  ## Analysis Information
70
547
  - **Content Type**: ${contentType}
71
548
 
72
- ${knowledgeContext ? `## Applied Security Knowledge
549
+ ${knowledgeContext
550
+ ? `## Applied Security Knowledge
73
551
 
74
552
  ${knowledgeContext}
75
- ` : ''}
553
+ `
554
+ : ''}
555
+ ${treeSitterContext}
76
556
  - **Content Length**: ${content.length} characters
77
557
  - **User-Defined Patterns**: ${userDefinedPatterns?.length || 0} patterns
78
558
 
@@ -80,6 +560,8 @@ ${knowledgeContext}
80
560
 
81
561
  ${executionResult.content}
82
562
 
563
+ ${memoryIntegrationInfo}
564
+
83
565
  ## Next Steps
84
566
 
85
567
  Based on the security analysis:
@@ -117,7 +599,9 @@ To apply masking to identified sensitive content, use the \`generate_content_mas
117
599
  * Enhanced with Generated Knowledge Prompting for security and privacy expertise
118
600
  */
119
601
  export async function generateContentMasking(args) {
120
- const { content, detectedItems, maskingStrategy = 'full' } = args;
602
+ const { content, detectedItems, maskingStrategy = 'full',
603
+ // enableMemoryIntegration and contentType can be used for future enhancements
604
+ } = args;
121
605
  try {
122
606
  const { generateMaskingInstructions } = await import('../utils/content-masking.js');
123
607
  if (!content || content.trim().length === 0) {
@@ -155,7 +639,7 @@ export async function generateContentMasking(args) {
155
639
  Apply appropriate masking to sensitive content while preserving functionality and readability.
156
640
  Focus on balancing security with usability, maintaining context where possible.
157
641
  Provide detailed explanations for masking decisions and security recommendations.`,
158
- responseFormat: 'text'
642
+ responseFormat: 'text',
159
643
  });
160
644
  if (executionResult.isAIGenerated) {
161
645
  // AI execution successful - return actual content masking results
@@ -218,7 +702,10 @@ export async function configureCustomPatterns(args) {
218
702
  // Use actual file operations to scan project structure
219
703
  const { scanProjectStructure } = await import('../utils/actual-file-operations.js');
220
704
  // Actually scan project structure
221
- const projectStructure = await scanProjectStructure(projectPath, { readContent: true, maxFileSize: 10000 });
705
+ const projectStructure = await scanProjectStructure(projectPath, {
706
+ readContent: true,
707
+ maxFileSize: 10000,
708
+ });
222
709
  const customPatternPrompt = `
223
710
  # Custom Pattern Configuration Generation
224
711
 
@@ -230,49 +717,65 @@ Based on actual project structure analysis, here are the findings:
230
717
  - **Directories**: ${projectStructure.directories.join(', ')}
231
718
 
232
719
  ## Package Management Files
233
- ${projectStructure.packageFiles.length > 0 ?
234
- projectStructure.packageFiles.map(f => `
720
+ ${projectStructure.packageFiles.length > 0
721
+ ? projectStructure.packageFiles
722
+ .map(f => `
235
723
  ### ${f.filename}
236
724
  \`\`\`
237
725
  ${f.content.slice(0, 500)}${f.content.length > 500 ? '\n... (truncated)' : ''}
238
726
  \`\`\`
239
- `).join('\n') : '- No package files found'}
727
+ `)
728
+ .join('\n')
729
+ : '- No package files found'}
240
730
 
241
731
  ## Environment Configuration Files
242
- ${projectStructure.environmentFiles.length > 0 ?
243
- projectStructure.environmentFiles.map(f => `
732
+ ${projectStructure.environmentFiles.length > 0
733
+ ? projectStructure.environmentFiles
734
+ .map(f => `
244
735
  ### ${f.filename}
245
736
  \`\`\`
246
737
  ${f.content.slice(0, 300)}${f.content.length > 300 ? '\n... (truncated)' : ''}
247
738
  \`\`\`
248
- `).join('\n') : '- No environment files found'}
739
+ `)
740
+ .join('\n')
741
+ : '- No environment files found'}
249
742
 
250
743
  ## Configuration Files
251
- ${projectStructure.configFiles.length > 0 ?
252
- projectStructure.configFiles.map(f => `
744
+ ${projectStructure.configFiles.length > 0
745
+ ? projectStructure.configFiles
746
+ .map(f => `
253
747
  ### ${f.filename}
254
748
  \`\`\`
255
749
  ${f.content.slice(0, 300)}${f.content.length > 300 ? '\n... (truncated)' : ''}
256
750
  \`\`\`
257
- `).join('\n') : '- No config files found'}
751
+ `)
752
+ .join('\n')
753
+ : '- No config files found'}
258
754
 
259
755
  ## Script Files
260
- ${projectStructure.scriptFiles.length > 0 ?
261
- projectStructure.scriptFiles.map(f => `
756
+ ${projectStructure.scriptFiles.length > 0
757
+ ? projectStructure.scriptFiles
758
+ .map(f => `
262
759
  ### ${f.filename}
263
760
  \`\`\`
264
761
  ${f.content.slice(0, 400)}${f.content.length > 400 ? '\n... (truncated)' : ''}
265
762
  \`\`\`
266
- `).join('\n') : '- No script files found'}
763
+ `)
764
+ .join('\n')
765
+ : '- No script files found'}
267
766
 
268
767
  ## Existing Patterns Context
269
768
 
270
- ${existingPatterns ? `
769
+ ${existingPatterns
770
+ ? `
271
771
  ### Current Patterns (${existingPatterns.length})
272
- ${existingPatterns.map((pattern, index) => `
772
+ ${existingPatterns
773
+ .map((pattern, index) => `
273
774
  #### ${index + 1}. ${pattern}
274
- `).join('')}
275
- ` : 'No existing patterns provided.'}
775
+ `)
776
+ .join('')}
777
+ `
778
+ : 'No existing patterns provided.'}
276
779
 
277
780
  ## Pattern Generation Requirements
278
781
 
@@ -345,9 +848,9 @@ const result = await configureCustomPatterns({ projectPath, existingPatterns });
345
848
  packageFiles: projectStructure.packageFiles.length,
346
849
  environmentFiles: projectStructure.environmentFiles.length,
347
850
  configFiles: projectStructure.configFiles.length,
348
- scriptFiles: projectStructure.scriptFiles.length
349
- }
350
- }
851
+ scriptFiles: projectStructure.scriptFiles.length,
852
+ },
853
+ },
351
854
  };
352
855
  return {
353
856
  content: [
@@ -466,4 +969,104 @@ ${validation.securityScore >= 0.9
466
969
  throw new McpAdrError(`Failed to validate masking: ${error instanceof Error ? error.message : String(error)}`, 'VALIDATION_ERROR');
467
970
  }
468
971
  }
972
+ /**
973
+ * Helper methods for SecurityMemoryManager
974
+ */
975
+ function calculateOverallRisk(detectedPatterns) {
976
+ if (detectedPatterns.length === 0)
977
+ return 'low';
978
+ const criticalCount = detectedPatterns.filter(p => p.severity === 'critical').length;
979
+ const highCount = detectedPatterns.filter(p => p.severity === 'high').length;
980
+ if (criticalCount > 0)
981
+ return 'critical';
982
+ if (highCount > 2)
983
+ return 'high';
984
+ if (detectedPatterns.length > 5)
985
+ return 'medium';
986
+ return 'low';
987
+ }
988
+ function assessComplianceImpact(detectedPatterns) {
989
+ const hasPersonalData = detectedPatterns.some(p => p.type === 'email' || p.type === 'name' || p.category === 'personal-data');
990
+ const hasFinancialData = detectedPatterns.some(p => p.type === 'credit-card' || p.type === 'bank-account' || p.category === 'payment-data');
991
+ const hasHealthData = detectedPatterns.some(p => p.type === 'medical-record' || p.category === 'health-data');
992
+ if (hasHealthData)
993
+ return 'HIPAA compliance required - high impact';
994
+ if (hasFinancialData)
995
+ return 'PCI DSS compliance required - high impact';
996
+ if (hasPersonalData)
997
+ return 'GDPR compliance required - medium impact';
998
+ return 'Standard security practices apply - low impact';
999
+ }
1000
+ /**
1001
+ * Helper function to parse detected patterns from AI analysis content
1002
+ */
1003
+ function parseDetectedPatterns(aiContent, userDefinedPatterns) {
1004
+ // Simplified pattern parsing - in production, would use more sophisticated NLP
1005
+ const patterns = [];
1006
+ // Look for common security-related keywords
1007
+ const securityKeywords = [
1008
+ { keyword: 'password', type: 'password', severity: 'high' },
1009
+ { keyword: 'secret', type: 'secret', severity: 'high' },
1010
+ { keyword: 'api.key', type: 'api-key', severity: 'critical' },
1011
+ { keyword: 'email', type: 'email', severity: 'medium' },
1012
+ { keyword: 'token', type: 'token', severity: 'high' },
1013
+ { keyword: 'credit.card', type: 'credit-card', severity: 'critical' },
1014
+ { keyword: 'ssn', type: 'ssn', severity: 'critical' },
1015
+ { keyword: 'phone', type: 'phone', severity: 'low' },
1016
+ ];
1017
+ const lowerContent = aiContent.toLowerCase();
1018
+ securityKeywords.forEach(({ keyword, type, severity }) => {
1019
+ if (lowerContent.includes(keyword.replace('.', ' '))) {
1020
+ patterns.push({
1021
+ type,
1022
+ category: 'sensitive-data',
1023
+ confidence: 0.7, // Simplified confidence
1024
+ severity: severity,
1025
+ description: `Detected potential ${type.replace('-', ' ')} pattern`,
1026
+ context: `Found in AI analysis content`,
1027
+ });
1028
+ }
1029
+ });
1030
+ // Add user-defined patterns
1031
+ if (userDefinedPatterns) {
1032
+ userDefinedPatterns.forEach(pattern => {
1033
+ if (lowerContent.includes(pattern.toLowerCase())) {
1034
+ patterns.push({
1035
+ type: 'user-defined',
1036
+ category: 'custom-pattern',
1037
+ confidence: 0.8,
1038
+ severity: 'medium',
1039
+ description: `User-defined pattern detected: ${pattern}`,
1040
+ context: 'User-defined security pattern',
1041
+ });
1042
+ }
1043
+ });
1044
+ }
1045
+ return patterns;
1046
+ }
1047
+ /**
1048
+ * Helper function to calculate security score based on detected patterns
1049
+ */
1050
+ function calculateSecurityScore(detectedPatterns, content) {
1051
+ if (detectedPatterns.length === 0) {
1052
+ return 1.0; // No patterns detected = highest security score
1053
+ }
1054
+ const contentLength = content.length;
1055
+ const patternDensity = detectedPatterns.length / Math.max(contentLength / 1000, 1); // patterns per 1000 chars
1056
+ // Calculate base score based on pattern density and severity
1057
+ let baseScore = 1.0;
1058
+ detectedPatterns.forEach(pattern => {
1059
+ const severityWeight = {
1060
+ low: 0.05,
1061
+ medium: 0.1,
1062
+ high: 0.2,
1063
+ critical: 0.3,
1064
+ }[pattern.severity] || 0.1;
1065
+ baseScore -= severityWeight * pattern.confidence;
1066
+ });
1067
+ // Apply density penalty
1068
+ const densityPenalty = Math.min(patternDensity * 0.1, 0.3);
1069
+ baseScore -= densityPenalty;
1070
+ return Math.max(0, Math.min(1, baseScore));
1071
+ }
469
1072
  //# sourceMappingURL=content-masking-tool.js.map