repodna-engine 1.0.1__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 (173) hide show
  1. repodna/__init__.py +3 -0
  2. repodna/__main__.py +10 -0
  3. repodna/advisor/__init__.py +17 -0
  4. repodna/advisor/engine.py +502 -0
  5. repodna/advisor/models.py +101 -0
  6. repodna/agent/__init__.py +87 -0
  7. repodna/agent/context.py +558 -0
  8. repodna/agent/deltas.py +198 -0
  9. repodna/agent/evidence.py +134 -0
  10. repodna/agent/expansion.py +447 -0
  11. repodna/agent/localization.py +518 -0
  12. repodna/agent/models.py +695 -0
  13. repodna/agent/patch.py +378 -0
  14. repodna/agent/postflight.py +278 -0
  15. repodna/agent/preflight.py +336 -0
  16. repodna/agent/ranking.py +318 -0
  17. repodna/agent/repo_map.py +392 -0
  18. repodna/agent/safety.py +111 -0
  19. repodna/agent/service.py +574 -0
  20. repodna/agent/sessions.py +264 -0
  21. repodna/agent/task.py +660 -0
  22. repodna/agent/telemetry.py +101 -0
  23. repodna/agent/token_budget.py +231 -0
  24. repodna/api/__init__.py +1 -0
  25. repodna/api/agent_routes.py +248 -0
  26. repodna/api/app.py +2904 -0
  27. repodna/benchmarks/__init__.py +29 -0
  28. repodna/benchmarks/baselines.py +126 -0
  29. repodna/benchmarks/budget_bench.py +162 -0
  30. repodna/benchmarks/engine.py +418 -0
  31. repodna/benchmarks/evaluator.py +310 -0
  32. repodna/benchmarks/metrics.py +206 -0
  33. repodna/benchmarks/models.py +194 -0
  34. repodna/benchmarks/scalability.py +166 -0
  35. repodna/brain/__init__.py +46 -0
  36. repodna/brain/evidence.py +276 -0
  37. repodna/brain/extractor.py +1207 -0
  38. repodna/brain/indexer.py +766 -0
  39. repodna/brain/models.py +275 -0
  40. repodna/brain/multilang_extractors.py +889 -0
  41. repodna/brain/retrieval.py +469 -0
  42. repodna/brain/tracer.py +203 -0
  43. repodna/cli/__init__.py +1 -0
  44. repodna/cli/__main__.py +10 -0
  45. repodna/cli/agent_cmd.py +228 -0
  46. repodna/cli/installer.py +590 -0
  47. repodna/cli/main.py +2173 -0
  48. repodna/cli/plugin_cmd.py +130 -0
  49. repodna/cli/workspace_cmd.py +211 -0
  50. repodna/context/__init__.py +9 -0
  51. repodna/context/builder.py +379 -0
  52. repodna/context/models.py +133 -0
  53. repodna/contract/__init__.py +39 -0
  54. repodna/contract/evaluator.py +318 -0
  55. repodna/contract/loader.py +260 -0
  56. repodna/contract/models.py +185 -0
  57. repodna/core/__init__.py +1 -0
  58. repodna/core/analyzer.py +1424 -0
  59. repodna/diff/__init__.py +35 -0
  60. repodna/diff/engine.py +332 -0
  61. repodna/diff/models.py +117 -0
  62. repodna/diff/snapshot.py +248 -0
  63. repodna/ecosystem/__init__.py +27 -0
  64. repodna/ecosystem/contracts.py +129 -0
  65. repodna/ecosystem/doctor.py +253 -0
  66. repodna/git_insights/__init__.py +1 -0
  67. repodna/git_insights/analyzer.py +273 -0
  68. repodna/graph/__init__.py +1 -0
  69. repodna/graph/engine.py +562 -0
  70. repodna/guardian/__init__.py +17 -0
  71. repodna/guardian/engine.py +369 -0
  72. repodna/guardian/models.py +104 -0
  73. repodna/history/__init__.py +40 -0
  74. repodna/history/cache.py +240 -0
  75. repodna/history/diff.py +394 -0
  76. repodna/history/engine.py +557 -0
  77. repodna/history/evidence.py +160 -0
  78. repodna/history/models.py +258 -0
  79. repodna/history/timeline.py +164 -0
  80. repodna/intelligence/__init__.py +33 -0
  81. repodna/intelligence/models.py +165 -0
  82. repodna/intelligence/service.py +570 -0
  83. repodna/live/__init__.py +94 -0
  84. repodna/live/alerts.py +443 -0
  85. repodna/live/coordinator.py +351 -0
  86. repodna/live/diff.py +444 -0
  87. repodna/live/events.py +471 -0
  88. repodna/live/filtering.py +329 -0
  89. repodna/live/history.py +637 -0
  90. repodna/live/models.py +505 -0
  91. repodna/live/observer.py +653 -0
  92. repodna/live/reconciliation.py +253 -0
  93. repodna/live/session.py +1547 -0
  94. repodna/mcp/__init__.py +5 -0
  95. repodna/mcp/__main__.py +6 -0
  96. repodna/mcp/agent_tools.py +258 -0
  97. repodna/mcp/server.py +3283 -0
  98. repodna/mcp/workspace_tools.py +200 -0
  99. repodna/parsers/__init__.py +13 -0
  100. repodna/parsers/base.py +126 -0
  101. repodna/parsers/capabilities.py +361 -0
  102. repodna/parsers/project_metadata.py +232 -0
  103. repodna/parsers/resolver.py +621 -0
  104. repodna/parsers/treesitter_parser.py +830 -0
  105. repodna/passport/__init__.py +64 -0
  106. repodna/passport/generator.py +546 -0
  107. repodna/passport/migrator.py +139 -0
  108. repodna/passport/models.py +224 -0
  109. repodna/passport/validator.py +143 -0
  110. repodna/performance/__init__.py +89 -0
  111. repodna/performance/cache.py +1584 -0
  112. repodna/performance/identity.py +341 -0
  113. repodna/performance/incremental.py +317 -0
  114. repodna/performance/models.py +157 -0
  115. repodna/performance/parallel.py +291 -0
  116. repodna/plugins/__init__.py +47 -0
  117. repodna/plugins/evaluator.py +334 -0
  118. repodna/plugins/models.py +113 -0
  119. repodna/plugins/validator.py +256 -0
  120. repodna/quality/__init__.py +91 -0
  121. repodna/quality/complexity.py +352 -0
  122. repodna/quality/config.py +159 -0
  123. repodna/quality/debt.py +73 -0
  124. repodna/quality/duplicates.py +330 -0
  125. repodna/quality/engine.py +282 -0
  126. repodna/quality/impact.py +198 -0
  127. repodna/quality/models.py +427 -0
  128. repodna/quality/rules.py +364 -0
  129. repodna/quality/sarif.py +107 -0
  130. repodna/quality/security_signals.py +278 -0
  131. repodna/quality/test_mapping.py +271 -0
  132. repodna/quality/unused.py +201 -0
  133. repodna/reports/__init__.py +1 -0
  134. repodna/reports/exporter.py +374 -0
  135. repodna/rules/__init__.py +1 -0
  136. repodna/rules/health.py +436 -0
  137. repodna/schemas/__init__.py +1 -0
  138. repodna/schemas/models.py +348 -0
  139. repodna/security/__init__.py +1 -0
  140. repodna/security/safe_yaml.py +81 -0
  141. repodna/security/validators.py +583 -0
  142. repodna/skills/__init__.py +0 -0
  143. repodna/skills/repodna/SKILL.md +59 -0
  144. repodna/skills/repodna/__init__.py +0 -0
  145. repodna/skills/repodna/examples/workflows.md +85 -0
  146. repodna/skills/repodna/references/architecture-rules.md +26 -0
  147. repodna/storage/__init__.py +1 -0
  148. repodna/storage/workspace.py +199 -0
  149. repodna/webui/__init__.py +1 -0
  150. repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
  151. repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
  152. repodna/webui/assets/index-ByZ5e5pe.js +506 -0
  153. repodna/webui/assets/index-CDj3e8hw.css +1 -0
  154. repodna/webui/index.html +21 -0
  155. repodna/workspace/__init__.py +131 -0
  156. repodna/workspace/compatibility.py +317 -0
  157. repodna/workspace/context.py +175 -0
  158. repodna/workspace/contracts.py +369 -0
  159. repodna/workspace/federation.py +411 -0
  160. repodna/workspace/identity.py +202 -0
  161. repodna/workspace/impact.py +111 -0
  162. repodna/workspace/manifest.py +266 -0
  163. repodna/workspace/models.py +461 -0
  164. repodna/workspace/packages.py +494 -0
  165. repodna/workspace/policies.py +142 -0
  166. repodna/workspace/services.py +238 -0
  167. repodna/workspace/topology.py +316 -0
  168. repodna_engine-1.0.1.dist-info/METADATA +129 -0
  169. repodna_engine-1.0.1.dist-info/RECORD +173 -0
  170. repodna_engine-1.0.1.dist-info/WHEEL +5 -0
  171. repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
  172. repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
  173. repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,160 @@
1
+ """Historical Evidence Provider.
2
+
3
+ Provides safe, read-only extraction of code content directly from Git commit history
4
+ without touching the current working tree or filesystem.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ from repodna.brain.evidence import extract_evidence_snippet, normalize_text_newlines
15
+ from repodna.brain.models import StalenessReason
16
+ from repodna.history.models import HistoricalEvidenceItem
17
+ from repodna.security.validators import SecurityValidationError, is_sensitive_relative_path
18
+
19
+ COMMIT_SHA_PATTERN = re.compile(r"^[0-9a-fA-F]{40}$")
20
+ SAFE_POSIX_PATH_PATTERN = re.compile(r"^[a-zA-Z0-9_\-./]+$")
21
+
22
+
23
+ class HistoricalEvidenceProvider:
24
+ """Safe, read-only historical blob reader directly querying Git object database."""
25
+
26
+ def __init__(self, repo_path: Path | str) -> None:
27
+ self.repo_path = Path(repo_path).resolve()
28
+ if not (self.repo_path / ".git").exists():
29
+ raise ValueError(f"Directory '{self.repo_path}' is not a valid Git repository.")
30
+
31
+ def read_historical_file(
32
+ self,
33
+ commit_sha: str,
34
+ file_path: str,
35
+ max_bytes: int = 5 * 1024 * 1024, # 5 MB safety limit
36
+ ) -> str:
37
+ """
38
+ Safely reads the contents of a file at a specific historical commit SHA.
39
+ Guarantees:
40
+ - Commit SHA is validated (40-character hex)
41
+ - File path is strictly POSIX relative with traversal prevention
42
+ - Blob size is checked before retrieval to prevent memory exhaustion
43
+ - Uses argument lists without shell execution
44
+ """
45
+ norm_sha = commit_sha.strip().lower()
46
+ if not COMMIT_SHA_PATTERN.match(norm_sha):
47
+ raise SecurityValidationError(
48
+ "INVALID_COMMIT_SHA", f"Invalid commit SHA: '{commit_sha}'"
49
+ )
50
+
51
+ norm_path = file_path.replace("\\", "/").strip().lstrip("/")
52
+ if (
53
+ not norm_path
54
+ or ".." in norm_path
55
+ or norm_path.startswith("/")
56
+ or (len(norm_path) > 1 and norm_path[1] == ":")
57
+ or not SAFE_POSIX_PATH_PATTERN.match(norm_path)
58
+ ):
59
+ raise SecurityValidationError(
60
+ "INVALID_FILE_PATH", f"Invalid or unsafe historical file path: '{file_path}'"
61
+ )
62
+
63
+ if is_sensitive_relative_path(norm_path):
64
+ raise SecurityValidationError(
65
+ "SENSITIVE_FILE_BLOCKED",
66
+ f"Access to sensitive historical file '{norm_path}' is blocked by security policy.",
67
+ )
68
+
69
+ # 1. Query blob size via git cat-file -s
70
+ size_cmd = ["git", "-C", str(self.repo_path), "cat-file", "-s", f"{norm_sha}:{norm_path}"]
71
+ try:
72
+ size_out = subprocess.check_output(
73
+ size_cmd, stderr=subprocess.PIPE, text=True, timeout=5.0
74
+ ).strip()
75
+ blob_size = int(size_out)
76
+ if blob_size > max_bytes:
77
+ raise SecurityValidationError(
78
+ "MAX_FILE_SIZE_EXCEEDED",
79
+ f"Historical file '{norm_path}' ({blob_size} bytes) exceeds limit of {max_bytes} bytes.",
80
+ )
81
+ except subprocess.CalledProcessError as exc:
82
+ # File might not exist in that commit
83
+ err_msg = (
84
+ exc.stderr
85
+ if isinstance(exc.stderr, str)
86
+ else (exc.stderr or b"").decode("utf-8", "replace")
87
+ )
88
+ raise FileNotFoundError(
89
+ f"File '{norm_path}' not found at commit {norm_sha}: {err_msg.strip()}"
90
+ ) from exc
91
+ except (subprocess.TimeoutExpired, ValueError) as exc:
92
+ raise RuntimeError(
93
+ f"Failed to inspect historical file size for '{norm_path}': {exc}"
94
+ ) from exc
95
+
96
+ # 2. Read blob content via git show <sha>:<path>
97
+ show_cmd = ["git", "-C", str(self.repo_path), "show", f"{norm_sha}:{norm_path}"]
98
+ env = os.environ.copy()
99
+ env["GIT_TERMINAL_PROMPT"] = "0"
100
+ env["GIT_OPTIONAL_LOCKS"] = "0"
101
+
102
+ try:
103
+ proc = subprocess.run(
104
+ show_cmd,
105
+ capture_output=True,
106
+ check=True,
107
+ timeout=10.0,
108
+ env=env,
109
+ )
110
+ return proc.stdout.decode("utf-8", errors="replace")
111
+ except subprocess.CalledProcessError as exc:
112
+ raise FileNotFoundError(
113
+ f"Failed to read historical file '{norm_path}' at commit {norm_sha}"
114
+ ) from exc
115
+ except subprocess.TimeoutExpired as exc:
116
+ raise TimeoutError(
117
+ f"Timed out reading historical file '{norm_path}' at commit {norm_sha}"
118
+ ) from exc
119
+
120
+ def verify_evidence_at_commit(
121
+ self,
122
+ evidence: HistoricalEvidenceItem,
123
+ ) -> tuple[bool, StalenessReason, str]:
124
+ """
125
+ Verifies that a historical evidence citation matches the exact code snippet
126
+ and content hash at its recorded commit.
127
+ """
128
+ try:
129
+ content = self.read_historical_file(evidence.commit_sha, evidence.file_path)
130
+ norm_content = normalize_text_newlines(content)
131
+ lines = norm_content.splitlines()
132
+
133
+ if not lines:
134
+ return False, StalenessReason.FILE_DELETED, "File is empty in historical commit."
135
+
136
+ snippet_now, hash_now = extract_evidence_snippet(
137
+ norm_content, evidence.line_start, evidence.line_end
138
+ )
139
+
140
+ if hash_now == evidence.content_hash:
141
+ return True, StalenessReason.FRESH, "Verified exact match at recorded coordinates."
142
+
143
+ # Check if snippet shifted within file
144
+ if evidence.code_snippet and evidence.code_snippet in norm_content:
145
+ return (
146
+ False,
147
+ StalenessReason.LINE_SHIFT,
148
+ "Exact snippet found at different line coordinates.",
149
+ )
150
+
151
+ return (
152
+ False,
153
+ StalenessReason.CONTENT_CHANGED,
154
+ "Snippet modified or not found at recorded coordinates.",
155
+ )
156
+
157
+ except FileNotFoundError:
158
+ return False, StalenessReason.FILE_DELETED, "File does not exist in recorded commit."
159
+ except Exception as exc:
160
+ return False, StalenessReason.CONTENT_CHANGED, f"Verification error: {exc}"
@@ -0,0 +1,258 @@
1
+ """Typed Pydantic models for RepoDNA Historical Architecture Snapshot Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from datetime import UTC, datetime
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+ from repodna.diff.models import (
13
+ CouplingDeltaItem,
14
+ CoverageDelta,
15
+ CycleChanges,
16
+ DependencyChanges,
17
+ HealthScoreDelta,
18
+ ModuleChanges,
19
+ RuleFindingChanges,
20
+ )
21
+ from repodna.schemas.models import RuleFinding, SeverityLevel
22
+
23
+ SNAPSHOT_SCHEMA_VERSION = "1.0.0"
24
+ CACHE_SCHEMA_VERSION = "1.0.0"
25
+
26
+
27
+ class SnapshotRuntimeMetadata(BaseModel):
28
+ """Runtime execution and cache metadata, excluded from deterministic architectural hashing."""
29
+
30
+ analyzed_at: str
31
+ analysis_duration_ms: float = 0.0
32
+ cache_hit: bool = False
33
+ analyzer_version: str = "0.6.0"
34
+ parser_version: str = "0.26.0"
35
+ config_fingerprint: str = "default-v1"
36
+
37
+
38
+ class HistoricalModuleSummary(BaseModel):
39
+ """Summary of a module (file) in a historical snapshot."""
40
+
41
+ path: str
42
+ name: str
43
+ language: str
44
+ lines_code: int = 0
45
+ fan_in: int = 0
46
+ fan_out: int = 0
47
+ instability: float = 0.0
48
+ is_hub: bool = False
49
+ in_cycle: bool = False
50
+ symbol_count: int = 0
51
+
52
+
53
+ class HistoricalDependencyEdge(BaseModel):
54
+ """Dependency relationship between two modules at a specific historical commit."""
55
+
56
+ source: str
57
+ target: str
58
+ import_names: list[str] = Field(default_factory=list)
59
+ is_dynamic: bool = False
60
+
61
+
62
+ class HistoricalCycle(BaseModel):
63
+ """Architectural cyclic dependency detected in a historical commit."""
64
+
65
+ id: str
66
+ nodes: list[str]
67
+ length: int
68
+ severity: SeverityLevel
69
+ description: str
70
+
71
+
72
+ class HistoricalCouplingMetrics(BaseModel):
73
+ """Fan-in, fan-out, and instability metrics for a module."""
74
+
75
+ fan_in: int = 0
76
+ fan_out: int = 0
77
+ instability: float = 0.0
78
+
79
+
80
+ class HistoricalHealthMetrics(BaseModel):
81
+ """Architecture health metrics and grade for a historical commit."""
82
+
83
+ score: float | None = None
84
+ grade: str = "N/A"
85
+ status: str = "UNKNOWN"
86
+ penalties: dict[str, float] = Field(default_factory=dict)
87
+
88
+
89
+ class HistoricalEvidenceItem(BaseModel):
90
+ """Immutable evidence citation tied to a specific historical Git commit."""
91
+
92
+ evidence_id: str
93
+ commit_sha: str
94
+ file_path: str
95
+ line_start: int
96
+ line_end: int
97
+ evidence_type: str
98
+ symbol_name: str | None = None
99
+ code_snippet: str
100
+ content_hash: str
101
+ support_level: str
102
+ snapshot_identity: str
103
+
104
+
105
+ class HistoricalLanguageSummary(BaseModel):
106
+ """Language breakdown in a historical snapshot."""
107
+
108
+ files_count: int = 0
109
+ lines_code: int = 0
110
+ percentage: float = 0.0
111
+
112
+
113
+ class HistoricalSnapshot(BaseModel):
114
+ """Immutable architectural snapshot of a repository at a specific Git commit SHA."""
115
+
116
+ schema_version: str = SNAPSHOT_SCHEMA_VERSION
117
+ commit_sha: str = Field(description="Full 40-character Git commit SHA.")
118
+ parent_shas: list[str] = Field(default_factory=list, description="Parent commit SHAs.")
119
+ repo_identity: str = Field(description="Canonical repository identity.")
120
+ commit_timestamp: str = Field(description="ISO-8601 commit timestamp.")
121
+ commit_author: str = Field(default="unknown")
122
+ commit_message: str = Field(default="")
123
+
124
+ # Deterministic architectural data
125
+ total_files: int = 0
126
+ total_lines_code: int = 0
127
+ ast_loc_coverage_pct: float = 0.0
128
+
129
+ languages: dict[str, HistoricalLanguageSummary] = Field(default_factory=dict)
130
+ modules: list[HistoricalModuleSummary] = Field(default_factory=list)
131
+ dependencies: list[HistoricalDependencyEdge] = Field(default_factory=list)
132
+ cycles: list[HistoricalCycle] = Field(default_factory=list)
133
+ coupling: dict[str, HistoricalCouplingMetrics] = Field(default_factory=dict)
134
+ health: HistoricalHealthMetrics = Field(default_factory=HistoricalHealthMetrics)
135
+ findings: list[RuleFinding] = Field(default_factory=list)
136
+ evidence: list[HistoricalEvidenceItem] = Field(default_factory=list)
137
+ limitations: list[str] = Field(default_factory=list)
138
+ is_shallow: bool = False
139
+
140
+ # Separated runtime execution metadata
141
+ runtime_metadata: SnapshotRuntimeMetadata = Field(
142
+ default_factory=lambda: SnapshotRuntimeMetadata(
143
+ analyzed_at=datetime.now(UTC).isoformat()
144
+ )
145
+ )
146
+
147
+ # Backwards-compatible fields (synced with runtime_metadata)
148
+ analyzed_at: str = ""
149
+ analyzer_version: str = "0.6.0"
150
+ cache_hit: bool = False
151
+
152
+ def model_post_init(self, __context: Any) -> None:
153
+ if self.runtime_metadata:
154
+ if not self.analyzed_at and self.runtime_metadata.analyzed_at:
155
+ self.analyzed_at = self.runtime_metadata.analyzed_at
156
+ elif self.analyzed_at and not self.runtime_metadata.analyzed_at:
157
+ self.runtime_metadata.analyzed_at = self.analyzed_at
158
+
159
+ if self.cache_hit and not self.runtime_metadata.cache_hit:
160
+ self.runtime_metadata.cache_hit = self.cache_hit
161
+ elif self.runtime_metadata.cache_hit and not self.cache_hit:
162
+ self.cache_hit = self.runtime_metadata.cache_hit
163
+
164
+ if self.analyzer_version:
165
+ self.runtime_metadata.analyzer_version = self.analyzer_version
166
+
167
+ def architectural_fingerprint(self) -> str:
168
+ """
169
+ Computes a deterministic cryptographic SHA-256 fingerprint exclusively from
170
+ architectural properties, unaffected by runtime execution timestamp or cache hits.
171
+ """
172
+ arch_data = {
173
+ "commit_sha": self.commit_sha,
174
+ "parent_shas": sorted(self.parent_shas),
175
+ "repo_identity": self.repo_identity,
176
+ "total_files": self.total_files,
177
+ "total_lines_code": self.total_lines_code,
178
+ "ast_loc_coverage_pct": round(self.ast_loc_coverage_pct, 4),
179
+ "languages": {k: v.model_dump() for k, v in sorted(self.languages.items())},
180
+ "modules": [m.model_dump() for m in sorted(self.modules, key=lambda x: x.path)],
181
+ "dependencies": [
182
+ d.model_dump()
183
+ for d in sorted(self.dependencies, key=lambda x: (x.source, x.target))
184
+ ],
185
+ "cycles": [c.model_dump() for c in sorted(self.cycles, key=lambda x: x.id)],
186
+ "health": self.health.model_dump(),
187
+ "limitations": sorted(self.limitations),
188
+ }
189
+ encoded = json.dumps(arch_data, sort_keys=True, separators=(",", ":")).encode("utf-8")
190
+ return hashlib.sha256(encoded).hexdigest()
191
+
192
+
193
+ class HistoricalDiffResult(BaseModel):
194
+ """Architectural evolution diff between two historical snapshots."""
195
+
196
+ schema_version: str = SNAPSHOT_SCHEMA_VERSION
197
+ base_commit_sha: str
198
+ head_commit_sha: str
199
+ base_timestamp: str
200
+ head_timestamp: str
201
+ time_delta_display: str = ""
202
+
203
+ module_changes: ModuleChanges = Field(default_factory=ModuleChanges)
204
+ dependency_changes: DependencyChanges = Field(default_factory=DependencyChanges)
205
+ cycle_changes: CycleChanges = Field(default_factory=CycleChanges)
206
+ coupling_deltas: list[CouplingDeltaItem] = Field(default_factory=list)
207
+ health_delta: HealthScoreDelta
208
+ coverage_delta: CoverageDelta
209
+ finding_changes: RuleFindingChanges = Field(default_factory=RuleFindingChanges)
210
+
211
+ caveats: list[str] = Field(default_factory=list)
212
+ summary_text: str = ""
213
+
214
+
215
+ class TimelineEntry(BaseModel):
216
+ """A single chronological point in the architectural evolution timeline."""
217
+
218
+ commit_sha: str
219
+ commit_timestamp: str
220
+ commit_author: str
221
+ commit_message: str
222
+ status: str = Field(
223
+ default="success", description="Status of analysis: success, failed, or partial."
224
+ )
225
+ error_message: str | None = None
226
+ total_files: int = 0
227
+ total_lines_code: int = 0
228
+ health_score: float | None = None
229
+ health_grade: str = "N/A"
230
+ cycles_count: int = 0
231
+ modules_count: int = 0
232
+ ast_coverage_pct: float = 0.0
233
+ cache_hit: bool = False
234
+
235
+
236
+ class TimelineResult(BaseModel):
237
+ """Architectural evolution timeline across multiple historical commits."""
238
+
239
+ schema_version: str = SNAPSHOT_SCHEMA_VERSION
240
+ repo_identity: str
241
+ total_commits: int
242
+ successful_commits: int = 0
243
+ failed_commits: int = 0
244
+ missing_commits: list[str] = Field(default_factory=list)
245
+ entries: list[TimelineEntry] = Field(default_factory=list)
246
+ summary_text: str = ""
247
+
248
+
249
+ class CacheEnvelope(BaseModel):
250
+ """On-disk safe serialization envelope with corruption detection."""
251
+
252
+ schema_version: str = CACHE_SCHEMA_VERSION
253
+ cache_key: str
254
+ created_at: str
255
+ commit_sha: str
256
+ analyzer_version: str
257
+ checksum: str
258
+ payload: dict[str, Any]
@@ -0,0 +1,164 @@
1
+ """Historical Architecture Timeline Engine.
2
+
3
+ Traces architectural progression and health evolution across a sequence of Git commits.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import subprocess
9
+ import threading
10
+
11
+ from repodna.history.engine import HistoricalSnapshotEngine
12
+ from repodna.history.models import (
13
+ SNAPSHOT_SCHEMA_VERSION,
14
+ TimelineEntry,
15
+ TimelineResult,
16
+ )
17
+
18
+
19
+ class TimelineEngine:
20
+ """Computes historical architectural progression across commit sequences."""
21
+
22
+ def __init__(self, engine: HistoricalSnapshotEngine) -> None:
23
+ self.engine = engine
24
+
25
+ def get_commit_list(self, limit: int = 30) -> list[str]:
26
+ """Queries Git for the most recent commit SHAs on current HEAD."""
27
+ cmd = [
28
+ "git",
29
+ "-C",
30
+ str(self.engine.repo_path),
31
+ "log",
32
+ f"-n{max(1, min(limit, 200))}",
33
+ "--format=%H",
34
+ ]
35
+ try:
36
+ out = subprocess.check_output(cmd, stderr=subprocess.PIPE, text=True, timeout=10.0)
37
+ return [line.strip() for line in out.splitlines() if line.strip()]
38
+ except Exception:
39
+ return []
40
+
41
+ def build_timeline(
42
+ self,
43
+ commits: list[str] | None = None,
44
+ limit: int = 30,
45
+ cancel_event: threading.Event | None = None,
46
+ ) -> TimelineResult:
47
+ """
48
+ Builds chronological architectural timeline for the specified commits or recent history.
49
+ Uses cached snapshots for lightning-fast incremental retrieval.
50
+ """
51
+ commit_shas = commits or self.get_commit_list(limit=limit)
52
+ # Reverse to chronological order (oldest to newest)
53
+ chronological_shas = list(reversed(commit_shas))
54
+
55
+ entries: list[TimelineEntry] = []
56
+ for sha in chronological_shas:
57
+ if cancel_event is not None and cancel_event.is_set():
58
+ raise InterruptedError("Timeline generation cancelled by user request.")
59
+ try:
60
+ snap = self.engine.create_snapshot(sha, use_cache=True)
61
+ entries.append(
62
+ TimelineEntry(
63
+ commit_sha=snap.commit_sha,
64
+ commit_timestamp=snap.commit_timestamp,
65
+ commit_author=snap.commit_author,
66
+ commit_message=snap.commit_message,
67
+ status="success",
68
+ total_files=snap.total_files,
69
+ total_lines_code=snap.total_lines_code,
70
+ health_score=snap.health.score,
71
+ health_grade=snap.health.grade,
72
+ cycles_count=len(snap.cycles),
73
+ modules_count=len(snap.modules),
74
+ ast_coverage_pct=snap.ast_loc_coverage_pct,
75
+ cache_hit=snap.cache_hit,
76
+ )
77
+ )
78
+ except Exception as exc:
79
+ # Failure is never silently dropped: record explicit failed entry with commit metadata
80
+ author = "unknown"
81
+ iso_ts = ""
82
+ subject = f"Failed to analyze commit: {exc}"
83
+ try:
84
+ cmd = [
85
+ "git",
86
+ "-C",
87
+ str(self.engine.repo_path),
88
+ "log",
89
+ "-1",
90
+ "--format=%an%x00%aI%x00%s",
91
+ sha,
92
+ ]
93
+ raw_meta = subprocess.check_output(
94
+ cmd, stderr=subprocess.PIPE, text=True, timeout=5.0
95
+ ).strip()
96
+ parts = raw_meta.split("\x00")
97
+ if len(parts) >= 3:
98
+ author, iso_ts, subject = parts[0], parts[1], parts[2]
99
+ except Exception:
100
+ pass
101
+
102
+ entries.append(
103
+ TimelineEntry(
104
+ commit_sha=sha,
105
+ commit_timestamp=iso_ts,
106
+ commit_author=author,
107
+ commit_message=subject,
108
+ status="failed",
109
+ error_message=str(exc),
110
+ total_files=0,
111
+ total_lines_code=0,
112
+ health_score=None,
113
+ health_grade="N/A",
114
+ cycles_count=0,
115
+ modules_count=0,
116
+ ast_coverage_pct=0.0,
117
+ cache_hit=False,
118
+ )
119
+ )
120
+
121
+ successful_commits = sum(1 for e in entries if e.status == "success")
122
+ failed_commits = sum(1 for e in entries if e.status == "failed")
123
+ missing_commits = [e.commit_sha for e in entries if e.status == "failed"]
124
+
125
+ summary_text = self._format_timeline_summary(entries)
126
+
127
+ return TimelineResult(
128
+ schema_version=SNAPSHOT_SCHEMA_VERSION,
129
+ repo_identity=self.engine.repo_identity,
130
+ total_commits=len(entries),
131
+ successful_commits=successful_commits,
132
+ failed_commits=failed_commits,
133
+ missing_commits=missing_commits,
134
+ entries=entries,
135
+ summary_text=summary_text,
136
+ )
137
+
138
+ def _format_timeline_summary(self, entries: list[TimelineEntry]) -> str:
139
+ lines = [
140
+ "=" * 84,
141
+ f"RepoDNA Architecture Timeline — {self.engine.repo_identity} ({len(entries)} commits)",
142
+ "=" * 84,
143
+ f"{'COMMIT':<10} | {'DATE':<12} | {'AUTHOR':<16} | {'STATUS':<7} | {'FILES':<6} | {'HEALTH':<7} | {'CYCLES':<6}",
144
+ "-" * 84,
145
+ ]
146
+ for e in entries:
147
+ dt_short = e.commit_timestamp[:10] if e.commit_timestamp else "N/A"
148
+ author_short = e.commit_author[:16]
149
+ status_disp = e.status.upper()
150
+ if e.status == "failed":
151
+ lines.append(
152
+ f"{e.commit_sha[:10]:<10} | {dt_short:<12} | {author_short:<16} | {status_disp:<7} | {'FAIL':<6} | {'N/A':<7} | {'N/A':<6} -> {e.error_message}"
153
+ )
154
+ else:
155
+ health_disp = (
156
+ f"{e.health_score:.1f} ({e.health_grade})"
157
+ if e.health_score is not None
158
+ else "N/A"
159
+ )
160
+ lines.append(
161
+ f"{e.commit_sha[:10]:<10} | {dt_short:<12} | {author_short:<16} | {status_disp:<7} | {e.total_files:<6} | {health_disp:<7} | {e.cycles_count:<6}"
162
+ )
163
+ lines.append("=" * 84)
164
+ return "\n".join(lines)
@@ -0,0 +1,33 @@
1
+ """RepoDNA AI Repository Intelligence Core."""
2
+
3
+ from repodna.intelligence.models import (
4
+ AnalysisCoverageReport,
5
+ ArchitectureFindingsResponse,
6
+ ArchitectureMap,
7
+ ChangeImpactResponse,
8
+ DependencyQueryResponse,
9
+ DependencyTraceItem,
10
+ ModuleDetails,
11
+ ModuleOverviewItem,
12
+ PackageCluster,
13
+ RelevantModuleMatch,
14
+ RelevantModulesResponse,
15
+ RepositoryOverview,
16
+ )
17
+ from repodna.intelligence.service import RepositoryIntelligenceService
18
+
19
+ __all__ = [
20
+ "AnalysisCoverageReport",
21
+ "ArchitectureFindingsResponse",
22
+ "ArchitectureMap",
23
+ "ChangeImpactResponse",
24
+ "DependencyQueryResponse",
25
+ "DependencyTraceItem",
26
+ "ModuleDetails",
27
+ "ModuleOverviewItem",
28
+ "PackageCluster",
29
+ "RelevantModuleMatch",
30
+ "RelevantModulesResponse",
31
+ "RepositoryIntelligenceService",
32
+ "RepositoryOverview",
33
+ ]