delta-cube 0.5.0__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.
Files changed (54) hide show
  1. delta_cube/__init__.py +10 -0
  2. delta_cube/__main__.py +15 -0
  3. delta_cube/config.py +23 -0
  4. delta_cube/cube/__init__.py +34 -0
  5. delta_cube/cube/advisor.py +385 -0
  6. delta_cube/cube/clones.py +364 -0
  7. delta_cube/cube/clustering.py +498 -0
  8. delta_cube/cube/code_point.py +318 -0
  9. delta_cube/cube/contracts.py +560 -0
  10. delta_cube/cube/cube.py +1191 -0
  11. delta_cube/cube/debt.py +489 -0
  12. delta_cube/cube/delta.py +287 -0
  13. delta_cube/cube/drift.py +338 -0
  14. delta_cube/cube/features/__init__.py +23 -0
  15. delta_cube/cube/features/lexical.py +319 -0
  16. delta_cube/cube/features/semantic.py +394 -0
  17. delta_cube/cube/features/structural.py +461 -0
  18. delta_cube/cube/features/temporal.py +359 -0
  19. delta_cube/cube/graph.py +503 -0
  20. delta_cube/cube/review.py +1079 -0
  21. delta_cube/cube/smells.py +485 -0
  22. delta_cube/cube/suggestions.py +520 -0
  23. delta_cube/cube/surface.py +307 -0
  24. delta_cube/cube/tension.py +561 -0
  25. delta_cube/cube/visualizations/__init__.py +21 -0
  26. delta_cube/cube/visualizations/architecture.py +632 -0
  27. delta_cube/cube/visualizations/heatmap.py +523 -0
  28. delta_cube/cube/visualizations/matrix.py +463 -0
  29. delta_cube/cube/visualizations/timeline.py +504 -0
  30. delta_cube/cube/waves.py +358 -0
  31. delta_cube/db/__init__.py +17 -0
  32. delta_cube/db/analysis_store.py +221 -0
  33. delta_cube/db/database.py +109 -0
  34. delta_cube/db/projects.py +74 -0
  35. delta_cube/db/schema.py +183 -0
  36. delta_cube/server.py +25 -0
  37. delta_cube/tools/__init__.py +30 -0
  38. delta_cube/tools/analysis.py +419 -0
  39. delta_cube/tools/contracts.py +53 -0
  40. delta_cube/tools/core.py +260 -0
  41. delta_cube/tools/deltas.py +147 -0
  42. delta_cube/tools/review.py +194 -0
  43. delta_cube/tools/search.py +269 -0
  44. delta_cube/tools/visualizations.py +157 -0
  45. delta_cube/utils/__init__.py +26 -0
  46. delta_cube/utils/errors.py +53 -0
  47. delta_cube/utils/logger.py +24 -0
  48. delta_cube/visualization/__init__.py +9 -0
  49. delta_cube/visualization/html_export.py +467 -0
  50. delta_cube-0.5.0.dist-info/METADATA +161 -0
  51. delta_cube-0.5.0.dist-info/RECORD +54 -0
  52. delta_cube-0.5.0.dist-info/WHEEL +4 -0
  53. delta_cube-0.5.0.dist-info/entry_points.txt +2 -0
  54. delta_cube-0.5.0.dist-info/licenses/LICENSE +21 -0
delta_cube/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """DeltaCodeCube - Multi-dimensional code indexing for MCP.
2
+
3
+ Represent code as points in 63D feature space for similarity search,
4
+ impact analysis, and change detection.
5
+ """
6
+
7
+ __version__ = "0.5.0"
8
+ __author__ = "Juan Pablo Diaz"
9
+
10
+ __all__ = ["__version__"]
delta_cube/__main__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Entry point for deltacodecube when run with uvx."""
2
+
3
+ import sys
4
+
5
+
6
+ def main() -> int:
7
+ """Run the DeltaCodeCube MCP server."""
8
+ from delta_cube.server import mcp
9
+
10
+ mcp.run()
11
+ return 0
12
+
13
+
14
+ if __name__ == "__main__":
15
+ sys.exit(main())
delta_cube/config.py ADDED
@@ -0,0 +1,23 @@
1
+ """Configuration for DeltaCodeCube (vendored inside jig)."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ # Unify DCC state under jig's XDG data dir. Override with DCC_DATA_DIR env
7
+ # if you need a separate location (e.g. a shared team DB).
8
+ _DEFAULT_DATA_DIR = Path.home() / ".local" / "share" / "jig"
9
+ DATA_DIR = Path(os.environ.get("DCC_DATA_DIR", _DEFAULT_DATA_DIR))
10
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
11
+
12
+ # Database path
13
+ DB_PATH = DATA_DIR / "dcc.db"
14
+
15
+ # Default chunk settings
16
+ DEFAULT_CHUNK_SIZE = 2000 # words
17
+ DEFAULT_OVERLAP = 100 # words
18
+
19
+ # Supported formats
20
+ SUPPORTED_FORMATS = {"txt", "md", "pdf", "epub", "html", "code"}
21
+
22
+ # Logging
23
+ LOG_LEVEL = os.environ.get("BIGCONTEXT_LOG_LEVEL", "INFO")
@@ -0,0 +1,34 @@
1
+ """
2
+ DeltaCodeCube - Sistema de indexación multidimensional para código.
3
+
4
+ Representa código como puntos en espacio 3D (Lexical, Structural, Semantic)
5
+ para búsqueda multidimensional y detección de impacto de cambios.
6
+ """
7
+
8
+ from delta_cube.cube.code_point import CodePoint
9
+ from delta_cube.cube.contracts import Contract, ContractDetector
10
+ from delta_cube.cube.cube import DeltaCodeCube
11
+ from delta_cube.cube.delta import Delta, DeltaTracker, create_delta
12
+ from delta_cube.cube.tension import Tension, TensionDetector
13
+ from delta_cube.cube.suggestions import (
14
+ ChangeAnalysis,
15
+ SuggestionGenerator,
16
+ analyze_change_type,
17
+ extract_relevant_snippets,
18
+ )
19
+
20
+ __all__ = [
21
+ "ChangeAnalysis",
22
+ "CodePoint",
23
+ "Contract",
24
+ "ContractDetector",
25
+ "Delta",
26
+ "DeltaCodeCube",
27
+ "DeltaTracker",
28
+ "SuggestionGenerator",
29
+ "Tension",
30
+ "TensionDetector",
31
+ "analyze_change_type",
32
+ "create_delta",
33
+ "extract_relevant_snippets",
34
+ ]
@@ -0,0 +1,385 @@
1
+ """
2
+ Refactoring Advisor for DeltaCodeCube.
3
+
4
+ Combines all analysis (graph, smells, clustering, tensions) to provide
5
+ actionable refactoring suggestions prioritized by impact and effort.
6
+
7
+ Suggestion types:
8
+ 1. Split: Divide a large file into smaller ones
9
+ 2. Merge: Combine related small files
10
+ 3. Move: Relocate file to better module
11
+ 4. Extract: Pull out shared code into utility
12
+ 5. Stabilize: Add protection to critical interfaces
13
+ 6. Remove: Delete dead code
14
+ 7. Decouple: Break circular or tight dependencies
15
+ """
16
+
17
+ import sqlite3
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+
23
+ from delta_cube.cube.graph import DependencyGraph
24
+ from delta_cube.cube.smells import SmellDetector
25
+ from delta_cube.cube.clustering import SemanticClustering
26
+ from delta_cube.utils.logger import get_logger
27
+
28
+ logger = get_logger(__name__)
29
+
30
+
31
+ @dataclass
32
+ class RefactoringSuggestion:
33
+ """A refactoring suggestion."""
34
+ action: str # split, merge, move, extract, stabilize, remove, decouple
35
+ priority: str # critical, high, medium, low
36
+ impact: str # high, medium, low
37
+ effort: str # high, medium, low
38
+ target_files: list[str]
39
+ description: str
40
+ rationale: str
41
+ steps: list[str]
42
+ metrics: dict[str, Any]
43
+
44
+ def to_dict(self) -> dict[str, Any]:
45
+ """Convert to dictionary."""
46
+ return {
47
+ "action": self.action,
48
+ "priority": self.priority,
49
+ "impact": self.impact,
50
+ "effort": self.effort,
51
+ "target_files": self.target_files,
52
+ "description": self.description,
53
+ "rationale": self.rationale,
54
+ "steps": self.steps,
55
+ "metrics": self.metrics,
56
+ }
57
+
58
+
59
+ class RefactoringAdvisor:
60
+ """
61
+ Generates refactoring suggestions based on comprehensive analysis.
62
+ """
63
+
64
+ def __init__(self, conn: sqlite3.Connection):
65
+ """Initialize with database connection."""
66
+ self.conn = conn
67
+ self.suggestions: list[RefactoringSuggestion] = []
68
+
69
+ # Run all analyses
70
+ self.graph = DependencyGraph(conn)
71
+ self.smell_detector = SmellDetector(conn)
72
+ self.clustering = SemanticClustering(conn)
73
+
74
+ def analyze(self) -> list[RefactoringSuggestion]:
75
+ """
76
+ Run comprehensive analysis and generate suggestions.
77
+
78
+ Returns:
79
+ List of prioritized refactoring suggestions.
80
+ """
81
+ self.suggestions = []
82
+
83
+ # Build graph and compute metrics
84
+ self.graph.build_graph()
85
+ self.graph.compute_pagerank()
86
+ self.graph.compute_hits()
87
+ self.graph.compute_betweenness()
88
+
89
+ # Detect smells
90
+ smells = self.smell_detector.detect_all()
91
+
92
+ # Run clustering
93
+ self.clustering.load_data()
94
+ clustering_result = self.clustering.cluster()
95
+
96
+ # Generate suggestions from each source
97
+ self._suggest_from_smells(smells)
98
+ self._suggest_from_clustering(clustering_result)
99
+ self._suggest_from_graph()
100
+ self._suggest_from_tensions()
101
+
102
+ # Deduplicate and prioritize
103
+ self._deduplicate()
104
+ self._prioritize()
105
+
106
+ return self.suggestions
107
+
108
+ def _suggest_from_smells(self, smells: list) -> None:
109
+ """Generate suggestions from code smells."""
110
+ for smell in smells:
111
+ if smell.smell_type == "god_file":
112
+ self.suggestions.append(RefactoringSuggestion(
113
+ action="split",
114
+ priority="high" if smell.severity == "critical" else "medium",
115
+ impact="high",
116
+ effort="high",
117
+ target_files=[smell.file_name],
118
+ description=f"Split {smell.file_name} into smaller, focused modules",
119
+ rationale=smell.description,
120
+ steps=[
121
+ f"1. Analyze {smell.file_name} to identify distinct responsibilities",
122
+ "2. Group related functions/classes together",
123
+ "3. Create new files for each responsibility group",
124
+ "4. Update imports in dependent files",
125
+ "5. Run tests to verify functionality",
126
+ ],
127
+ metrics=smell.metrics,
128
+ ))
129
+
130
+ elif smell.smell_type == "circular_dependency":
131
+ self.suggestions.append(RefactoringSuggestion(
132
+ action="decouple",
133
+ priority="high",
134
+ impact="medium",
135
+ effort="medium",
136
+ target_files=[smell.file_name],
137
+ description=f"Break circular dependency: {smell.file_name}",
138
+ rationale=smell.description,
139
+ steps=[
140
+ "1. Identify shared functionality causing the cycle",
141
+ "2. Extract shared code into a new utility module",
142
+ "3. Have both files import from the new module",
143
+ "4. Remove direct imports between the cyclic files",
144
+ ],
145
+ metrics=smell.metrics,
146
+ ))
147
+
148
+ elif smell.smell_type == "feature_envy":
149
+ self.suggestions.append(RefactoringSuggestion(
150
+ action="move",
151
+ priority="low",
152
+ impact="low",
153
+ effort="low",
154
+ target_files=[smell.file_name],
155
+ description=f"Consider moving {smell.file_name} to '{smell.metrics.get('dominant_module', 'target')}' module",
156
+ rationale=smell.description,
157
+ steps=[
158
+ f"1. Review if {smell.file_name} logically belongs to the other module",
159
+ "2. If yes, move the file to the appropriate directory",
160
+ "3. Update all import paths",
161
+ ],
162
+ metrics=smell.metrics,
163
+ ))
164
+
165
+ elif smell.smell_type == "dead_code_candidate":
166
+ self.suggestions.append(RefactoringSuggestion(
167
+ action="remove",
168
+ priority="low",
169
+ impact="low",
170
+ effort="low",
171
+ target_files=[smell.file_name],
172
+ description=f"Verify and potentially remove {smell.file_name}",
173
+ rationale=smell.description,
174
+ steps=[
175
+ f"1. Search codebase for any references to {smell.file_name}",
176
+ "2. Check if it's an entry point or CLI script",
177
+ "3. If truly unused, archive or delete the file",
178
+ ],
179
+ metrics=smell.metrics,
180
+ ))
181
+
182
+ elif smell.smell_type == "unstable_interface":
183
+ self.suggestions.append(RefactoringSuggestion(
184
+ action="stabilize",
185
+ priority="high",
186
+ impact="high",
187
+ effort="medium",
188
+ target_files=[smell.file_name],
189
+ description=f"Stabilize the interface of {smell.file_name}",
190
+ rationale=smell.description,
191
+ steps=[
192
+ "1. Document the public API clearly",
193
+ "2. Add comprehensive tests for the interface",
194
+ "3. Consider versioning or deprecation strategy",
195
+ "4. Extract volatile parts to separate files",
196
+ ],
197
+ metrics=smell.metrics,
198
+ ))
199
+
200
+ elif smell.smell_type == "hub_overload":
201
+ self.suggestions.append(RefactoringSuggestion(
202
+ action="split",
203
+ priority="medium",
204
+ impact="medium",
205
+ effort="medium",
206
+ target_files=[smell.file_name],
207
+ description=f"Reduce dependencies in {smell.file_name}",
208
+ rationale=smell.description,
209
+ steps=[
210
+ "1. Group imports by functionality",
211
+ "2. Split file into smaller files with focused imports",
212
+ "3. Use lazy imports for optional dependencies",
213
+ ],
214
+ metrics=smell.metrics,
215
+ ))
216
+
217
+ def _suggest_from_clustering(self, result) -> None:
218
+ """Generate suggestions from clustering analysis."""
219
+ # Suggest moves for misclassified files
220
+ for misclassified in result.misclassified:
221
+ self.suggestions.append(RefactoringSuggestion(
222
+ action="move",
223
+ priority="low",
224
+ impact="low",
225
+ effort="low",
226
+ target_files=[misclassified["name"]],
227
+ description=f"Consider reorganizing {misclassified['name']}",
228
+ rationale=f"This file is {misclassified['improvement']} to cluster "
229
+ f"{misclassified['suggested_cluster']} than its current cluster",
230
+ steps=[
231
+ "1. Review the file's actual purpose",
232
+ "2. Compare with files in the suggested cluster",
233
+ "3. Move if it logically fits better there",
234
+ ],
235
+ metrics={
236
+ "current_cluster": misclassified["current_cluster"],
237
+ "suggested_cluster": misclassified["suggested_cluster"],
238
+ "improvement": misclassified["improvement"],
239
+ },
240
+ ))
241
+
242
+ # Suggest merges for small clusters with similar files
243
+ small_clusters = [c for c in result.clusters if c.size <= 2]
244
+ for cluster in small_clusters:
245
+ if cluster.size == 1:
246
+ self.suggestions.append(RefactoringSuggestion(
247
+ action="merge",
248
+ priority="low",
249
+ impact="low",
250
+ effort="low",
251
+ target_files=[f["name"] for f in cluster.files],
252
+ description=f"Isolated file: {cluster.files[0]['name']}",
253
+ rationale="This file forms its own cluster - it may be an outlier "
254
+ "that should be merged with related code",
255
+ steps=[
256
+ "1. Review the file's functionality",
257
+ "2. Find the most similar existing file",
258
+ "3. Merge if functionality overlaps",
259
+ ],
260
+ metrics={"cluster_size": 1},
261
+ ))
262
+
263
+ def _suggest_from_graph(self) -> None:
264
+ """Generate suggestions from graph analysis."""
265
+ # Find critical bridges
266
+ for node in self.graph.nodes.values():
267
+ if node.betweenness > 0.15:
268
+ self.suggestions.append(RefactoringSuggestion(
269
+ action="extract",
270
+ priority="medium",
271
+ impact="high",
272
+ effort="high",
273
+ target_files=[node.name],
274
+ description=f"Extract shared utilities from {node.name}",
275
+ rationale=f"This file is a critical bridge (betweenness: {node.betweenness:.2f}). "
276
+ "It connects many parts of the codebase.",
277
+ steps=[
278
+ "1. Identify what makes this file a bridge",
279
+ "2. Extract commonly used utilities to separate files",
280
+ "3. Reduce the file's centrality by distributing functionality",
281
+ ],
282
+ metrics={
283
+ "betweenness": node.betweenness,
284
+ "in_degree": node.in_degree,
285
+ "out_degree": node.out_degree,
286
+ },
287
+ ))
288
+
289
+ def _suggest_from_tensions(self) -> None:
290
+ """Generate suggestions from active tensions."""
291
+ from delta_cube.cube.tension import TensionDetector
292
+
293
+ detector = TensionDetector(self.conn)
294
+ tensions = detector.get_tensions(status="detected", limit=20)
295
+
296
+ for tension in tensions:
297
+ if tension.tension_percent > 0.25:
298
+ self.suggestions.append(RefactoringSuggestion(
299
+ action="stabilize",
300
+ priority="high",
301
+ impact="high",
302
+ effort="medium",
303
+ target_files=[Path(tension.callee_path).name, Path(tension.caller_path).name],
304
+ description=f"Resolve tension between {Path(tension.callee_path).name} "
305
+ f"and {Path(tension.caller_path).name}",
306
+ rationale=f"Recent changes caused {tension.tension_percent:.0%} deviation "
307
+ f"from baseline distance",
308
+ steps=[
309
+ f"1. Review recent changes to {Path(tension.callee_path).name}",
310
+ f"2. Check if {Path(tension.caller_path).name} needs updates",
311
+ "3. Run tests to verify compatibility",
312
+ "4. Mark tension as resolved when fixed",
313
+ ],
314
+ metrics={
315
+ "tension_percent": tension.tension_percent,
316
+ "baseline_distance": tension.baseline_distance,
317
+ "current_distance": tension.current_distance,
318
+ },
319
+ ))
320
+
321
+ def _deduplicate(self) -> None:
322
+ """Remove duplicate suggestions for the same file."""
323
+ seen = set()
324
+ unique = []
325
+
326
+ for suggestion in self.suggestions:
327
+ key = (suggestion.action, tuple(sorted(suggestion.target_files)))
328
+ if key not in seen:
329
+ seen.add(key)
330
+ unique.append(suggestion)
331
+
332
+ self.suggestions = unique
333
+
334
+ def _prioritize(self) -> None:
335
+ """Sort suggestions by priority."""
336
+ priority_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
337
+ self.suggestions.sort(key=lambda s: (priority_order.get(s.priority, 4), s.action))
338
+
339
+
340
+ def get_refactoring_suggestions(
341
+ conn: sqlite3.Connection,
342
+ summary_only: bool = False,
343
+ limit: int = 50,
344
+ ) -> dict[str, Any]:
345
+ """
346
+ Get prioritized refactoring suggestions.
347
+
348
+ Args:
349
+ conn: Database connection.
350
+ summary_only: When True, return only aggregate counts without the full
351
+ ``suggestions`` list. Produces a much smaller payload.
352
+ limit: Maximum number of suggestions to include when ``summary_only``
353
+ is False (default 50). Suggestions are already sorted by priority,
354
+ so this keeps the highest-priority items.
355
+
356
+ Returns:
357
+ Dictionary with suggestions and summary.
358
+ """
359
+ advisor = RefactoringAdvisor(conn)
360
+ suggestions = advisor.analyze()
361
+
362
+ # Group by action type
363
+ by_action: dict[str, list] = {}
364
+ by_priority: dict[str, int] = {}
365
+
366
+ for s in suggestions:
367
+ by_action.setdefault(s.action, []).append(s.to_dict())
368
+ by_priority[s.priority] = by_priority.get(s.priority, 0) + 1
369
+
370
+ result: dict[str, Any] = {
371
+ "total_suggestions": len(suggestions),
372
+ "by_action": {k: len(v) for k, v in by_action.items()},
373
+ "by_priority": by_priority,
374
+ }
375
+
376
+ if summary_only:
377
+ result["truncated"] = True
378
+ result["limit"] = limit
379
+ else:
380
+ result["suggestions"] = [s.to_dict() for s in suggestions[:limit]]
381
+ if len(suggestions) > limit:
382
+ result["truncated"] = True
383
+ result["limit"] = limit
384
+
385
+ return result