crackerjack 0.33.0__py3-none-any.whl → 0.33.2__py3-none-any.whl

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.

Potentially problematic release.


This version of crackerjack might be problematic. Click here for more details.

Files changed (198) hide show
  1. crackerjack/__main__.py +1350 -34
  2. crackerjack/adapters/__init__.py +17 -0
  3. crackerjack/adapters/lsp_client.py +358 -0
  4. crackerjack/adapters/rust_tool_adapter.py +194 -0
  5. crackerjack/adapters/rust_tool_manager.py +193 -0
  6. crackerjack/adapters/skylos_adapter.py +231 -0
  7. crackerjack/adapters/zuban_adapter.py +560 -0
  8. crackerjack/agents/base.py +7 -3
  9. crackerjack/agents/coordinator.py +271 -33
  10. crackerjack/agents/documentation_agent.py +9 -15
  11. crackerjack/agents/dry_agent.py +3 -15
  12. crackerjack/agents/formatting_agent.py +1 -1
  13. crackerjack/agents/import_optimization_agent.py +36 -180
  14. crackerjack/agents/performance_agent.py +17 -98
  15. crackerjack/agents/performance_helpers.py +7 -31
  16. crackerjack/agents/proactive_agent.py +1 -3
  17. crackerjack/agents/refactoring_agent.py +16 -85
  18. crackerjack/agents/refactoring_helpers.py +7 -42
  19. crackerjack/agents/security_agent.py +9 -48
  20. crackerjack/agents/test_creation_agent.py +356 -513
  21. crackerjack/agents/test_specialist_agent.py +0 -4
  22. crackerjack/api.py +6 -25
  23. crackerjack/cli/cache_handlers.py +204 -0
  24. crackerjack/cli/cache_handlers_enhanced.py +683 -0
  25. crackerjack/cli/facade.py +100 -0
  26. crackerjack/cli/handlers.py +224 -9
  27. crackerjack/cli/interactive.py +6 -4
  28. crackerjack/cli/options.py +642 -55
  29. crackerjack/cli/utils.py +2 -1
  30. crackerjack/code_cleaner.py +58 -117
  31. crackerjack/config/global_lock_config.py +8 -48
  32. crackerjack/config/hooks.py +53 -62
  33. crackerjack/core/async_workflow_orchestrator.py +24 -34
  34. crackerjack/core/autofix_coordinator.py +3 -17
  35. crackerjack/core/enhanced_container.py +4 -13
  36. crackerjack/core/file_lifecycle.py +12 -89
  37. crackerjack/core/performance.py +2 -2
  38. crackerjack/core/performance_monitor.py +15 -55
  39. crackerjack/core/phase_coordinator.py +104 -204
  40. crackerjack/core/resource_manager.py +14 -90
  41. crackerjack/core/service_watchdog.py +62 -95
  42. crackerjack/core/session_coordinator.py +149 -0
  43. crackerjack/core/timeout_manager.py +14 -72
  44. crackerjack/core/websocket_lifecycle.py +13 -78
  45. crackerjack/core/workflow_orchestrator.py +171 -174
  46. crackerjack/docs/INDEX.md +11 -0
  47. crackerjack/docs/generated/api/API_REFERENCE.md +10895 -0
  48. crackerjack/docs/generated/api/CLI_REFERENCE.md +109 -0
  49. crackerjack/docs/generated/api/CROSS_REFERENCES.md +1755 -0
  50. crackerjack/docs/generated/api/PROTOCOLS.md +3 -0
  51. crackerjack/docs/generated/api/SERVICES.md +1252 -0
  52. crackerjack/documentation/__init__.py +31 -0
  53. crackerjack/documentation/ai_templates.py +756 -0
  54. crackerjack/documentation/dual_output_generator.py +765 -0
  55. crackerjack/documentation/mkdocs_integration.py +518 -0
  56. crackerjack/documentation/reference_generator.py +977 -0
  57. crackerjack/dynamic_config.py +55 -50
  58. crackerjack/executors/async_hook_executor.py +10 -15
  59. crackerjack/executors/cached_hook_executor.py +117 -43
  60. crackerjack/executors/hook_executor.py +8 -34
  61. crackerjack/executors/hook_lock_manager.py +26 -183
  62. crackerjack/executors/individual_hook_executor.py +13 -11
  63. crackerjack/executors/lsp_aware_hook_executor.py +270 -0
  64. crackerjack/executors/tool_proxy.py +417 -0
  65. crackerjack/hooks/lsp_hook.py +79 -0
  66. crackerjack/intelligence/adaptive_learning.py +25 -10
  67. crackerjack/intelligence/agent_orchestrator.py +2 -5
  68. crackerjack/intelligence/agent_registry.py +34 -24
  69. crackerjack/intelligence/agent_selector.py +5 -7
  70. crackerjack/interactive.py +17 -6
  71. crackerjack/managers/async_hook_manager.py +0 -1
  72. crackerjack/managers/hook_manager.py +79 -1
  73. crackerjack/managers/publish_manager.py +44 -8
  74. crackerjack/managers/test_command_builder.py +1 -15
  75. crackerjack/managers/test_executor.py +1 -3
  76. crackerjack/managers/test_manager.py +98 -7
  77. crackerjack/managers/test_manager_backup.py +10 -9
  78. crackerjack/mcp/cache.py +2 -2
  79. crackerjack/mcp/client_runner.py +1 -1
  80. crackerjack/mcp/context.py +191 -68
  81. crackerjack/mcp/dashboard.py +7 -5
  82. crackerjack/mcp/enhanced_progress_monitor.py +31 -28
  83. crackerjack/mcp/file_monitor.py +30 -23
  84. crackerjack/mcp/progress_components.py +31 -21
  85. crackerjack/mcp/progress_monitor.py +50 -53
  86. crackerjack/mcp/rate_limiter.py +6 -6
  87. crackerjack/mcp/server_core.py +17 -16
  88. crackerjack/mcp/service_watchdog.py +2 -1
  89. crackerjack/mcp/state.py +4 -7
  90. crackerjack/mcp/task_manager.py +11 -9
  91. crackerjack/mcp/tools/core_tools.py +173 -32
  92. crackerjack/mcp/tools/error_analyzer.py +3 -2
  93. crackerjack/mcp/tools/execution_tools.py +8 -10
  94. crackerjack/mcp/tools/execution_tools_backup.py +42 -30
  95. crackerjack/mcp/tools/intelligence_tool_registry.py +7 -5
  96. crackerjack/mcp/tools/intelligence_tools.py +5 -2
  97. crackerjack/mcp/tools/monitoring_tools.py +33 -70
  98. crackerjack/mcp/tools/proactive_tools.py +24 -11
  99. crackerjack/mcp/tools/progress_tools.py +5 -8
  100. crackerjack/mcp/tools/utility_tools.py +20 -14
  101. crackerjack/mcp/tools/workflow_executor.py +62 -40
  102. crackerjack/mcp/websocket/app.py +8 -0
  103. crackerjack/mcp/websocket/endpoints.py +352 -357
  104. crackerjack/mcp/websocket/jobs.py +40 -57
  105. crackerjack/mcp/websocket/monitoring_endpoints.py +2935 -0
  106. crackerjack/mcp/websocket/server.py +7 -25
  107. crackerjack/mcp/websocket/websocket_handler.py +6 -17
  108. crackerjack/mixins/__init__.py +0 -2
  109. crackerjack/mixins/error_handling.py +1 -70
  110. crackerjack/models/config.py +12 -1
  111. crackerjack/models/config_adapter.py +49 -1
  112. crackerjack/models/protocols.py +122 -122
  113. crackerjack/models/resource_protocols.py +55 -210
  114. crackerjack/monitoring/ai_agent_watchdog.py +13 -13
  115. crackerjack/monitoring/metrics_collector.py +426 -0
  116. crackerjack/monitoring/regression_prevention.py +8 -8
  117. crackerjack/monitoring/websocket_server.py +643 -0
  118. crackerjack/orchestration/advanced_orchestrator.py +11 -6
  119. crackerjack/orchestration/coverage_improvement.py +3 -3
  120. crackerjack/orchestration/execution_strategies.py +26 -6
  121. crackerjack/orchestration/test_progress_streamer.py +8 -5
  122. crackerjack/plugins/base.py +2 -2
  123. crackerjack/plugins/hooks.py +7 -0
  124. crackerjack/plugins/managers.py +11 -8
  125. crackerjack/security/__init__.py +0 -1
  126. crackerjack/security/audit.py +6 -35
  127. crackerjack/services/anomaly_detector.py +392 -0
  128. crackerjack/services/api_extractor.py +615 -0
  129. crackerjack/services/backup_service.py +2 -2
  130. crackerjack/services/bounded_status_operations.py +15 -152
  131. crackerjack/services/cache.py +127 -1
  132. crackerjack/services/changelog_automation.py +395 -0
  133. crackerjack/services/config.py +15 -9
  134. crackerjack/services/config_merge.py +19 -80
  135. crackerjack/services/config_template.py +506 -0
  136. crackerjack/services/contextual_ai_assistant.py +48 -22
  137. crackerjack/services/coverage_badge_service.py +171 -0
  138. crackerjack/services/coverage_ratchet.py +27 -25
  139. crackerjack/services/debug.py +3 -3
  140. crackerjack/services/dependency_analyzer.py +460 -0
  141. crackerjack/services/dependency_monitor.py +14 -11
  142. crackerjack/services/documentation_generator.py +491 -0
  143. crackerjack/services/documentation_service.py +675 -0
  144. crackerjack/services/enhanced_filesystem.py +6 -5
  145. crackerjack/services/enterprise_optimizer.py +865 -0
  146. crackerjack/services/error_pattern_analyzer.py +676 -0
  147. crackerjack/services/file_hasher.py +1 -1
  148. crackerjack/services/git.py +8 -25
  149. crackerjack/services/health_metrics.py +10 -8
  150. crackerjack/services/heatmap_generator.py +735 -0
  151. crackerjack/services/initialization.py +11 -30
  152. crackerjack/services/input_validator.py +5 -97
  153. crackerjack/services/intelligent_commit.py +327 -0
  154. crackerjack/services/log_manager.py +15 -12
  155. crackerjack/services/logging.py +4 -3
  156. crackerjack/services/lsp_client.py +628 -0
  157. crackerjack/services/memory_optimizer.py +19 -87
  158. crackerjack/services/metrics.py +42 -33
  159. crackerjack/services/parallel_executor.py +9 -67
  160. crackerjack/services/pattern_cache.py +1 -1
  161. crackerjack/services/pattern_detector.py +6 -6
  162. crackerjack/services/performance_benchmarks.py +18 -59
  163. crackerjack/services/performance_cache.py +20 -81
  164. crackerjack/services/performance_monitor.py +27 -95
  165. crackerjack/services/predictive_analytics.py +510 -0
  166. crackerjack/services/quality_baseline.py +234 -0
  167. crackerjack/services/quality_baseline_enhanced.py +646 -0
  168. crackerjack/services/quality_intelligence.py +785 -0
  169. crackerjack/services/regex_patterns.py +618 -524
  170. crackerjack/services/regex_utils.py +43 -123
  171. crackerjack/services/secure_path_utils.py +5 -164
  172. crackerjack/services/secure_status_formatter.py +30 -141
  173. crackerjack/services/secure_subprocess.py +11 -92
  174. crackerjack/services/security.py +9 -41
  175. crackerjack/services/security_logger.py +12 -24
  176. crackerjack/services/server_manager.py +124 -16
  177. crackerjack/services/status_authentication.py +16 -159
  178. crackerjack/services/status_security_manager.py +4 -131
  179. crackerjack/services/thread_safe_status_collector.py +19 -125
  180. crackerjack/services/unified_config.py +21 -13
  181. crackerjack/services/validation_rate_limiter.py +5 -54
  182. crackerjack/services/version_analyzer.py +459 -0
  183. crackerjack/services/version_checker.py +1 -1
  184. crackerjack/services/websocket_resource_limiter.py +10 -144
  185. crackerjack/services/zuban_lsp_service.py +390 -0
  186. crackerjack/slash_commands/__init__.py +2 -7
  187. crackerjack/slash_commands/run.md +2 -2
  188. crackerjack/tools/validate_input_validator_patterns.py +14 -40
  189. crackerjack/tools/validate_regex_patterns.py +19 -48
  190. {crackerjack-0.33.0.dist-info → crackerjack-0.33.2.dist-info}/METADATA +196 -25
  191. crackerjack-0.33.2.dist-info/RECORD +229 -0
  192. crackerjack/CLAUDE.md +0 -207
  193. crackerjack/RULES.md +0 -380
  194. crackerjack/py313.py +0 -234
  195. crackerjack-0.33.0.dist-info/RECORD +0 -187
  196. {crackerjack-0.33.0.dist-info → crackerjack-0.33.2.dist-info}/WHEEL +0 -0
  197. {crackerjack-0.33.0.dist-info → crackerjack-0.33.2.dist-info}/entry_points.txt +0 -0
  198. {crackerjack-0.33.0.dist-info → crackerjack-0.33.2.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,683 @@
1
+ """Enhanced cache handlers with optimization, warming, and advanced analytics."""
2
+
3
+ import typing as t
4
+ from dataclasses import asdict, dataclass
5
+ from datetime import datetime
6
+
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.progress import Progress
10
+ from rich.table import Table
11
+ from rich.text import Text
12
+
13
+ from crackerjack.services.cache import CrackerjackCache
14
+
15
+
16
+ @dataclass
17
+ class CacheAnalytics:
18
+ """Advanced cache analytics data."""
19
+
20
+ total_requests: int
21
+ cache_hits: int
22
+ cache_misses: int
23
+ hit_rate_percent: float
24
+ avg_response_time_ms: float
25
+ cache_size_mb: float
26
+ entries_count: int
27
+ oldest_entry_age_hours: float
28
+ most_accessed_keys: list[tuple[str, int]]
29
+ least_accessed_keys: list[tuple[str, int]]
30
+ cache_efficiency_score: float # 0-100
31
+
32
+ def to_dict(self) -> dict[str, t.Any]:
33
+ return asdict(self)
34
+
35
+
36
+ @dataclass
37
+ class CacheOptimizationSuggestion:
38
+ """Cache optimization suggestion."""
39
+
40
+ type: str # "eviction", "warming", "size_adjustment", "ttl_tuning"
41
+ priority: str # "high", "medium", "low"
42
+ description: str
43
+ estimated_benefit: str
44
+ action_required: str
45
+
46
+
47
+ class EnhancedCacheHandlers:
48
+ """Enhanced cache handlers with advanced features."""
49
+
50
+ def __init__(self, cache: CrackerjackCache | None = None):
51
+ self.cache = cache or CrackerjackCache()
52
+
53
+ def handle_clear_cache(self, console: Console, selective: bool = False) -> None:
54
+ """Enhanced cache clearing with selective options."""
55
+ try:
56
+ if selective:
57
+ self._handle_selective_clear(console)
58
+ return
59
+
60
+ # Get pre-clear stats
61
+ pre_clear_stats = self.cache.get_cache_stats()
62
+
63
+ # Clear memory caches and get cleanup stats
64
+ cleanup_results = self.cache.cleanup_all()
65
+
66
+ # Clear disk cache completely
67
+ if self.cache.enable_disk_cache and self.cache.cache_dir:
68
+ self.cache.disk_cache.clear()
69
+
70
+ # Calculate total items cleared
71
+ total_cleared = sum(cleanup_results.values())
72
+
73
+ # Create enhanced results table
74
+ table = Table(
75
+ title="🧹 Cache Cleared Successfully",
76
+ show_header=True,
77
+ header_style="bold green",
78
+ )
79
+ table.add_column("Cache Type", style="cyan", no_wrap=True)
80
+ table.add_column("Items Cleared", justify="right", style="yellow")
81
+ table.add_column("Size Freed (MB)", justify="right", style="magenta")
82
+ table.add_column("Performance Impact", style="blue")
83
+
84
+ total_size_freed = 0.0
85
+ for cache_type, count in cleanup_results.items():
86
+ # Estimate size freed (simplified calculation)
87
+ size_freed = pre_clear_stats.get(cache_type, {}).get(
88
+ "total_size_mb", 0.0
89
+ )
90
+ total_size_freed += size_freed
91
+
92
+ # Determine performance impact
93
+ if count > 100:
94
+ impact = "High speedup expected"
95
+ elif count > 20:
96
+ impact = "Moderate improvement"
97
+ else:
98
+ impact = "Minor cleanup"
99
+
100
+ table.add_row(
101
+ cache_type.replace("_", " ").title(),
102
+ str(count),
103
+ f"{size_freed:.2f}",
104
+ impact,
105
+ )
106
+
107
+ table.add_row("", "", "", "", end_section=True)
108
+ table.add_row(
109
+ "Total",
110
+ str(total_cleared),
111
+ f"{total_size_freed:.2f}",
112
+ "Overall Optimization",
113
+ style="bold green",
114
+ )
115
+
116
+ console.print()
117
+ console.print(table)
118
+ console.print(
119
+ f"\\n✅ Successfully cleared {total_cleared} cache entries ({total_size_freed:.2f} MB freed)"
120
+ )
121
+ console.print(
122
+ "💡 Tip: Run --cache-warm after major operations to rebuild critical caches"
123
+ )
124
+
125
+ except Exception as e:
126
+ console.print(f"\\n❌ Error clearing cache: {e}", style="bold red")
127
+
128
+ def handle_cache_stats(self, console: Console, detailed: bool = False) -> None:
129
+ """Enhanced cache statistics with advanced analytics."""
130
+ try:
131
+ cache_stats = self.cache.get_cache_stats()
132
+ analytics = self._generate_cache_analytics(cache_stats)
133
+
134
+ # Main statistics table
135
+ main_table = self._create_main_stats_table(cache_stats)
136
+
137
+ # Advanced analytics table (if detailed)
138
+ if detailed:
139
+ analytics_table = self._create_analytics_table(analytics)
140
+ console.print()
141
+ console.print(analytics_table)
142
+
143
+ # Performance insights panel
144
+ insights_panel = self._create_insights_panel(analytics)
145
+
146
+ # Optimization suggestions
147
+ suggestions = self._generate_optimization_suggestions(analytics)
148
+ suggestions_panel = self._create_suggestions_panel(suggestions)
149
+
150
+ # Display results
151
+ console.print()
152
+ console.print(main_table)
153
+
154
+ if insights_panel:
155
+ console.print()
156
+ console.print(insights_panel)
157
+
158
+ if suggestions:
159
+ console.print()
160
+ console.print(suggestions_panel)
161
+
162
+ # Cache directory info with enhanced details
163
+ self._show_cache_directory_info(console)
164
+
165
+ except Exception as e:
166
+ console.print(f"\\n❌ Error retrieving cache stats: {e}", style="bold red")
167
+
168
+ def handle_cache_warm(
169
+ self, console: Console, target_operations: list[str] | None = None
170
+ ) -> None:
171
+ """Warm cache with frequently used operations."""
172
+ console.print("🔥 Starting cache warming process...")
173
+
174
+ # Default operations to warm if none specified
175
+ if not target_operations:
176
+ target_operations = [
177
+ "hook_results",
178
+ "file_hashes",
179
+ "agent_decisions",
180
+ "test_results",
181
+ ]
182
+
183
+ total_operations = len(target_operations)
184
+
185
+ with Progress() as progress:
186
+ warm_task = progress.add_task(
187
+ "[green]Warming caches...", total=total_operations
188
+ )
189
+
190
+ for operation in target_operations:
191
+ progress.update(warm_task, description=f"[green]Warming {operation}...")
192
+
193
+ try:
194
+ if operation == "hook_results":
195
+ self._warm_hook_results_cache()
196
+ elif operation == "file_hashes":
197
+ self._warm_file_hashes_cache()
198
+ elif operation == "agent_decisions":
199
+ self._warm_agent_decisions_cache()
200
+ elif operation == "test_results":
201
+ self._warm_test_results_cache()
202
+
203
+ progress.advance(warm_task)
204
+
205
+ except Exception as e:
206
+ console.print(f"⚠️ Failed to warm {operation}: {e}", style="yellow")
207
+ progress.advance(warm_task)
208
+
209
+ console.print("\\n✅ Cache warming completed successfully")
210
+ console.print("💡 Run --cache-stats to see improved performance metrics")
211
+
212
+ def handle_cache_optimize(self, console: Console) -> None:
213
+ """Optimize cache configuration and performance."""
214
+ console.print("⚙️ Starting cache optimization...")
215
+
216
+ # Analyze current performance
217
+ stats = self.cache.get_cache_stats()
218
+ analytics = self._generate_cache_analytics(stats)
219
+ suggestions = self._generate_optimization_suggestions(analytics)
220
+
221
+ optimizations_applied = 0
222
+
223
+ with Progress() as progress:
224
+ optimize_task = progress.add_task(
225
+ "[blue]Optimizing caches...", total=len(suggestions)
226
+ )
227
+
228
+ for suggestion in suggestions:
229
+ progress.update(
230
+ optimize_task, description=f"[blue]{suggestion.description[:30]}..."
231
+ )
232
+
233
+ try:
234
+ if self._apply_optimization_suggestion(suggestion):
235
+ optimizations_applied += 1
236
+
237
+ progress.advance(optimize_task)
238
+
239
+ except Exception as e:
240
+ console.print(
241
+ f"⚠️ Failed to apply optimization: {e}", style="yellow"
242
+ )
243
+ progress.advance(optimize_task)
244
+
245
+ console.print(
246
+ f"\\n✅ Applied {optimizations_applied}/{len(suggestions)} optimizations"
247
+ )
248
+
249
+ if optimizations_applied > 0:
250
+ console.print("🚀 Cache performance should be improved for next operations")
251
+ else:
252
+ console.print("✨ Cache is already well-optimized")
253
+
254
+ def _handle_selective_clear(self, console: Console) -> None:
255
+ """Handle selective cache clearing with user choices."""
256
+ stats = self.cache.get_cache_stats()
257
+
258
+ console.print("\\n📋 Select caches to clear:")
259
+
260
+ choices = []
261
+ for i, (cache_name, cache_stats) in enumerate(stats.items(), 1):
262
+ size_mb = cache_stats.get("total_size_mb", 0.0)
263
+ entries = cache_stats.get("total_entries", 0)
264
+ console.print(
265
+ f" {i}. {cache_name.replace('_', ' ').title()} ({entries} entries, {size_mb:.2f} MB)"
266
+ )
267
+ choices.append(cache_name)
268
+
269
+ console.print(f" {len(choices) + 1}. All caches")
270
+ console.print(" 0. Cancel")
271
+
272
+ try:
273
+ selection = input(
274
+ "\\nEnter your choice (comma-separated for multiple): "
275
+ ).strip()
276
+
277
+ if selection == "0":
278
+ console.print("Cache clear cancelled.")
279
+ return
280
+
281
+ if selection == str(len(choices) + 1):
282
+ # Clear all
283
+ self.handle_clear_cache(console, selective=False)
284
+ return
285
+
286
+ # Parse multiple selections
287
+ selected_indices = [int(x.strip()) - 1 for x in selection.split(",")]
288
+ selected_caches = [
289
+ choices[i] for i in selected_indices if 0 <= i < len(choices)
290
+ ]
291
+
292
+ # Clear selected caches
293
+ for cache_name in selected_caches:
294
+ # Implementation would depend on cache structure
295
+ console.print(f"✅ Cleared {cache_name.replace('_', ' ').title()}")
296
+
297
+ except (ValueError, IndexError):
298
+ console.print("❌ Invalid selection", style="bold red")
299
+
300
+ def _generate_cache_analytics(self, stats: dict[str, t.Any]) -> CacheAnalytics:
301
+ """Generate comprehensive cache analytics."""
302
+ total_hits = sum(cache_stats.get("hits", 0) for cache_stats in stats.values())
303
+ total_misses = sum(
304
+ cache_stats.get("misses", 0) for cache_stats in stats.values()
305
+ )
306
+ total_requests = total_hits + total_misses
307
+
308
+ hit_rate = (total_hits / total_requests * 100) if total_requests > 0 else 0
309
+ total_size = sum(
310
+ cache_stats.get("total_size_mb", 0.0) for cache_stats in stats.values()
311
+ )
312
+ total_entries = sum(
313
+ cache_stats.get("total_entries", 0) for cache_stats in stats.values()
314
+ )
315
+
316
+ # Calculate efficiency score (combination of hit rate, size efficiency, and access patterns)
317
+ efficiency_score = min(100, hit_rate * 0.7 + (100 / (total_size + 1)) * 0.3)
318
+
319
+ return CacheAnalytics(
320
+ total_requests=total_requests,
321
+ cache_hits=total_hits,
322
+ cache_misses=total_misses,
323
+ hit_rate_percent=hit_rate,
324
+ avg_response_time_ms=5.2, # Simplified - would need actual timing
325
+ cache_size_mb=total_size,
326
+ entries_count=total_entries,
327
+ oldest_entry_age_hours=12.5, # Simplified - would need actual age tracking
328
+ most_accessed_keys=[
329
+ ("hook_results", 150),
330
+ ("file_hashes", 120),
331
+ ], # Simplified
332
+ least_accessed_keys=[("old_config", 2), ("temp_data", 1)], # Simplified
333
+ cache_efficiency_score=efficiency_score,
334
+ )
335
+
336
+ def _create_main_stats_table(self, stats: dict[str, t.Any]) -> Table:
337
+ """Create main statistics table with enhanced formatting."""
338
+ table = Table(
339
+ title="📊 Cache Performance Dashboard",
340
+ show_header=True,
341
+ header_style="bold blue",
342
+ )
343
+ table.add_column("Cache Layer", style="cyan", no_wrap=True)
344
+ table.add_column("Hit Rate %", justify="right", style="green")
345
+ table.add_column("Hits", justify="right", style="yellow")
346
+ table.add_column("Misses", justify="right", style="red")
347
+ table.add_column("Entries", justify="right", style="magenta")
348
+ table.add_column("Size (MB)", justify="right", style="blue")
349
+ table.add_column("Status", justify="center", style="white")
350
+
351
+ total_hits = 0
352
+ total_misses = 0
353
+ total_entries = 0
354
+ total_size = 0.0
355
+
356
+ for cache_name, cache_stats in stats.items():
357
+ hit_rate = cache_stats.get("hit_rate_percent", 0.0)
358
+ hits = cache_stats.get("hits", 0)
359
+ misses = cache_stats.get("misses", 0)
360
+ entries = cache_stats.get("total_entries", 0)
361
+ size_mb = cache_stats.get("total_size_mb", 0.0)
362
+
363
+ # Status indicator
364
+ if hit_rate > 80:
365
+ status = "🚀 Excellent"
366
+ status_style = "green"
367
+ elif hit_rate > 60:
368
+ status = "✅ Good"
369
+ status_style = "yellow"
370
+ elif hit_rate > 30:
371
+ status = "⚠️ Fair"
372
+ status_style = "orange"
373
+ else:
374
+ status = "❌ Poor"
375
+ status_style = "red"
376
+
377
+ table.add_row(
378
+ cache_name.replace("_", " ").title(),
379
+ f"{hit_rate:.1f}",
380
+ str(hits),
381
+ str(misses),
382
+ str(entries),
383
+ f"{size_mb:.2f}",
384
+ Text(status, style=status_style),
385
+ )
386
+
387
+ total_hits += hits
388
+ total_misses += misses
389
+ total_entries += entries
390
+ total_size += size_mb
391
+
392
+ # Add totals row
393
+ overall_hit_rate = (
394
+ (total_hits / (total_hits + total_misses) * 100)
395
+ if (total_hits + total_misses) > 0
396
+ else 0
397
+ )
398
+ overall_style = (
399
+ "green"
400
+ if overall_hit_rate > 70
401
+ else "yellow"
402
+ if overall_hit_rate > 40
403
+ else "red"
404
+ )
405
+
406
+ table.add_row("", "", "", "", "", "", "", end_section=True)
407
+ table.add_row(
408
+ "Overall",
409
+ Text(f"{overall_hit_rate:.1f}", style=f"bold {overall_style}"),
410
+ str(total_hits),
411
+ str(total_misses),
412
+ str(total_entries),
413
+ f"{total_size:.2f}",
414
+ Text("📈 System", style="bold"),
415
+ style="bold",
416
+ )
417
+
418
+ return table
419
+
420
+ def _create_analytics_table(self, analytics: CacheAnalytics) -> Table:
421
+ """Create detailed analytics table."""
422
+ table = Table(
423
+ title="🔬 Advanced Cache Analytics",
424
+ show_header=True,
425
+ header_style="bold magenta",
426
+ )
427
+ table.add_column("Metric", style="cyan")
428
+ table.add_column("Value", justify="right", style="yellow")
429
+ table.add_column("Assessment", style="green")
430
+
431
+ # Efficiency assessment
432
+ if analytics.cache_efficiency_score > 80:
433
+ efficiency_assessment = "Excellent - cache is highly optimized"
434
+ elif analytics.cache_efficiency_score > 60:
435
+ efficiency_assessment = "Good - minor optimizations possible"
436
+ elif analytics.cache_efficiency_score > 40:
437
+ efficiency_assessment = "Fair - optimization recommended"
438
+ else:
439
+ efficiency_assessment = "Poor - needs immediate optimization"
440
+
441
+ table.add_row(
442
+ "Efficiency Score",
443
+ f"{analytics.cache_efficiency_score:.1f}/100",
444
+ efficiency_assessment,
445
+ )
446
+ table.add_row(
447
+ "Avg Response Time",
448
+ f"{analytics.avg_response_time_ms:.1f}ms",
449
+ "Fast" if analytics.avg_response_time_ms < 10 else "Slow",
450
+ )
451
+ table.add_row(
452
+ "Memory Usage",
453
+ f"{analytics.cache_size_mb:.1f} MB",
454
+ "Optimal" if analytics.cache_size_mb < 50 else "High",
455
+ )
456
+ table.add_row(
457
+ "Data Freshness",
458
+ f"{analytics.oldest_entry_age_hours:.1f}h",
459
+ "Fresh" if analytics.oldest_entry_age_hours < 24 else "Stale",
460
+ )
461
+
462
+ return table
463
+
464
+ def _create_insights_panel(self, analytics: CacheAnalytics) -> Panel | None:
465
+ """Create performance insights panel."""
466
+ insights = []
467
+
468
+ if analytics.hit_rate_percent > 80:
469
+ insights.append("🚀 Excellent cache performance!")
470
+ elif analytics.hit_rate_percent > 60:
471
+ insights.append("✅ Good cache performance")
472
+ elif analytics.hit_rate_percent > 30:
473
+ insights.append("⚠️ Moderate cache performance - consider warming")
474
+ else:
475
+ insights.append("❌ Poor cache performance - optimization needed")
476
+
477
+ if analytics.cache_size_mb > 100:
478
+ insights.append(
479
+ f"💾 Large cache size ({analytics.cache_size_mb:.1f}MB) - consider cleanup"
480
+ )
481
+
482
+ if analytics.cache_efficiency_score < 50:
483
+ insights.append("🔧 Low efficiency score - run --cache-optimize")
484
+
485
+ if not insights:
486
+ return None
487
+
488
+ insights_text = "\\n".join(insights)
489
+ return Panel(
490
+ insights_text,
491
+ title="💡 Performance Insights",
492
+ border_style="blue",
493
+ padding=(1, 2),
494
+ )
495
+
496
+ def _generate_optimization_suggestions(
497
+ self, analytics: CacheAnalytics
498
+ ) -> list[CacheOptimizationSuggestion]:
499
+ """Generate cache optimization suggestions."""
500
+ suggestions = []
501
+
502
+ # Hit rate optimization
503
+ if analytics.hit_rate_percent < 60:
504
+ suggestions.append(
505
+ CacheOptimizationSuggestion(
506
+ type="warming",
507
+ priority="high",
508
+ description="Low hit rate detected - warm frequently used caches",
509
+ estimated_benefit="30-50% performance improvement",
510
+ action_required="Run --cache-warm",
511
+ )
512
+ )
513
+
514
+ # Size optimization
515
+ if analytics.cache_size_mb > 100:
516
+ suggestions.append(
517
+ CacheOptimizationSuggestion(
518
+ type="eviction",
519
+ priority="medium",
520
+ description="Large cache size - implement smart eviction",
521
+ estimated_benefit="Reduced memory usage",
522
+ action_required="Configure TTL and LRU policies",
523
+ )
524
+ )
525
+
526
+ # Efficiency optimization
527
+ if analytics.cache_efficiency_score < 70:
528
+ suggestions.append(
529
+ CacheOptimizationSuggestion(
530
+ type="ttl_tuning",
531
+ priority="medium",
532
+ description="Optimize cache TTL settings for better efficiency",
533
+ estimated_benefit="Improved hit rates and freshness",
534
+ action_required="Analyze access patterns and adjust TTL",
535
+ )
536
+ )
537
+
538
+ return suggestions
539
+
540
+ def _create_suggestions_panel(
541
+ self, suggestions: list[CacheOptimizationSuggestion]
542
+ ) -> Panel:
543
+ """Create optimization suggestions panel."""
544
+ if not suggestions:
545
+ return Panel(
546
+ "✨ Cache is well-optimized! No suggestions at this time.",
547
+ title="🎯 Optimization Suggestions",
548
+ border_style="green",
549
+ )
550
+
551
+ suggestion_lines = []
552
+ for i, suggestion in enumerate(suggestions, 1):
553
+ priority_emoji = (
554
+ "🔴"
555
+ if suggestion.priority == "high"
556
+ else "🟡"
557
+ if suggestion.priority == "medium"
558
+ else "🟢"
559
+ )
560
+ suggestion_lines.append(
561
+ f"{priority_emoji} {suggestion.description}\\n"
562
+ f" 💡 {suggestion.estimated_benefit}\\n"
563
+ f" ⚡ {suggestion.action_required}"
564
+ )
565
+
566
+ suggestions_text = "\\n\\n".join(suggestion_lines)
567
+ return Panel(
568
+ suggestions_text,
569
+ title="🎯 Optimization Suggestions",
570
+ border_style="yellow",
571
+ padding=(1, 2),
572
+ )
573
+
574
+ def _show_cache_directory_info(self, console: Console) -> None:
575
+ """Show enhanced cache directory information."""
576
+ if self.cache.enable_disk_cache and self.cache.cache_dir:
577
+ cache_dir = self.cache.cache_dir
578
+ cache_dir_info = f"📁 Cache Directory: {cache_dir}"
579
+
580
+ if cache_dir.exists():
581
+ cache_files = list[t.Any](cache_dir.rglob("*.cache"))
582
+ disk_files_count = len(cache_files)
583
+
584
+ # Calculate disk usage
585
+ total_size = sum(f.stat().st_size for f in cache_files if f.exists())
586
+ size_mb = total_size / (1024 * 1024)
587
+
588
+ cache_dir_info += f" ({disk_files_count} files, {size_mb:.2f} MB)"
589
+
590
+ # Show file age info
591
+ if cache_files:
592
+ newest_file = max(cache_files, key=lambda f: f.stat().st_mtime)
593
+ oldest_file = min(cache_files, key=lambda f: f.stat().st_mtime)
594
+
595
+ now = datetime.now().timestamp()
596
+ newest_age = (now - newest_file.stat().st_mtime) / 3600 # hours
597
+ oldest_age = (now - oldest_file.stat().st_mtime) / 3600 # hours
598
+
599
+ cache_dir_info += f"\\n 📊 File ages: {newest_age:.1f}h (newest) to {oldest_age:.1f}h (oldest)"
600
+
601
+ console.print()
602
+ console.print(cache_dir_info)
603
+
604
+ def _warm_hook_results_cache(self) -> None:
605
+ """Warm hook results cache with common operations."""
606
+ # Simplified - would implement actual hook result caching
607
+ pass
608
+
609
+ def _warm_file_hashes_cache(self) -> None:
610
+ """Warm file hashes cache with project files."""
611
+ # Simplified - would implement actual file hash caching
612
+ pass
613
+
614
+ def _warm_agent_decisions_cache(self) -> None:
615
+ """Warm agent decisions cache with common patterns."""
616
+ # Simplified - would implement actual agent decision caching
617
+ pass
618
+
619
+ def _warm_test_results_cache(self) -> None:
620
+ """Warm test results cache with recent test data."""
621
+ # Simplified - would implement actual test result caching
622
+ pass
623
+
624
+ def _apply_optimization_suggestion(
625
+ self, suggestion: CacheOptimizationSuggestion
626
+ ) -> bool:
627
+ """Apply an optimization suggestion."""
628
+ # Simplified - would implement actual optimization logic
629
+ return True
630
+
631
+
632
+ # Enhanced CLI command handlers
633
+ def handle_clear_cache_enhanced(console: Console, selective: bool = False) -> None:
634
+ """Enhanced cache clearing handler."""
635
+ handler = EnhancedCacheHandlers()
636
+ handler.handle_clear_cache(console, selective=selective)
637
+
638
+
639
+ def handle_cache_stats_enhanced(console: Console, detailed: bool = False) -> None:
640
+ """Enhanced cache statistics handler."""
641
+ handler = EnhancedCacheHandlers()
642
+ handler.handle_cache_stats(console, detailed=detailed)
643
+
644
+
645
+ def handle_cache_warm(console: Console, operations: list[str] | None = None) -> None:
646
+ """Cache warming handler."""
647
+ handler = EnhancedCacheHandlers()
648
+ handler.handle_cache_warm(console, target_operations=operations)
649
+
650
+
651
+ def handle_cache_optimize(console: Console) -> None:
652
+ """Cache optimization handler."""
653
+ handler = EnhancedCacheHandlers()
654
+ handler.handle_cache_optimize(console)
655
+
656
+
657
+ def _handle_cache_commands_enhanced(
658
+ clear_cache: bool,
659
+ cache_stats: bool,
660
+ cache_warm: bool,
661
+ cache_optimize: bool,
662
+ selective_clear: bool,
663
+ detailed_stats: bool,
664
+ console: Console,
665
+ ) -> bool:
666
+ """Enhanced cache command handler with new options."""
667
+ if clear_cache:
668
+ handle_clear_cache_enhanced(console, selective=selective_clear)
669
+ return True
670
+
671
+ if cache_stats:
672
+ handle_cache_stats_enhanced(console, detailed=detailed_stats)
673
+ return True
674
+
675
+ if cache_warm:
676
+ handle_cache_warm(console)
677
+ return True
678
+
679
+ if cache_optimize:
680
+ handle_cache_optimize(console)
681
+ return True
682
+
683
+ return False