git-contribution-analyzer 0.8.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 (187) hide show
  1. git_contribution_analyzer/__init__.py +3 -0
  2. git_contribution_analyzer/adapters/__init__.py +1 -0
  3. git_contribution_analyzer/adapters/git/__init__.py +1 -0
  4. git_contribution_analyzer/adapters/git/local_identity.py +51 -0
  5. git_contribution_analyzer/adapters/git/native_git.py +353 -0
  6. git_contribution_analyzer/adapters/git/pydriller_history.py +57 -0
  7. git_contribution_analyzer/adapters/git/repository_discovery.py +75 -0
  8. git_contribution_analyzer/adapters/gui/__init__.py +1 -0
  9. git_contribution_analyzer/adapters/gui/app.py +63 -0
  10. git_contribution_analyzer/adapters/gui/controller.py +1084 -0
  11. git_contribution_analyzer/adapters/gui/models/__init__.py +3 -0
  12. git_contribution_analyzer/adapters/gui/models/base_table.py +108 -0
  13. git_contribution_analyzer/adapters/gui/settings.py +53 -0
  14. git_contribution_analyzer/adapters/gui/task_runner.py +196 -0
  15. git_contribution_analyzer/adapters/llm/__init__.py +1 -0
  16. git_contribution_analyzer/adapters/llm/anthropic.py +52 -0
  17. git_contribution_analyzer/adapters/llm/base.py +142 -0
  18. git_contribution_analyzer/adapters/llm/cache.py +148 -0
  19. git_contribution_analyzer/adapters/llm/claude_cli.py +52 -0
  20. git_contribution_analyzer/adapters/llm/codex_cli.py +52 -0
  21. git_contribution_analyzer/adapters/llm/command_base.py +153 -0
  22. git_contribution_analyzer/adapters/llm/mock.py +82 -0
  23. git_contribution_analyzer/adapters/llm/ollama.py +53 -0
  24. git_contribution_analyzer/adapters/llm/openai_compatible.py +61 -0
  25. git_contribution_analyzer/adapters/llm/registry.py +117 -0
  26. git_contribution_analyzer/adapters/mcp/__init__.py +13 -0
  27. git_contribution_analyzer/adapters/mcp/installer.py +175 -0
  28. git_contribution_analyzer/adapters/mcp/prompts_resources.py +218 -0
  29. git_contribution_analyzer/adapters/mcp/protocol.py +361 -0
  30. git_contribution_analyzer/adapters/mcp/server.py +52 -0
  31. git_contribution_analyzer/adapters/mcp/tools.py +621 -0
  32. git_contribution_analyzer/adapters/outcomes/__init__.py +1 -0
  33. git_contribution_analyzer/adapters/outcomes/yaml_loader.py +55 -0
  34. git_contribution_analyzer/adapters/outcomes/yaml_store.py +104 -0
  35. git_contribution_analyzer/adapters/reporting/__init__.py +1 -0
  36. git_contribution_analyzer/adapters/reporting/brag_markdown.py +115 -0
  37. git_contribution_analyzer/adapters/reporting/html_report.py +1413 -0
  38. git_contribution_analyzer/adapters/reporting/markdown.py +217 -0
  39. git_contribution_analyzer/adapters/reporting/portfolio_markdown.py +167 -0
  40. git_contribution_analyzer/adapters/reporting/recap_markdown.py +212 -0
  41. git_contribution_analyzer/adapters/reporting/resume_markdown.py +37 -0
  42. git_contribution_analyzer/adapters/reporting/work_assessment_csv.py +117 -0
  43. git_contribution_analyzer/adapters/reporting/work_assessment_markdown.py +90 -0
  44. git_contribution_analyzer/adapters/reporting/work_assessment_series_markdown.py +31 -0
  45. git_contribution_analyzer/adapters/storage/__init__.py +1 -0
  46. git_contribution_analyzer/adapters/storage/sqlite/__init__.py +1 -0
  47. git_contribution_analyzer/adapters/storage/sqlite/analysis.py +708 -0
  48. git_contribution_analyzer/adapters/storage/sqlite/database.py +98 -0
  49. git_contribution_analyzer/adapters/storage/sqlite/git_index.py +482 -0
  50. git_contribution_analyzer/adapters/storage/sqlite/identity_merge.py +373 -0
  51. git_contribution_analyzer/adapters/storage/sqlite/llm_audit.py +109 -0
  52. git_contribution_analyzer/adapters/storage/sqlite/migrations/env.py +34 -0
  53. git_contribution_analyzer/adapters/storage/sqlite/migrations/script.py.mako +22 -0
  54. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0001_initial.py +51 -0
  55. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0002_git_index.py +146 -0
  56. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0003_analysis.py +79 -0
  57. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0004_llm_audit.py +69 -0
  58. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0005_run_types.py +42 -0
  59. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0006_identity_merges.py +83 -0
  60. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0007_structural_baselines.py +173 -0
  61. git_contribution_analyzer/adapters/storage/sqlite/models.py +354 -0
  62. git_contribution_analyzer/adapters/storage/sqlite/structural_baseline.py +841 -0
  63. git_contribution_analyzer/adapters/workspace/__init__.py +1 -0
  64. git_contribution_analyzer/adapters/workspace/config.py +135 -0
  65. git_contribution_analyzer/adapters/workspace/git_exclude.py +32 -0
  66. git_contribution_analyzer/adapters/workspace/layout.py +40 -0
  67. git_contribution_analyzer/adapters/workspace/locks.py +27 -0
  68. git_contribution_analyzer/adapters/workspace/portfolio_workspace.py +380 -0
  69. git_contribution_analyzer/adapters/workspace/ranking_config.py +17 -0
  70. git_contribution_analyzer/application/__init__.py +1 -0
  71. git_contribution_analyzer/application/dto/__init__.py +19 -0
  72. git_contribution_analyzer/application/dto/gui.py +86 -0
  73. git_contribution_analyzer/application/dto/results.py +21 -0
  74. git_contribution_analyzer/application/facades/__init__.py +3 -0
  75. git_contribution_analyzer/application/facades/gui.py +568 -0
  76. git_contribution_analyzer/application/ports/__init__.py +22 -0
  77. git_contribution_analyzer/application/ports/cancellation.py +50 -0
  78. git_contribution_analyzer/application/ports/git_history.py +22 -0
  79. git_contribution_analyzer/application/ports/llm.py +44 -0
  80. git_contribution_analyzer/application/ports/portfolio_store.py +34 -0
  81. git_contribution_analyzer/application/ports/progress.py +43 -0
  82. git_contribution_analyzer/application/ports/structural_baseline.py +93 -0
  83. git_contribution_analyzer/application/services/__init__.py +1 -0
  84. git_contribution_analyzer/application/services/assessment_explanation.py +127 -0
  85. git_contribution_analyzer/application/services/default_person.py +61 -0
  86. git_contribution_analyzer/application/services/evidence_snapshot.py +64 -0
  87. git_contribution_analyzer/application/services/person_selection.py +88 -0
  88. git_contribution_analyzer/application/services/resume_generation.py +318 -0
  89. git_contribution_analyzer/application/services/semantic_enhancement.py +157 -0
  90. git_contribution_analyzer/application/services/time_boundaries.py +49 -0
  91. git_contribution_analyzer/application/use_cases/__init__.py +1 -0
  92. git_contribution_analyzer/application/use_cases/analyze_contributions.py +276 -0
  93. git_contribution_analyzer/application/use_cases/analyze_project.py +295 -0
  94. git_contribution_analyzer/application/use_cases/assess_portfolio.py +327 -0
  95. git_contribution_analyzer/application/use_cases/assess_work.py +602 -0
  96. git_contribution_analyzer/application/use_cases/assess_work_series.py +212 -0
  97. git_contribution_analyzer/application/use_cases/compare_assessment_runs.py +121 -0
  98. git_contribution_analyzer/application/use_cases/export_report.py +49 -0
  99. git_contribution_analyzer/application/use_cases/generate_brag.py +308 -0
  100. git_contribution_analyzer/application/use_cases/generate_portfolio_recap.py +244 -0
  101. git_contribution_analyzer/application/use_cases/generate_portfolio_resume.py +152 -0
  102. git_contribution_analyzer/application/use_cases/generate_recap.py +316 -0
  103. git_contribution_analyzer/application/use_cases/generate_report.py +32 -0
  104. git_contribution_analyzer/application/use_cases/generate_resume.py +209 -0
  105. git_contribution_analyzer/application/use_cases/get_portfolio_status.py +83 -0
  106. git_contribution_analyzer/application/use_cases/get_run.py +16 -0
  107. git_contribution_analyzer/application/use_cases/get_status.py +69 -0
  108. git_contribution_analyzer/application/use_cases/index_repository.py +267 -0
  109. git_contribution_analyzer/application/use_cases/init_portfolio.py +89 -0
  110. git_contribution_analyzer/application/use_cases/init_project.py +71 -0
  111. git_contribution_analyzer/application/use_cases/list_identities.py +16 -0
  112. git_contribution_analyzer/application/use_cases/list_providers.py +29 -0
  113. git_contribution_analyzer/application/use_cases/list_runs.py +17 -0
  114. git_contribution_analyzer/application/use_cases/manage_identity_merges.py +48 -0
  115. git_contribution_analyzer/application/use_cases/manage_outcomes.py +189 -0
  116. git_contribution_analyzer/application/use_cases/manage_structural_baselines.py +262 -0
  117. git_contribution_analyzer/application/use_cases/map_identity.py +28 -0
  118. git_contribution_analyzer/application/use_cases/recover_runs.py +22 -0
  119. git_contribution_analyzer/application/use_cases/run_doctor.py +81 -0
  120. git_contribution_analyzer/application/use_cases/sync_portfolio.py +232 -0
  121. git_contribution_analyzer/application/use_cases/test_provider.py +22 -0
  122. git_contribution_analyzer/application/use_cases/uninit_project.py +23 -0
  123. git_contribution_analyzer/application/use_cases/verify_portfolio.py +165 -0
  124. git_contribution_analyzer/cli/__init__.py +1 -0
  125. git_contribution_analyzer/cli/app.py +1430 -0
  126. git_contribution_analyzer/cli/exit_codes.py +13 -0
  127. git_contribution_analyzer/cli/output.py +26 -0
  128. git_contribution_analyzer/cli/portfolio_commands.py +629 -0
  129. git_contribution_analyzer/domain/__init__.py +1 -0
  130. git_contribution_analyzer/domain/errors.py +55 -0
  131. git_contribution_analyzer/domain/models/__init__.py +3 -0
  132. git_contribution_analyzer/domain/models/analysis.py +29 -0
  133. git_contribution_analyzer/domain/models/assessment.py +12 -0
  134. git_contribution_analyzer/domain/models/brag.py +148 -0
  135. git_contribution_analyzer/domain/models/contribution.py +55 -0
  136. git_contribution_analyzer/domain/models/git_history.py +69 -0
  137. git_contribution_analyzer/domain/models/person_selection.py +46 -0
  138. git_contribution_analyzer/domain/models/portfolio.py +498 -0
  139. git_contribution_analyzer/domain/models/ranking.py +48 -0
  140. git_contribution_analyzer/domain/models/recap.py +235 -0
  141. git_contribution_analyzer/domain/models/repository.py +10 -0
  142. git_contribution_analyzer/domain/models/resume.py +59 -0
  143. git_contribution_analyzer/domain/models/run.py +10 -0
  144. git_contribution_analyzer/domain/models/semantic.py +34 -0
  145. git_contribution_analyzer/domain/models/snapshot.py +208 -0
  146. git_contribution_analyzer/domain/models/structural_baseline.py +120 -0
  147. git_contribution_analyzer/domain/models/work_assessment.py +81 -0
  148. git_contribution_analyzer/domain/services/assessment_periods.py +182 -0
  149. git_contribution_analyzer/domain/services/brag_rules.py +250 -0
  150. git_contribution_analyzer/domain/services/capability_rules.py +91 -0
  151. git_contribution_analyzer/domain/services/contribution_clustering.py +98 -0
  152. git_contribution_analyzer/domain/services/contribution_rules.py +79 -0
  153. git_contribution_analyzer/domain/services/difficulty_rules.py +191 -0
  154. git_contribution_analyzer/domain/services/dimensional_summary.py +117 -0
  155. git_contribution_analyzer/domain/services/portfolio_aggregation.py +250 -0
  156. git_contribution_analyzer/domain/services/portfolio_resume_rules.py +265 -0
  157. git_contribution_analyzer/domain/services/portfolio_verifier.py +238 -0
  158. git_contribution_analyzer/domain/services/ranking_rules.py +226 -0
  159. git_contribution_analyzer/domain/services/recap_rules.py +268 -0
  160. git_contribution_analyzer/domain/services/resume_claim_rules.py +70 -0
  161. git_contribution_analyzer/domain/services/structural_baseline.py +317 -0
  162. git_contribution_analyzer/domain/services/structural_signals.py +151 -0
  163. git_contribution_analyzer/domain/services/workload_rules.py +185 -0
  164. git_contribution_analyzer/gui/__init__.py +1 -0
  165. git_contribution_analyzer/gui/qml/Main.qml +1141 -0
  166. git_contribution_analyzer/gui/qml/__init__.py +1 -0
  167. git_contribution_analyzer/prompts/__init__.py +1 -0
  168. git_contribution_analyzer/prompts/assessment/__init__.py +1 -0
  169. git_contribution_analyzer/prompts/assessment/v1/__init__.py +1 -0
  170. git_contribution_analyzer/prompts/assessment/v1/explanation.txt +4 -0
  171. git_contribution_analyzer/prompts/resume/__init__.py +1 -0
  172. git_contribution_analyzer/prompts/resume/v1/__init__.py +1 -0
  173. git_contribution_analyzer/prompts/resume/v1/style-concise.txt +1 -0
  174. git_contribution_analyzer/prompts/resume/v1/style-star.txt +1 -0
  175. git_contribution_analyzer/prompts/resume/v1/style-xyz.txt +1 -0
  176. git_contribution_analyzer/prompts/resume/v1/system.txt +3 -0
  177. git_contribution_analyzer/prompts/v1/__init__.py +1 -0
  178. git_contribution_analyzer/prompts/v1/capability_explanation.txt +2 -0
  179. git_contribution_analyzer/prompts/v1/contribution_summary.txt +2 -0
  180. git_contribution_analyzer/prompts/v1/overall_summary.txt +2 -0
  181. git_contribution_analyzer/prompts/v1/resume_bullet.txt +2 -0
  182. git_contribution_analyzer-0.8.0.dist-info/METADATA +667 -0
  183. git_contribution_analyzer-0.8.0.dist-info/RECORD +187 -0
  184. git_contribution_analyzer-0.8.0.dist-info/WHEEL +4 -0
  185. git_contribution_analyzer-0.8.0.dist-info/entry_points.txt +3 -0
  186. git_contribution_analyzer-0.8.0.dist-info/licenses/LICENSE +201 -0
  187. git_contribution_analyzer-0.8.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,841 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from collections.abc import Iterable
6
+ from datetime import UTC, datetime
7
+ from itertools import combinations
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from sqlalchemy import delete, func, insert, select, update
12
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
13
+
14
+ from git_contribution_analyzer.adapters.storage.sqlite.database import create_database_engine
15
+ from git_contribution_analyzer.adapters.storage.sqlite.models import (
16
+ commits,
17
+ repositories,
18
+ structural_baselines,
19
+ structural_commit_facts,
20
+ structural_edge_counts,
21
+ structural_edge_occurrences,
22
+ structural_file_counts,
23
+ structural_file_occurrences,
24
+ structural_materializations,
25
+ )
26
+ from git_contribution_analyzer.domain.errors import WorkspaceError
27
+ from git_contribution_analyzer.domain.models.contribution import ContributionCommit
28
+ from git_contribution_analyzer.domain.models.git_history import GitCommit
29
+ from git_contribution_analyzer.domain.models.structural_baseline import (
30
+ StructuralBaseline,
31
+ StructuralRuleConfig,
32
+ )
33
+ from git_contribution_analyzer.domain.services.contribution_rules import is_generated_path
34
+ from git_contribution_analyzer.domain.services.structural_baseline import (
35
+ STRUCTURAL_FACT_RULE_VERSION,
36
+ STRUCTURAL_METRIC_RULE_VERSION,
37
+ STRUCTURAL_THRESHOLD_VERSION,
38
+ )
39
+
40
+
41
+ class SqliteStructuralBaselineStore:
42
+ def __init__(self, database_path: Path, repository_root: str) -> None:
43
+ self.database_path = database_path
44
+ self.repository_root = repository_root
45
+
46
+ def repository_id(self) -> str:
47
+ engine = create_database_engine(self.database_path)
48
+ try:
49
+ with engine.connect() as connection:
50
+ value = connection.execute(
51
+ select(repositories.c.id).where(
52
+ repositories.c.root_path == self.repository_root
53
+ )
54
+ ).scalar_one_or_none()
55
+ if value is None:
56
+ raise WorkspaceError(f"Repository is not registered: {self.repository_root}")
57
+ return str(value)
58
+ finally:
59
+ engine.dispose()
60
+
61
+ def sync_commit_facts(
62
+ self,
63
+ git_commits: Iterable[GitCommit],
64
+ *,
65
+ clear_existing: bool,
66
+ maximum_context_paths: int = 200,
67
+ ) -> dict[str, int]:
68
+ engine = create_database_engine(self.database_path)
69
+ inserted_commits = 0
70
+ inserted_files = 0
71
+ inserted_edges = 0
72
+ try:
73
+ with engine.begin() as connection:
74
+ repository_id = connection.execute(
75
+ select(repositories.c.id).where(
76
+ repositories.c.root_path == self.repository_root
77
+ )
78
+ ).scalar_one()
79
+ if clear_existing:
80
+ connection.execute(
81
+ delete(structural_baselines).where(
82
+ structural_baselines.c.repository_id == repository_id
83
+ )
84
+ )
85
+ connection.execute(
86
+ delete(structural_commit_facts).where(
87
+ structural_commit_facts.c.repository_id == repository_id
88
+ )
89
+ )
90
+ for commit in git_commits:
91
+ paths, excluded_reason = _eligible_git_paths(commit)
92
+ capped = len(paths) > maximum_context_paths
93
+ edges = () if capped else tuple(combinations(paths, 2))
94
+ statement = sqlite_insert(structural_commit_facts).values(
95
+ repository_id=repository_id,
96
+ commit_hash=commit.hash,
97
+ fact_rule_version=STRUCTURAL_FACT_RULE_VERSION,
98
+ occurred_at=commit.committed_at.astimezone(UTC),
99
+ path_count=len(paths),
100
+ edge_count=len(edges),
101
+ context_capped=capped,
102
+ excluded_reason=excluded_reason,
103
+ )
104
+ result = connection.execute(
105
+ statement.on_conflict_do_nothing(
106
+ index_elements=[
107
+ structural_commit_facts.c.repository_id,
108
+ structural_commit_facts.c.commit_hash,
109
+ structural_commit_facts.c.fact_rule_version,
110
+ ]
111
+ )
112
+ )
113
+ if result.rowcount == 0:
114
+ continue
115
+ inserted_commits += 1
116
+ if paths:
117
+ connection.execute(
118
+ insert(structural_file_occurrences),
119
+ [
120
+ {
121
+ "repository_id": repository_id,
122
+ "commit_hash": commit.hash,
123
+ "fact_rule_version": STRUCTURAL_FACT_RULE_VERSION,
124
+ "path": path,
125
+ }
126
+ for path in paths
127
+ ],
128
+ )
129
+ inserted_files += len(paths)
130
+ if edges:
131
+ connection.execute(
132
+ insert(structural_edge_occurrences),
133
+ [
134
+ {
135
+ "repository_id": repository_id,
136
+ "commit_hash": commit.hash,
137
+ "fact_rule_version": STRUCTURAL_FACT_RULE_VERSION,
138
+ "left_path": left,
139
+ "right_path": right,
140
+ }
141
+ for left, right in edges
142
+ ],
143
+ )
144
+ inserted_edges += len(edges)
145
+ finally:
146
+ engine.dispose()
147
+ return {
148
+ "processedCommits": inserted_commits,
149
+ "fileOccurrences": inserted_files,
150
+ "edgeOccurrences": inserted_edges,
151
+ }
152
+
153
+ def load_commits(
154
+ self,
155
+ *,
156
+ allowed_hashes: set[str],
157
+ cutoff: datetime,
158
+ scope: str | None,
159
+ ) -> tuple[ContributionCommit, ...]:
160
+ engine = create_database_engine(self.database_path)
161
+ try:
162
+ with engine.connect() as connection:
163
+ repository_id = connection.execute(
164
+ select(repositories.c.id).where(
165
+ repositories.c.root_path == self.repository_root
166
+ )
167
+ ).scalar_one()
168
+ rows = connection.execute(
169
+ select(
170
+ structural_commit_facts.c.commit_hash,
171
+ structural_commit_facts.c.occurred_at,
172
+ structural_commit_facts.c.context_capped,
173
+ commits.c.subject,
174
+ commits.c.is_merge,
175
+ commits.c.patch_id,
176
+ )
177
+ .join(
178
+ commits,
179
+ (commits.c.repository_id == structural_commit_facts.c.repository_id)
180
+ & (commits.c.hash == structural_commit_facts.c.commit_hash),
181
+ )
182
+ .where(
183
+ structural_commit_facts.c.repository_id == repository_id,
184
+ structural_commit_facts.c.fact_rule_version
185
+ == STRUCTURAL_FACT_RULE_VERSION,
186
+ structural_commit_facts.c.occurred_at < cutoff.astimezone(UTC),
187
+ )
188
+ .order_by(
189
+ structural_commit_facts.c.occurred_at,
190
+ structural_commit_facts.c.commit_hash,
191
+ )
192
+ ).mappings()
193
+ selected = [row for row in rows if str(row["commit_hash"]) in allowed_hashes]
194
+ hashes = tuple(str(row["commit_hash"]) for row in selected)
195
+ path_rows = connection.execute(
196
+ select(
197
+ structural_file_occurrences.c.commit_hash,
198
+ structural_file_occurrences.c.path,
199
+ ).where(
200
+ structural_file_occurrences.c.repository_id == repository_id,
201
+ structural_file_occurrences.c.fact_rule_version
202
+ == STRUCTURAL_FACT_RULE_VERSION,
203
+ )
204
+ )
205
+ paths_by_commit: dict[str, list[str]] = {value: [] for value in hashes}
206
+ normalized_scope = scope.replace("\\", "/").strip("/") if scope else None
207
+ for commit_hash, path in path_rows:
208
+ actual_hash = str(commit_hash)
209
+ actual_path = str(path)
210
+ if actual_hash not in paths_by_commit:
211
+ continue
212
+ if normalized_scope and not (
213
+ actual_path == normalized_scope
214
+ or actual_path.startswith(f"{normalized_scope}/")
215
+ ):
216
+ continue
217
+ paths_by_commit[actual_hash].append(actual_path)
218
+ finally:
219
+ engine.dispose()
220
+
221
+ result: list[ContributionCommit] = []
222
+ for row in selected:
223
+ commit_hash = str(row["commit_hash"])
224
+ paths = tuple(sorted(set(paths_by_commit[commit_hash])))
225
+ if not paths:
226
+ continue
227
+ occurred_at = _aware_utc(row["occurred_at"])
228
+ result.append(
229
+ ContributionCommit(
230
+ hash=commit_hash,
231
+ subject=str(row["subject"]),
232
+ authored_at=occurred_at,
233
+ commit_type="STRUCTURAL_FACT",
234
+ delivery_status="LANDED",
235
+ paths=paths,
236
+ modules=tuple(sorted({_module(path) for path in paths})),
237
+ insertions=1,
238
+ deletions=0,
239
+ files_changed=len(paths),
240
+ merge=bool(row["is_merge"]),
241
+ binary_files=0,
242
+ generated_files=0,
243
+ patch_id=str(row["patch_id"]) if row["patch_id"] else None,
244
+ period_at=occurred_at,
245
+ )
246
+ )
247
+ return tuple(result)
248
+
249
+ def latest_fact_commit(
250
+ self,
251
+ *,
252
+ allowed_hashes: set[str],
253
+ cutoff: datetime,
254
+ scope: str | None,
255
+ ) -> str | None:
256
+ engine = create_database_engine(self.database_path)
257
+ try:
258
+ with engine.connect() as connection:
259
+ repository_id = connection.execute(
260
+ select(repositories.c.id).where(
261
+ repositories.c.root_path == self.repository_root
262
+ )
263
+ ).scalar_one()
264
+ normalized_scope = scope.replace("\\", "/").strip("/") if scope else None
265
+ statement = (
266
+ select(
267
+ structural_commit_facts.c.commit_hash,
268
+ structural_commit_facts.c.occurred_at,
269
+ )
270
+ .join(
271
+ structural_file_occurrences,
272
+ (
273
+ structural_file_occurrences.c.repository_id
274
+ == structural_commit_facts.c.repository_id
275
+ )
276
+ & (
277
+ structural_file_occurrences.c.commit_hash
278
+ == structural_commit_facts.c.commit_hash
279
+ )
280
+ & (
281
+ structural_file_occurrences.c.fact_rule_version
282
+ == structural_commit_facts.c.fact_rule_version
283
+ ),
284
+ )
285
+ .where(
286
+ structural_commit_facts.c.repository_id == repository_id,
287
+ structural_commit_facts.c.fact_rule_version
288
+ == STRUCTURAL_FACT_RULE_VERSION,
289
+ structural_commit_facts.c.occurred_at < cutoff.astimezone(UTC),
290
+ )
291
+ )
292
+ if normalized_scope:
293
+ statement = statement.where(
294
+ (structural_file_occurrences.c.path == normalized_scope)
295
+ | structural_file_occurrences.c.path.startswith(
296
+ f"{normalized_scope}/"
297
+ )
298
+ )
299
+ rows = connection.execute(
300
+ statement.distinct().order_by(
301
+ structural_commit_facts.c.occurred_at.desc(),
302
+ structural_commit_facts.c.commit_hash.desc(),
303
+ )
304
+ )
305
+ for commit_hash, _occurred_at in rows:
306
+ value = str(commit_hash)
307
+ if value in allowed_hashes:
308
+ return value
309
+ return None
310
+ finally:
311
+ engine.dispose()
312
+
313
+ def save_baseline(
314
+ self,
315
+ baseline: StructuralBaseline,
316
+ *,
317
+ branch: str,
318
+ scope: str | None,
319
+ baseline_commit: str | None,
320
+ filter_fingerprint: str,
321
+ diagnostic_id: str | None = None,
322
+ ) -> dict[str, Any]:
323
+ payload = serialize_baseline(
324
+ baseline,
325
+ branch=branch,
326
+ scope=scope,
327
+ baseline_commit=baseline_commit,
328
+ status="COMPLETED",
329
+ )
330
+ encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
331
+ content_hash = hashlib.sha256(encoded.encode("utf-8")).hexdigest()
332
+ engine = create_database_engine(self.database_path)
333
+ try:
334
+ with engine.begin() as connection:
335
+ repository_id = connection.execute(
336
+ select(repositories.c.id).where(
337
+ repositories.c.root_path == self.repository_root
338
+ )
339
+ ).scalar_one()
340
+ if diagnostic_id is not None:
341
+ connection.execute(
342
+ delete(structural_baselines).where(
343
+ structural_baselines.c.id == diagnostic_id
344
+ )
345
+ )
346
+ connection.execute(
347
+ delete(structural_baselines).where(structural_baselines.c.id == baseline.id)
348
+ )
349
+ connection.execute(
350
+ insert(structural_baselines).values(
351
+ id=baseline.id,
352
+ repository_id=repository_id,
353
+ baseline_commit=baseline_commit,
354
+ cutoff_at=baseline.cutoff.astimezone(UTC),
355
+ branch=branch,
356
+ scope=scope,
357
+ filter_fingerprint=filter_fingerprint,
358
+ time_strategy=baseline.config.time_strategy.value,
359
+ fact_rule_version=STRUCTURAL_FACT_RULE_VERSION,
360
+ metric_rule_version=STRUCTURAL_METRIC_RULE_VERSION,
361
+ threshold_version=STRUCTURAL_THRESHOLD_VERSION,
362
+ status="COMPLETED",
363
+ eligible_commit_count=baseline.summary.eligible_commits,
364
+ eligible_file_count=baseline.summary.eligible_files,
365
+ raw_edge_count=baseline.summary.raw_edges,
366
+ completed_at=datetime.now(UTC),
367
+ )
368
+ )
369
+ if baseline.file_counts:
370
+ connection.execute(
371
+ insert(structural_file_counts),
372
+ [
373
+ {
374
+ "baseline_id": baseline.id,
375
+ "path": value.path,
376
+ "change_count": value.change_count,
377
+ "recent_change_count": value.recent_change_count,
378
+ }
379
+ for value in baseline.file_counts
380
+ ],
381
+ )
382
+ if baseline.edge_counts:
383
+ connection.execute(
384
+ insert(structural_edge_counts),
385
+ [
386
+ {
387
+ "baseline_id": baseline.id,
388
+ "left_path": value.left_path,
389
+ "right_path": value.right_path,
390
+ "co_change_count": value.co_change_count,
391
+ "recent_co_change_count": value.recent_co_change_count,
392
+ }
393
+ for value in baseline.edge_counts
394
+ ],
395
+ )
396
+ connection.execute(
397
+ insert(structural_materializations).values(
398
+ baseline_id=baseline.id,
399
+ metric_rule_version=STRUCTURAL_METRIC_RULE_VERSION,
400
+ threshold_version=STRUCTURAL_THRESHOLD_VERSION,
401
+ content_hash=content_hash,
402
+ result_json=encoded,
403
+ )
404
+ )
405
+ finally:
406
+ engine.dispose()
407
+ return payload
408
+
409
+ def begin_baseline(
410
+ self,
411
+ build_id: str,
412
+ *,
413
+ branch: str,
414
+ scope: str | None,
415
+ cutoff: datetime,
416
+ baseline_commit: str | None,
417
+ filter_fingerprint: str,
418
+ config: StructuralRuleConfig,
419
+ ) -> None:
420
+ engine = create_database_engine(self.database_path)
421
+ try:
422
+ with engine.begin() as connection:
423
+ repository_id = connection.execute(
424
+ select(repositories.c.id).where(
425
+ repositories.c.root_path == self.repository_root
426
+ )
427
+ ).scalar_one()
428
+ connection.execute(
429
+ insert(structural_baselines).values(
430
+ id=build_id,
431
+ repository_id=repository_id,
432
+ baseline_commit=baseline_commit,
433
+ cutoff_at=cutoff.astimezone(UTC),
434
+ branch=branch,
435
+ scope=scope,
436
+ filter_fingerprint=filter_fingerprint,
437
+ time_strategy=config.time_strategy.value,
438
+ fact_rule_version=STRUCTURAL_FACT_RULE_VERSION,
439
+ metric_rule_version=STRUCTURAL_METRIC_RULE_VERSION,
440
+ threshold_version=STRUCTURAL_THRESHOLD_VERSION,
441
+ status="BUILDING",
442
+ eligible_commit_count=0,
443
+ eligible_file_count=0,
444
+ raw_edge_count=0,
445
+ )
446
+ )
447
+ finally:
448
+ engine.dispose()
449
+
450
+ def finish_baseline(
451
+ self,
452
+ build_id: str,
453
+ *,
454
+ status: str,
455
+ error_message: str,
456
+ ) -> None:
457
+ if status not in {"FAILED", "CANCELLED"}:
458
+ raise ValueError(f"Unsupported diagnostic status: {status}")
459
+ engine = create_database_engine(self.database_path)
460
+ try:
461
+ with engine.begin() as connection:
462
+ connection.execute(
463
+ update(structural_baselines)
464
+ .where(structural_baselines.c.id == build_id)
465
+ .values(
466
+ status=status,
467
+ error_message=error_message,
468
+ completed_at=datetime.now(UTC),
469
+ )
470
+ )
471
+ finally:
472
+ engine.dispose()
473
+
474
+ def mark_stale(self, baseline_ids: Iterable[str]) -> int:
475
+ ids = tuple(sorted(set(baseline_ids)))
476
+ if not ids:
477
+ return 0
478
+ engine = create_database_engine(self.database_path)
479
+ try:
480
+ with engine.begin() as connection:
481
+ result = connection.execute(
482
+ update(structural_baselines)
483
+ .where(
484
+ structural_baselines.c.id.in_(ids),
485
+ structural_baselines.c.status == "COMPLETED",
486
+ )
487
+ .values(status="STALE")
488
+ )
489
+ return int(result.rowcount or 0)
490
+ finally:
491
+ engine.dispose()
492
+
493
+ def find_completed(
494
+ self,
495
+ *,
496
+ branch: str,
497
+ scope: str | None,
498
+ cutoff: datetime,
499
+ baseline_commit: str | None,
500
+ filter_fingerprint: str,
501
+ time_strategy: str,
502
+ ) -> dict[str, Any] | None:
503
+ engine = create_database_engine(self.database_path)
504
+ try:
505
+ with engine.connect() as connection:
506
+ repository_id = connection.execute(
507
+ select(repositories.c.id).where(
508
+ repositories.c.root_path == self.repository_root
509
+ )
510
+ ).scalar_one()
511
+ scope_filter = (
512
+ structural_baselines.c.scope.is_(None)
513
+ if scope is None
514
+ else structural_baselines.c.scope == scope
515
+ )
516
+ rows = connection.execute(
517
+ select(
518
+ structural_baselines.c.baseline_commit,
519
+ structural_materializations.c.result_json,
520
+ )
521
+ .join(
522
+ structural_materializations,
523
+ structural_materializations.c.baseline_id
524
+ == structural_baselines.c.id,
525
+ )
526
+ .where(
527
+ structural_baselines.c.repository_id == repository_id,
528
+ structural_baselines.c.status == "COMPLETED",
529
+ structural_baselines.c.branch == branch,
530
+ scope_filter,
531
+ structural_baselines.c.cutoff_at == cutoff.astimezone(UTC),
532
+ structural_baselines.c.filter_fingerprint == filter_fingerprint,
533
+ structural_baselines.c.time_strategy == time_strategy,
534
+ structural_baselines.c.fact_rule_version
535
+ == STRUCTURAL_FACT_RULE_VERSION,
536
+ structural_baselines.c.metric_rule_version
537
+ == STRUCTURAL_METRIC_RULE_VERSION,
538
+ structural_baselines.c.threshold_version
539
+ == STRUCTURAL_THRESHOLD_VERSION,
540
+ )
541
+ .order_by(structural_baselines.c.completed_at.desc())
542
+ )
543
+ for stored_baseline_commit, encoded in rows:
544
+ commit = (
545
+ str(stored_baseline_commit) if stored_baseline_commit else None
546
+ )
547
+ if commit == baseline_commit:
548
+ return dict(json.loads(str(encoded)))
549
+ return None
550
+ finally:
551
+ engine.dispose()
552
+
553
+ def show(self, baseline_id: str) -> dict[str, Any] | None:
554
+ engine = create_database_engine(self.database_path)
555
+ try:
556
+ with engine.connect() as connection:
557
+ repository_id = connection.execute(
558
+ select(repositories.c.id).where(
559
+ repositories.c.root_path == self.repository_root
560
+ )
561
+ ).scalar_one()
562
+ value = connection.execute(
563
+ select(structural_materializations.c.result_json)
564
+ .join(
565
+ structural_baselines,
566
+ structural_baselines.c.id == structural_materializations.c.baseline_id,
567
+ )
568
+ .where(
569
+ structural_baselines.c.repository_id == repository_id,
570
+ structural_materializations.c.baseline_id == baseline_id,
571
+ )
572
+ ).scalar_one_or_none()
573
+ return dict(json.loads(str(value))) if value else None
574
+ finally:
575
+ engine.dispose()
576
+
577
+ def status(self) -> dict[str, Any]:
578
+ engine = create_database_engine(self.database_path)
579
+ try:
580
+ with engine.connect() as connection:
581
+ repository_id = connection.execute(
582
+ select(repositories.c.id).where(
583
+ repositories.c.root_path == self.repository_root
584
+ )
585
+ ).scalar_one()
586
+ count = int(
587
+ connection.execute(
588
+ select(func.count()).select_from(structural_baselines).where(
589
+ structural_baselines.c.repository_id == repository_id,
590
+ structural_baselines.c.status == "COMPLETED",
591
+ )
592
+ ).scalar_one()
593
+ )
594
+ latest = connection.execute(
595
+ select(structural_baselines.c.id)
596
+ .where(
597
+ structural_baselines.c.repository_id == repository_id,
598
+ structural_baselines.c.status == "COMPLETED",
599
+ )
600
+ .order_by(
601
+ structural_baselines.c.cutoff_at.desc(),
602
+ structural_baselines.c.created_at.desc(),
603
+ )
604
+ .limit(1)
605
+ ).scalar_one_or_none()
606
+ facts = int(
607
+ connection.execute(
608
+ select(func.count()).select_from(structural_commit_facts).where(
609
+ structural_commit_facts.c.repository_id == repository_id
610
+ )
611
+ ).scalar_one()
612
+ )
613
+ status_counts = {
614
+ status: int(
615
+ connection.execute(
616
+ select(func.count()).select_from(structural_baselines).where(
617
+ structural_baselines.c.repository_id == repository_id,
618
+ structural_baselines.c.status == status,
619
+ )
620
+ ).scalar_one()
621
+ )
622
+ for status in ("BUILDING", "FAILED", "CANCELLED", "STALE")
623
+ }
624
+ orphan = int(
625
+ connection.execute(
626
+ select(func.count())
627
+ .select_from(
628
+ structural_baselines.outerjoin(
629
+ structural_materializations,
630
+ structural_materializations.c.baseline_id
631
+ == structural_baselines.c.id,
632
+ )
633
+ )
634
+ .where(
635
+ structural_baselines.c.repository_id == repository_id,
636
+ structural_baselines.c.status == "COMPLETED",
637
+ structural_materializations.c.baseline_id.is_(None),
638
+ )
639
+ ).scalar_one()
640
+ )
641
+ latest_diagnostic = connection.execute(
642
+ select(structural_baselines.c.id)
643
+ .where(
644
+ structural_baselines.c.repository_id == repository_id,
645
+ structural_baselines.c.status.in_(
646
+ ("BUILDING", "FAILED", "CANCELLED", "STALE")
647
+ ),
648
+ )
649
+ .order_by(structural_baselines.c.created_at.desc())
650
+ .limit(1)
651
+ ).scalar_one_or_none()
652
+ return {
653
+ "baselineCount": count,
654
+ "latestBaselineId": str(latest) if latest else None,
655
+ "processedCommits": facts,
656
+ "factRuleVersion": STRUCTURAL_FACT_RULE_VERSION,
657
+ "unhealthyBaselines": (
658
+ status_counts["BUILDING"] + status_counts["FAILED"] + orphan
659
+ ),
660
+ "orphanBaselines": orphan,
661
+ "buildingBaselines": status_counts["BUILDING"],
662
+ "failedBaselines": status_counts["FAILED"],
663
+ "cancelledBaselines": status_counts["CANCELLED"],
664
+ "staleBaselines": status_counts["STALE"],
665
+ "latestDiagnosticId": (
666
+ str(latest_diagnostic) if latest_diagnostic else None
667
+ ),
668
+ }
669
+ finally:
670
+ engine.dispose()
671
+
672
+ def completed_baseline_refs(self) -> tuple[dict[str, str | None], ...]:
673
+ engine = create_database_engine(self.database_path)
674
+ try:
675
+ with engine.connect() as connection:
676
+ repository_id = connection.execute(
677
+ select(repositories.c.id).where(
678
+ repositories.c.root_path == self.repository_root
679
+ )
680
+ ).scalar_one()
681
+ rows = connection.execute(
682
+ select(
683
+ structural_baselines.c.id,
684
+ structural_baselines.c.branch,
685
+ structural_baselines.c.baseline_commit,
686
+ ).where(
687
+ structural_baselines.c.repository_id == repository_id,
688
+ structural_baselines.c.status == "COMPLETED",
689
+ )
690
+ ).mappings()
691
+ return tuple(
692
+ {
693
+ "baselineId": str(row["id"]),
694
+ "branch": str(row["branch"]),
695
+ "baselineCommit": (
696
+ str(row["baseline_commit"])
697
+ if row["baseline_commit"]
698
+ else None
699
+ ),
700
+ }
701
+ for row in rows
702
+ )
703
+ finally:
704
+ engine.dispose()
705
+
706
+ def prune(self, keep: int) -> dict[str, int]:
707
+ if keep < 0:
708
+ raise ValueError("keep must not be negative")
709
+ engine = create_database_engine(self.database_path)
710
+ try:
711
+ with engine.begin() as connection:
712
+ repository_id = connection.execute(
713
+ select(repositories.c.id).where(
714
+ repositories.c.root_path == self.repository_root
715
+ )
716
+ ).scalar_one()
717
+ ids = list(
718
+ connection.execute(
719
+ select(structural_baselines.c.id)
720
+ .where(structural_baselines.c.repository_id == repository_id)
721
+ .order_by(
722
+ structural_baselines.c.cutoff_at.desc(),
723
+ structural_baselines.c.created_at.desc(),
724
+ )
725
+ ).scalars()
726
+ )
727
+ deleted = ids[keep:]
728
+ if deleted:
729
+ connection.execute(
730
+ delete(structural_baselines).where(
731
+ structural_baselines.c.id.in_(deleted)
732
+ )
733
+ )
734
+ return {"deletedBaselines": len(deleted), "remainingBaselines": len(ids[:keep])}
735
+ finally:
736
+ engine.dispose()
737
+
738
+
739
+ def serialize_baseline(
740
+ baseline: StructuralBaseline,
741
+ *,
742
+ branch: str,
743
+ scope: str | None,
744
+ baseline_commit: str | None,
745
+ status: str,
746
+ ) -> dict[str, Any]:
747
+ return {
748
+ "schemaVersion": "1.0",
749
+ "baselineId": baseline.id,
750
+ "status": status,
751
+ "baselineCommit": baseline_commit,
752
+ "cutoff": baseline.cutoff.isoformat(),
753
+ "branch": branch,
754
+ "scope": scope,
755
+ "timeStrategy": baseline.config.time_strategy.value,
756
+ "configuration": {
757
+ "minimumBaselineCommits": baseline.config.minimum_baseline_commits,
758
+ "hotspotPercentile": baseline.config.hotspot_percentile,
759
+ "minimumCoChangeCount": baseline.config.minimum_co_change_count,
760
+ "minimumSubsetRatio": baseline.config.minimum_subset_ratio,
761
+ "minimumJaccard": baseline.config.minimum_jaccard,
762
+ "minimumHubPenalty": baseline.config.minimum_hub_penalty,
763
+ "maximumContextPaths": baseline.config.maximum_context_paths,
764
+ "rollingWindowDays": baseline.config.rolling_window_days,
765
+ },
766
+ "ruleVersions": {
767
+ "facts": STRUCTURAL_FACT_RULE_VERSION,
768
+ "metrics": STRUCTURAL_METRIC_RULE_VERSION,
769
+ "thresholds": STRUCTURAL_THRESHOLD_VERSION,
770
+ },
771
+ "summary": {
772
+ "eligibleCommits": baseline.summary.eligible_commits,
773
+ "eligibleFiles": baseline.summary.eligible_files,
774
+ "rawEdges": baseline.summary.raw_edges,
775
+ "cappedCommits": baseline.summary.capped_commits,
776
+ },
777
+ "materialization": {
778
+ "hotspots": [
779
+ {
780
+ "path": value.path,
781
+ "changeCount": value.change_count,
782
+ "percentile": value.percentile,
783
+ "recentPercentile": value.recent_percentile,
784
+ "confidence": value.confidence,
785
+ }
786
+ for value in baseline.materialization.file_metrics
787
+ ],
788
+ "couplings": [
789
+ {
790
+ "leftPath": value.left_path,
791
+ "rightPath": value.right_path,
792
+ "coChangeCount": value.co_change_count,
793
+ "subsetRatio": value.subset_ratio,
794
+ "leftConditional": value.left_conditional,
795
+ "rightConditional": value.right_conditional,
796
+ "jaccard": value.jaccard,
797
+ "hubPenalty": value.hub_penalty,
798
+ "crossModule": value.cross_module,
799
+ "confidence": value.confidence,
800
+ }
801
+ for value in baseline.materialization.edge_metrics
802
+ ],
803
+ "confidence": baseline.materialization.confidence,
804
+ "gaps": list(baseline.materialization.gaps),
805
+ "limitations": list(baseline.materialization.limitations),
806
+ },
807
+ }
808
+
809
+
810
+ def _eligible_git_paths(commit: GitCommit) -> tuple[tuple[str, ...], str | None]:
811
+ if commit.is_merge:
812
+ return (), "MERGE"
813
+ normalized = tuple(
814
+ sorted(
815
+ {
816
+ path
817
+ for change in commit.changes
818
+ for path in (change.new_path or change.old_path,)
819
+ if path and not is_generated_path(path)
820
+ }
821
+ )
822
+ )
823
+ if not normalized:
824
+ return (), "NOISE_ONLY"
825
+ if (
826
+ all(change.is_binary for change in commit.changes)
827
+ and commit.insertions + commit.deletions == 0
828
+ ):
829
+ return (), "BINARY_ONLY"
830
+ return normalized, None
831
+
832
+
833
+ def _module(path: str) -> str:
834
+ normalized = path.replace("\\", "/").strip("/")
835
+ return normalized.split("/", maxsplit=1)[0] if "/" in normalized else "root"
836
+
837
+
838
+ def _aware_utc(value: Any) -> datetime:
839
+ if not isinstance(value, datetime):
840
+ raise TypeError("Expected datetime")
841
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)