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,256 @@
1
+ """Safe loader, schema validator, ReDoS guard, and cache-fingerprint generator for Declarative Plugins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from repodna.plugins.models import (
12
+ MAX_MANIFEST_BYTES,
13
+ MAX_REGEX_LEN,
14
+ MAX_RULES_PER_PACK,
15
+ MAX_YAML_DEPTH,
16
+ PLUGIN_SCHEMA_VERSION,
17
+ DeclarativePluginManifest,
18
+ PluginValidationError,
19
+ )
20
+
21
+ # Structural ReDoS guard (SEC-10): enforces a safe linear-time regex subset without private APIs
22
+ _BACKREF_OR_LOOKAROUND_RE = re.compile(r"\\[1-9]|\(\?[=!<]")
23
+ _BOUNDED_QUANT_RE = re.compile(r"\{(\d+)(?:,(\d*))?\}")
24
+ _ADJACENT_UNBOUNDED_RE = re.compile(
25
+ r"(?:\.\*|\.\+|\\w\+|\\w\*|\\S\+|\\S\*|\[[^\]]+\][+*])(?:\.\*|\.\+|\\w\+|\\w\*|\\S\+|\\S\*|\[[^\]]+\][+*])"
26
+ )
27
+ _MAX_BOUNDED_REPEAT = 32
28
+
29
+
30
+ def _has_unsafe_nested_or_alternation_quantifier(pattern: str) -> bool:
31
+ """Walks the regex structure tracking group depth to reject nested quantifiers and quantified alternations."""
32
+ # Stack frames: [has_inner_quantifier, has_alternation]
33
+ stack: list[list[bool]] = []
34
+ in_char_class = False
35
+ i = 0
36
+ n = len(pattern)
37
+ while i < n:
38
+ ch = pattern[i]
39
+ if ch == "\\":
40
+ i += 2
41
+ continue
42
+ if in_char_class:
43
+ if ch == "]":
44
+ in_char_class = False
45
+ i += 1
46
+ continue
47
+ if ch == "[":
48
+ in_char_class = True
49
+ i += 1
50
+ continue
51
+ if ch == "(":
52
+ stack.append([False, False])
53
+ i += 1
54
+ continue
55
+ if ch == "|":
56
+ if stack:
57
+ stack[-1][1] = True
58
+ i += 1
59
+ continue
60
+ if ch == ")":
61
+ frame = stack.pop() if stack else [False, False]
62
+ # Check if this group is followed by a quantifier (+, *, ?, or {m,n})
63
+ next_idx = i + 1
64
+ is_quantified = False
65
+ if next_idx < n and pattern[next_idx] in "+*?{":
66
+ # A bare single optional `?` on a non-nested group is safe; +, *, {n,m} with repeat > 1 are dangerous
67
+ if pattern[next_idx] in "+*{":
68
+ is_quantified = True
69
+ elif pattern[next_idx] == "?" and frame[0]:
70
+ is_quantified = True
71
+ if is_quantified and (frame[0] or frame[1]):
72
+ return True
73
+ if stack and (frame[0] or is_quantified):
74
+ stack[-1][0] = True
75
+ i += 1
76
+ continue
77
+ if ch in "+*{" and stack:
78
+ stack[-1][0] = True
79
+ i += 1
80
+ return False
81
+
82
+
83
+ def validate_safe_regex(pattern: str) -> re.Pattern[str]:
84
+ """Validates and compiles a bounded regex while rejecting ReDoS-prone constructs (SEC-10)."""
85
+ if not isinstance(pattern, str) or not pattern:
86
+ raise PluginValidationError("INVALID_REGEX", "Regex pattern must be a non-empty string.")
87
+ if len(pattern) > MAX_REGEX_LEN:
88
+ raise PluginValidationError(
89
+ "REGEX_TOO_LONG",
90
+ f"Regex length {len(pattern)} exceeds maximum allowed length of {MAX_REGEX_LEN}.",
91
+ )
92
+ if _BACKREF_OR_LOOKAROUND_RE.search(pattern):
93
+ raise PluginValidationError(
94
+ "UNSAFE_REDOS_REGEX",
95
+ f"Regex '{pattern}' rejected by ReDoS guard (backreferences and lookarounds are disallowed).",
96
+ )
97
+ for m in _BOUNDED_QUANT_RE.finditer(pattern):
98
+ low = int(m.group(1))
99
+ high = int(m.group(2)) if m.group(2) else low
100
+ if low > _MAX_BOUNDED_REPEAT or high > _MAX_BOUNDED_REPEAT:
101
+ raise PluginValidationError(
102
+ "UNSAFE_REDOS_REGEX",
103
+ f"Regex '{pattern}' rejected by ReDoS guard (bounded repetition exceeds {_MAX_BOUNDED_REPEAT}).",
104
+ )
105
+ if _ADJACENT_UNBOUNDED_RE.search(pattern) or _has_unsafe_nested_or_alternation_quantifier(pattern):
106
+ raise PluginValidationError(
107
+ "UNSAFE_REDOS_REGEX",
108
+ f"Regex '{pattern}' rejected by ReDoS guard (nested/overlapping quantifiers or quantified alternation disallowed).",
109
+ )
110
+ try:
111
+ return re.compile(pattern)
112
+ except re.error as exc:
113
+ raise PluginValidationError("INVALID_REGEX", f"Invalid regex '{pattern}': {exc}") from exc
114
+
115
+
116
+ def _check_nesting_depth(obj: Any, current: int = 0) -> None:
117
+ if current > MAX_YAML_DEPTH:
118
+ raise PluginValidationError(
119
+ "EXCESSIVE_NESTING",
120
+ f"Plugin manifest nesting depth exceeds maximum allowed ({MAX_YAML_DEPTH}).",
121
+ )
122
+ if isinstance(obj, dict):
123
+ for v in obj.values():
124
+ _check_nesting_depth(v, current + 1)
125
+ elif isinstance(obj, list):
126
+ for item in obj:
127
+ _check_nesting_depth(item, current + 1)
128
+
129
+
130
+ def load_and_validate_plugin_manifest(
131
+ manifest_path: Path | str,
132
+ *,
133
+ repo_root: Path | None = None,
134
+ ) -> DeclarativePluginManifest:
135
+ """Safely loads and validates a YAML/JSON declarative plugin manifest.
136
+
137
+ Enforces:
138
+ - Repository boundary containment if `repo_root` is provided.
139
+ - Maximum manifest size (`MAX_MANIFEST_BYTES`).
140
+ - Safe YAML loading (`yaml.safe_load`, no Python object tags).
141
+ - Nesting depth cap (`MAX_YAML_DEPTH`).
142
+ - Schema version compatibility (`1.0`).
143
+ - Duplicate rule_id rejection and safe regex validation.
144
+ """
145
+ p = Path(manifest_path).resolve()
146
+ if repo_root is not None:
147
+ root_res = repo_root.resolve()
148
+ try:
149
+ p.relative_to(root_res)
150
+ except ValueError as exc:
151
+ raise PluginValidationError(
152
+ "PATH_OUTSIDE_REPO",
153
+ f"Plugin manifest '{p}' escapes authorized repository root '{root_res}'.",
154
+ ) from exc
155
+
156
+ if not p.exists() or not p.is_file():
157
+ raise PluginValidationError("MANIFEST_NOT_FOUND", f"Plugin manifest not found: '{p}'.")
158
+
159
+ size = p.stat().st_size
160
+ if size > MAX_MANIFEST_BYTES:
161
+ raise PluginValidationError(
162
+ "MANIFEST_TOO_LARGE",
163
+ f"Plugin manifest size ({size:,} bytes) exceeds maximum ({MAX_MANIFEST_BYTES:,} bytes).",
164
+ )
165
+
166
+ raw_text = p.read_text(encoding="utf-8", errors="replace")
167
+ try:
168
+ if p.suffix.lower() == ".json":
169
+ data = json.loads(raw_text)
170
+ else:
171
+ from repodna.security.safe_yaml import safe_load_bounded_yaml
172
+
173
+ data = safe_load_bounded_yaml(raw_text, max_bytes=MAX_MANIFEST_BYTES, max_aliases=0)
174
+ except Exception as exc:
175
+ raise PluginValidationError("PARSE_ERROR", f"Failed to parse plugin manifest '{p.name}': {exc}") from exc
176
+
177
+ if not isinstance(data, dict):
178
+ raise PluginValidationError("INVALID_ROOT", "Plugin manifest root must be a YAML/JSON mapping.")
179
+
180
+ _check_nesting_depth(data)
181
+
182
+ # Reject unknown executable keys explicitly
183
+ for forbidden_key in (
184
+ "entrypoint",
185
+ "python_module",
186
+ "script",
187
+ "command",
188
+ "exec",
189
+ "shell",
190
+ "eval",
191
+ "python",
192
+ "hook",
193
+ ):
194
+ if forbidden_key in data:
195
+ raise PluginValidationError(
196
+ "EXECUTABLE_PLUGIN_DISALLOWED",
197
+ f"Field '{forbidden_key}' is forbidden in zero-execution declarative plugins.",
198
+ )
199
+
200
+ try:
201
+ manifest = DeclarativePluginManifest.model_validate(data)
202
+ except Exception as exc:
203
+ raise PluginValidationError("SCHEMA_INVALID", f"Manifest schema validation failed: {exc}") from exc
204
+
205
+ if manifest.schema_version != PLUGIN_SCHEMA_VERSION:
206
+ raise PluginValidationError(
207
+ "UNSUPPORTED_SCHEMA_VERSION",
208
+ f"Unsupported plugin schema_version '{manifest.schema_version}'; expected '{PLUGIN_SCHEMA_VERSION}'.",
209
+ )
210
+
211
+ if len(manifest.rules) > MAX_RULES_PER_PACK:
212
+ raise PluginValidationError(
213
+ "TOO_MANY_RULES",
214
+ f"Manifest defines {len(manifest.rules)} rules; maximum allowed is {MAX_RULES_PER_PACK}.",
215
+ )
216
+
217
+ seen_rule_ids: set[str] = set()
218
+ for rule in manifest.rules:
219
+ if rule.rule_id in seen_rule_ids:
220
+ raise PluginValidationError("DUPLICATE_RULE_ID", f"Duplicate rule_id '{rule.rule_id}' in '{manifest.plugin_id}'.")
221
+ seen_rule_ids.add(rule.rule_id)
222
+ for regex_key in ("pattern", "regex", "import_pattern", "required_pattern", "forbidden_pattern"):
223
+ val = rule.params.get(regex_key)
224
+ if val is not None:
225
+ validate_safe_regex(str(val))
226
+
227
+ return manifest
228
+
229
+
230
+ def discover_local_plugin_manifests(repo_root: Path) -> list[Path]:
231
+ """Discovers declarative plugin manifests under `.repodna/plugins/*.{yml,yaml,json}`."""
232
+ plugins_dir = (repo_root.resolve() / ".repodna" / "plugins")
233
+ if not plugins_dir.exists() or not plugins_dir.is_dir():
234
+ return []
235
+ found: list[Path] = []
236
+ for item in sorted(plugins_dir.iterdir()):
237
+ if item.is_file() and item.suffix.lower() in (".yml", ".yaml", ".json") and not item.is_symlink():
238
+ found.append(item)
239
+ return found[:25]
240
+
241
+
242
+ def compute_plugins_fingerprint(manifests: list[DeclarativePluginManifest]) -> str:
243
+ """Computes a deterministic SHA-256 fingerprint across active plugin manifests for cache invalidation."""
244
+ if not manifests:
245
+ return "no_plugins"
246
+ canonical = json.dumps(
247
+ [m.model_dump(mode="json") for m in sorted(manifests, key=lambda x: (x.plugin_id, x.plugin_version))],
248
+ sort_keys=True,
249
+ separators=(",", ":"),
250
+ )
251
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
252
+
253
+
254
+ def export_plugin_json_schema() -> dict[str, Any]:
255
+ """Exports the JSON Schema for DeclarativePluginManifest v1.0."""
256
+ return DeclarativePluginManifest.model_json_schema()
@@ -0,0 +1,91 @@
1
+ """RepoDNA v0.10.0 Deep Code Intelligence package."""
2
+
3
+ from repodna.quality.complexity import analyze_file_complexity
4
+ from repodna.quality.config import (
5
+ KNOWN_QUALITY_RULES,
6
+ compute_ruleset_fingerprint,
7
+ find_quality_config_file,
8
+ load_quality_config,
9
+ )
10
+ from repodna.quality.debt import compute_technical_debt
11
+ from repodna.quality.duplicates import detect_duplicates
12
+ from repodna.quality.engine import QualityIntelligenceEngine
13
+ from repodna.quality.impact import compute_symbol_impact
14
+ from repodna.quality.models import (
15
+ QUALITY_ENGINE_VERSION,
16
+ QUALITY_SCHEMA_VERSION,
17
+ CloneGroup,
18
+ CloneLocation,
19
+ CloneType,
20
+ ComplexityContributor,
21
+ DuplicateAnalysisSummary,
22
+ FindingCategory,
23
+ FindingStatus,
24
+ QualityConfidence,
25
+ QualityConfig,
26
+ QualityFinding,
27
+ QualityReport,
28
+ SecuritySignal,
29
+ SecuritySignalCategory,
30
+ SymbolComplexityMetric,
31
+ SymbolImpactChangeKind,
32
+ SymbolImpactItem,
33
+ SymbolImpactReport,
34
+ TechnicalDebtItem,
35
+ TechnicalDebtSummary,
36
+ TestMappingEntry,
37
+ TestMappingSummary,
38
+ TestRelationshipKind,
39
+ UnusedCandidateCategory,
40
+ UnusedCodeCandidate,
41
+ )
42
+ from repodna.quality.rules import evaluate_quality_rules
43
+ from repodna.quality.sarif import export_quality_to_json, export_quality_to_sarif
44
+ from repodna.quality.security_signals import analyze_file_security_signals, redact_secrets_in_text
45
+ from repodna.quality.test_mapping import build_static_test_mapping
46
+ from repodna.quality.unused import analyze_unused_candidates
47
+
48
+ __all__ = [
49
+ "KNOWN_QUALITY_RULES",
50
+ "QUALITY_ENGINE_VERSION",
51
+ "QUALITY_SCHEMA_VERSION",
52
+ "CloneGroup",
53
+ "CloneLocation",
54
+ "CloneType",
55
+ "ComplexityContributor",
56
+ "DuplicateAnalysisSummary",
57
+ "FindingCategory",
58
+ "FindingStatus",
59
+ "QualityConfidence",
60
+ "QualityConfig",
61
+ "QualityFinding",
62
+ "QualityIntelligenceEngine",
63
+ "QualityReport",
64
+ "SecuritySignal",
65
+ "SecuritySignalCategory",
66
+ "SymbolComplexityMetric",
67
+ "SymbolImpactChangeKind",
68
+ "SymbolImpactItem",
69
+ "SymbolImpactReport",
70
+ "TechnicalDebtItem",
71
+ "TechnicalDebtSummary",
72
+ "TestMappingEntry",
73
+ "TestMappingSummary",
74
+ "TestRelationshipKind",
75
+ "UnusedCandidateCategory",
76
+ "UnusedCodeCandidate",
77
+ "analyze_file_complexity",
78
+ "analyze_file_security_signals",
79
+ "analyze_unused_candidates",
80
+ "build_static_test_mapping",
81
+ "compute_ruleset_fingerprint",
82
+ "compute_symbol_impact",
83
+ "compute_technical_debt",
84
+ "detect_duplicates",
85
+ "evaluate_quality_rules",
86
+ "export_quality_to_json",
87
+ "export_quality_to_sarif",
88
+ "find_quality_config_file",
89
+ "load_quality_config",
90
+ "redact_secrets_in_text",
91
+ ]
@@ -0,0 +1,352 @@
1
+ """Language-aware deterministic Cyclomatic & Nesting-Weighted Complexity Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from repodna.brain.models import SymbolDefinition, SymbolKind
8
+ from repodna.parsers.capabilities import CapabilityLevel, get_language_capability
9
+ from repodna.parsers.treesitter_parser import _TS_PARSERS, _init_treesitter_parsers, _node_text
10
+ from repodna.quality.models import ComplexityContributor, SymbolComplexityMetric
11
+
12
+ _PARSER_KEY_BY_LANG: dict[str, str] = {
13
+ "Python": "python",
14
+ "TypeScript": "typescript",
15
+ "TypeScript (TSX)": "tsx",
16
+ "JavaScript": "javascript",
17
+ "JavaScript (JSX)": "javascript",
18
+ "Go": "go",
19
+ "Rust": "rust",
20
+ "C#": "c_sharp",
21
+ "Java": "java",
22
+ "C": "c",
23
+ "C++": "cpp",
24
+ "C/C++ Header": "cpp",
25
+ "C++ Header": "cpp",
26
+ }
27
+
28
+ _FUNCTION_NODE_TYPES: dict[str, frozenset[str]] = {
29
+ "python": frozenset({"function_definition"}),
30
+ "typescript": frozenset({"function_declaration", "method_definition", "arrow_function", "function_expression"}),
31
+ "tsx": frozenset({"function_declaration", "method_definition", "arrow_function", "function_expression"}),
32
+ "javascript": frozenset({"function_declaration", "method_definition", "arrow_function", "function_expression"}),
33
+ "go": frozenset({"function_declaration", "method_declaration"}),
34
+ "rust": frozenset({"function_item"}),
35
+ "c_sharp": frozenset({"method_declaration", "constructor_declaration", "destructor_declaration", "local_function_statement"}),
36
+ "java": frozenset({"method_declaration", "constructor_declaration"}),
37
+ "c": frozenset({"function_definition"}),
38
+ "cpp": frozenset({"function_definition"}),
39
+ }
40
+
41
+ _BRANCH_NODE_TYPES: dict[str, frozenset[str]] = {
42
+ "python": frozenset({
43
+ "if_statement", "elif_clause", "for_statement", "while_statement",
44
+ "except_clause", "conditional_expression", "case_clause",
45
+ "for_in_clause", "if_clause",
46
+ }),
47
+ "typescript": frozenset({
48
+ "if_statement", "for_statement", "for_in_statement", "while_statement",
49
+ "do_statement", "switch_case", "catch_clause", "ternary_expression",
50
+ }),
51
+ "tsx": frozenset({
52
+ "if_statement", "for_statement", "for_in_statement", "while_statement",
53
+ "do_statement", "switch_case", "catch_clause", "ternary_expression",
54
+ }),
55
+ "javascript": frozenset({
56
+ "if_statement", "for_statement", "for_in_statement", "while_statement",
57
+ "do_statement", "switch_case", "catch_clause", "ternary_expression",
58
+ }),
59
+ "go": frozenset({
60
+ "if_statement", "for_statement", "expression_case", "type_case",
61
+ "communication_case",
62
+ }),
63
+ "rust": frozenset({
64
+ "if_expression", "for_expression", "while_expression", "loop_expression",
65
+ "match_arm",
66
+ }),
67
+ "c_sharp": frozenset({
68
+ "if_statement", "for_statement", "foreach_statement", "while_statement",
69
+ "do_statement", "switch_section", "catch_clause", "conditional_expression",
70
+ "switch_expression_arm",
71
+ }),
72
+ "java": frozenset({
73
+ "if_statement", "for_statement", "enhanced_for_statement", "while_statement",
74
+ "do_statement", "switch_block_statement_group", "switch_rule",
75
+ "catch_clause", "ternary_expression",
76
+ }),
77
+ "c": frozenset({
78
+ "if_statement", "for_statement", "while_statement", "do_statement",
79
+ "case_statement", "conditional_expression",
80
+ }),
81
+ "cpp": frozenset({
82
+ "if_statement", "for_statement", "for_range_loop", "while_statement",
83
+ "do_statement", "case_statement", "catch_clause", "conditional_expression",
84
+ }),
85
+ }
86
+
87
+ _NESTING_NODE_TYPES: frozenset[str] = frozenset({
88
+ "if_statement", "if_expression", "for_statement", "for_in_statement",
89
+ "for_range_loop", "foreach_statement", "enhanced_for_statement",
90
+ "while_statement", "while_expression", "do_statement", "loop_expression",
91
+ "switch_statement", "switch_expression", "match_expression",
92
+ "try_statement", "catch_clause", "except_clause",
93
+ })
94
+
95
+ _RETURN_NODE_TYPES: frozenset[str] = frozenset({
96
+ "return_statement", "return_expression", "yield", "throw_statement", "raise_statement",
97
+ })
98
+
99
+ _BOOL_OPS = frozenset({"&&", "||", "and", "or", "??"})
100
+
101
+ _MAX_AST_DEPTH = 150
102
+
103
+
104
+ def _count_parameters(source_bytes: bytes, fn_node: Any, parser_key: str) -> int:
105
+ params_node = fn_node.child_by_field_name("parameters")
106
+ if params_node is None and parser_key in ("c", "cpp"):
107
+ decl = fn_node.child_by_field_name("declarator")
108
+ if decl is not None:
109
+ params_node = decl.child_by_field_name("parameters")
110
+ if params_node is None:
111
+ return 0
112
+ count = 0
113
+ for ch in params_node.named_children:
114
+ if ch.type in ("comment", "decorator"):
115
+ continue
116
+ txt = _node_text(source_bytes, ch).strip()
117
+ if not txt or txt in ("self", "cls", "void"):
118
+ continue
119
+ count += 1
120
+ return count
121
+
122
+
123
+ def _count_logical_sloc(lines: list[str], line_start: int, line_end: int) -> int:
124
+ sloc = 0
125
+ for ln in lines[max(0, line_start - 1) : min(len(lines), line_end)]:
126
+ s = ln.strip()
127
+ if not s or s.startswith(("//", "#", "/*", "*", "*/")):
128
+ continue
129
+ sloc += 1
130
+ return sloc
131
+
132
+
133
+ def _measure_function_node(
134
+ source_bytes: bytes,
135
+ lines: list[str],
136
+ fn_node: Any,
137
+ parser_key: str,
138
+ ) -> tuple[int, int, int, int, int, int, int, list[ComplexityContributor]]:
139
+ """
140
+ Compute (cyclomatic, nesting_weighted, max_nesting, logical_sloc, param_count,
141
+ branch_count, return_count, contributors) for one AST function/method node.
142
+ """
143
+ branch_types = _BRANCH_NODE_TYPES.get(parser_key, frozenset())
144
+ fn_types = _FUNCTION_NODE_TYPES.get(parser_key, frozenset())
145
+
146
+ cyclomatic = 1
147
+ nesting_weighted = 0
148
+ max_nesting = 0
149
+ branch_count = 0
150
+ return_count = 0
151
+ contributors: list[ComplexityContributor] = []
152
+
153
+ # Iterative DFS with explicit (node, depth, ast_depth) to avoid Python RecursionError on hostile inputs
154
+ stack: list[tuple[Any, int, int]] = [(ch, 0, 1) for ch in reversed(fn_node.children)]
155
+ while stack:
156
+ node, nest_depth, ast_depth = stack.pop()
157
+ if ast_depth > _MAX_AST_DEPTH:
158
+ continue
159
+ ntype = node.type
160
+ line_no = node.start_point[0] + 1
161
+
162
+ # Do not double-count nested inner function bodies into outer function complexity
163
+ if ntype in fn_types and node is not fn_node:
164
+ continue
165
+
166
+ if ntype in branch_types:
167
+ cyclomatic += 1
168
+ branch_count += 1
169
+ nw_delta = 1 + nest_depth
170
+ nesting_weighted += nw_delta
171
+ if len(contributors) < 100:
172
+ contributors.append(
173
+ ComplexityContributor(
174
+ construct_kind=ntype,
175
+ line=line_no,
176
+ cyclomatic_delta=1,
177
+ nesting_depth=nest_depth,
178
+ nesting_weighted_delta=nw_delta,
179
+ )
180
+ )
181
+ elif ntype in ("boolean_operator", "binary_expression"):
182
+ op_node = node.child_by_field_name("operator")
183
+ op_text = _node_text(source_bytes, op_node).strip() if op_node is not None else ""
184
+ if op_text in _BOOL_OPS:
185
+ cyclomatic += 1
186
+ branch_count += 1
187
+ nesting_weighted += 1
188
+ if len(contributors) < 100:
189
+ contributors.append(
190
+ ComplexityContributor(
191
+ construct_kind=f"boolean_op({op_text})",
192
+ line=line_no,
193
+ cyclomatic_delta=1,
194
+ nesting_depth=nest_depth,
195
+ nesting_weighted_delta=1,
196
+ )
197
+ )
198
+
199
+ if ntype in _RETURN_NODE_TYPES:
200
+ return_count += 1
201
+
202
+ next_nest = nest_depth + 1 if ntype in _NESTING_NODE_TYPES else nest_depth
203
+ if next_nest > max_nesting:
204
+ max_nesting = next_nest
205
+
206
+ for ch in reversed(node.children):
207
+ stack.append((ch, next_nest, ast_depth + 1))
208
+
209
+ line_start = fn_node.start_point[0] + 1
210
+ line_end = max(line_start, fn_node.end_point[0] + 1)
211
+ logical_sloc = _count_logical_sloc(lines, line_start, line_end)
212
+ param_count = _count_parameters(source_bytes, fn_node, parser_key)
213
+ return (
214
+ cyclomatic,
215
+ nesting_weighted,
216
+ max_nesting,
217
+ logical_sloc,
218
+ param_count,
219
+ branch_count,
220
+ return_count,
221
+ contributors,
222
+ )
223
+
224
+
225
+ def analyze_file_complexity(
226
+ *,
227
+ file_path: str,
228
+ content: str,
229
+ language: str,
230
+ symbols: list[SymbolDefinition],
231
+ ) -> list[SymbolComplexityMetric]:
232
+ """
233
+ Compute deterministic complexity metrics for all function/method/constructor symbols in `file_path`.
234
+ Returns `cyclomatic_complexity=None` and `capability=UNSUPPORTED` for unsupported languages (never fake 0).
235
+ """
236
+ callable_syms = [
237
+ s
238
+ for s in symbols
239
+ if s.kind in (SymbolKind.FUNCTION, SymbolKind.METHOD, SymbolKind.CONSTRUCTOR, SymbolKind.DESTRUCTOR)
240
+ ]
241
+ if not callable_syms:
242
+ return []
243
+
244
+ cap = get_language_capability(language)
245
+ parser_key = _PARSER_KEY_BY_LANG.get(language)
246
+ _init_treesitter_parsers()
247
+ ts_parser = _TS_PARSERS.get(parser_key) if parser_key else None
248
+
249
+ if cap.complexity == CapabilityLevel.UNSUPPORTED or ts_parser is None or parser_key is None:
250
+ return [
251
+ SymbolComplexityMetric(
252
+ symbol_id=s.id,
253
+ symbol_name=s.name,
254
+ qualified_name=s.qualified_name,
255
+ file_path=file_path,
256
+ language=language,
257
+ line_start=s.line_start,
258
+ line_end=s.line_end,
259
+ cyclomatic_complexity=None,
260
+ nesting_weighted_complexity=None,
261
+ max_nesting_depth=None,
262
+ logical_sloc=None,
263
+ function_length=max(1, s.line_end - s.line_start + 1),
264
+ parameter_count=None,
265
+ branch_count=None,
266
+ return_count=None,
267
+ capability=CapabilityLevel.UNSUPPORTED,
268
+ has_syntax_error=s.has_syntax_error,
269
+ evidence_id=s.evidence_id,
270
+ )
271
+ for s in callable_syms
272
+ ]
273
+
274
+ source_bytes = content.encode("utf-8", errors="replace")
275
+ lines = content.replace("\r\n", "\n").replace("\r", "\n").splitlines()
276
+ tree = ts_parser.parse(source_bytes)
277
+ file_has_error = bool(tree.root_node.has_error)
278
+
279
+ # Index AST function nodes by starting line for O(1) symbol matching
280
+ fn_types = _FUNCTION_NODE_TYPES.get(parser_key, frozenset())
281
+ nodes_by_line: dict[int, list[Any]] = {}
282
+ stack = [tree.root_node]
283
+ while stack:
284
+ n = stack.pop()
285
+ if n.type in fn_types:
286
+ ln = n.start_point[0] + 1
287
+ nodes_by_line.setdefault(ln, []).append(n)
288
+ stack.extend(reversed(n.children))
289
+
290
+ results: list[SymbolComplexityMetric] = []
291
+ for sym in callable_syms:
292
+ fn_node = None
293
+ # Match exact line or decorated definition (+1..+5 lines down)
294
+ for offset in range(0, 6):
295
+ cands = nodes_by_line.get(sym.line_start + offset)
296
+ if cands:
297
+ fn_node = cands[0]
298
+ break
299
+
300
+ if fn_node is None:
301
+ results.append(
302
+ SymbolComplexityMetric(
303
+ symbol_id=sym.id,
304
+ symbol_name=sym.name,
305
+ qualified_name=sym.qualified_name,
306
+ file_path=file_path,
307
+ language=language,
308
+ line_start=sym.line_start,
309
+ line_end=sym.line_end,
310
+ cyclomatic_complexity=None,
311
+ nesting_weighted_complexity=None,
312
+ max_nesting_depth=None,
313
+ logical_sloc=None,
314
+ function_length=max(1, sym.line_end - sym.line_start + 1),
315
+ parameter_count=None,
316
+ branch_count=None,
317
+ return_count=None,
318
+ capability=CapabilityLevel.PARTIAL,
319
+ has_syntax_error=file_has_error or sym.has_syntax_error,
320
+ evidence_id=sym.evidence_id,
321
+ )
322
+ )
323
+ continue
324
+
325
+ cc, nw, max_nest, sloc, params, branches, returns, contribs = _measure_function_node(
326
+ source_bytes, lines, fn_node, parser_key
327
+ )
328
+ results.append(
329
+ SymbolComplexityMetric(
330
+ symbol_id=sym.id,
331
+ symbol_name=sym.name,
332
+ qualified_name=sym.qualified_name,
333
+ file_path=file_path,
334
+ language=language,
335
+ line_start=sym.line_start,
336
+ line_end=sym.line_end,
337
+ cyclomatic_complexity=cc,
338
+ nesting_weighted_complexity=nw,
339
+ max_nesting_depth=max_nest,
340
+ logical_sloc=sloc,
341
+ function_length=max(1, sym.line_end - sym.line_start + 1),
342
+ parameter_count=params,
343
+ branch_count=branches,
344
+ return_count=returns,
345
+ capability=cap.complexity,
346
+ has_syntax_error=file_has_error or bool(fn_node.has_error) or sym.has_syntax_error,
347
+ contributors=contribs,
348
+ evidence_id=sym.evidence_id,
349
+ )
350
+ )
351
+
352
+ return results