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,278 @@
1
+ """Bounded AST-only structural security signal detector with strict secret redaction.
2
+
3
+ Honesty & Security Invariants:
4
+ - RepoDNA is NOT a full SAST or taint-tracking engine; these are structural AST signals only.
5
+ - Uses Tree-sitter AST call/assignment nodes so comments, docstrings, and string literals
6
+ do NOT trigger false positives for API calls.
7
+ - Severity and confidence are strictly separated.
8
+ - Raw secret values are NEVER stored in signals, evidence snippets, SSE, MCP, or exports.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import re
15
+ from typing import Any
16
+
17
+ from repodna.parsers.capabilities import CapabilityLevel, get_language_capability
18
+ from repodna.parsers.treesitter_parser import _TS_PARSERS, _init_treesitter_parsers, _node_text
19
+ from repodna.quality.complexity import _PARSER_KEY_BY_LANG
20
+ from repodna.quality.models import (
21
+ QualityConfidence,
22
+ SecuritySignal,
23
+ SecuritySignalCategory,
24
+ )
25
+ from repodna.schemas.models import SeverityLevel
26
+
27
+ _CALL_NODE_TYPES = frozenset({
28
+ "call", "call_expression", "invocation_expression", "method_invocation", "new_expression",
29
+ "object_creation_expression",
30
+ })
31
+ _ASSIGN_NODE_TYPES = frozenset({
32
+ "assignment", "assignment_expression", "variable_declarator", "init_declarator",
33
+ })
34
+
35
+ _SECRET_VAR_RE = re.compile(
36
+ r"(?:^|_)(api_?key|secret_?key|access_?token|private_?key|auth_?token|password|passwd|client_?secret)$",
37
+ re.IGNORECASE,
38
+ )
39
+ _PLACEHOLDER_RE = re.compile(
40
+ r"^(?:changeme|example|dummy|test|fake|placeholder|your[_-]|xxx+|redacted|\$\{|<.*>|\s*)$",
41
+ re.IGNORECASE,
42
+ )
43
+ _KNOWN_TOKEN_PREFIX_RE = re.compile(
44
+ r"(?:ghp_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN (?:RSA |EC )?PRIVATE KEY-----)"
45
+ )
46
+
47
+
48
+ def redact_secrets_in_text(text: str) -> str:
49
+ """Redact high-confidence secret tokens and quoted credential assignments."""
50
+ redacted = _KNOWN_TOKEN_PREFIX_RE.sub("[REDACTED_SECRET]", text)
51
+ redacted = re.sub(
52
+ r"""((?:api_?key|secret_?key|access_?token|private_?key|auth_?token|password|passwd|client_?secret)\s*[:=]\s*["'])([^"']{4,})(["'])""",
53
+ r"\1[REDACTED]\3",
54
+ redacted,
55
+ flags=re.IGNORECASE,
56
+ )
57
+ return redacted
58
+
59
+
60
+ def _signal_id(file_path: str, rule_id: str, line: int, detail: str) -> str:
61
+ h = hashlib.sha256(f"{file_path}|{rule_id}|{line}|{detail}".encode()).hexdigest()[:14]
62
+ return f"sec_{h}"
63
+
64
+
65
+ def _classify_call_signal(
66
+ fn_text: str, full_call_text: str, language: str
67
+ ) -> tuple[str, SecuritySignalCategory, SeverityLevel, QualityConfidence, str | None, str] | None:
68
+ fn = fn_text.strip()
69
+ lower = fn.lower()
70
+
71
+ # 1. Risky dynamic execution
72
+ if language == "Python" and fn in ("eval", "exec", "compile"):
73
+ return (
74
+ "SEC-AST-001",
75
+ SecuritySignalCategory.DYNAMIC_EXECUTION,
76
+ SeverityLevel.WARNING,
77
+ QualityConfidence.MEDIUM,
78
+ "CWE-95",
79
+ f"Dynamic code execution call '{fn}(...)' detected in AST.",
80
+ )
81
+ if language.startswith(("JavaScript", "TypeScript")) and fn in ("eval", "Function", "window.eval"):
82
+ return (
83
+ "SEC-AST-001",
84
+ SecuritySignalCategory.DYNAMIC_EXECUTION,
85
+ SeverityLevel.WARNING,
86
+ QualityConfidence.MEDIUM,
87
+ "CWE-95",
88
+ f"Dynamic JavaScript execution call '{fn}(...)' detected in AST.",
89
+ )
90
+
91
+ # 2. Unsafe deserialization candidates
92
+ if language == "Python" and fn in ("pickle.loads", "pickle.load", "marshal.loads", "yaml.load"):
93
+ if fn == "yaml.load" and "SafeLoader" in full_call_text:
94
+ return None
95
+ return (
96
+ "SEC-AST-002",
97
+ SecuritySignalCategory.UNSAFE_DESERIALIZATION,
98
+ SeverityLevel.CRITICAL if "pickle" in fn else SeverityLevel.WARNING,
99
+ QualityConfidence.MEDIUM,
100
+ "CWE-502",
101
+ f"Potential unsafe deserialization call '{fn}(...)' detected in AST.",
102
+ )
103
+ if language == "C#" and ("BinaryFormatter" in fn or "TypeNameHandling.All" in full_call_text):
104
+ return (
105
+ "SEC-AST-002",
106
+ SecuritySignalCategory.UNSAFE_DESERIALIZATION,
107
+ SeverityLevel.CRITICAL,
108
+ QualityConfidence.MEDIUM,
109
+ "CWE-502",
110
+ f"Potential unsafe .NET deserialization pattern '{fn}' detected in AST.",
111
+ )
112
+ if language == "Java" and ("ObjectInputStream" in fn or fn.endswith(".readObject")):
113
+ return (
114
+ "SEC-AST-002",
115
+ SecuritySignalCategory.UNSAFE_DESERIALIZATION,
116
+ SeverityLevel.WARNING,
117
+ QualityConfidence.LOW,
118
+ "CWE-502",
119
+ f"Potential Java deserialization call '{fn}' detected in AST.",
120
+ )
121
+
122
+ # 3. Weak cryptographic primitives
123
+ if any(
124
+ tok in lower
125
+ for tok in (
126
+ "hashlib.md5",
127
+ "hashlib.sha1",
128
+ "md5.create",
129
+ "sha1.create",
130
+ "messagedigest.getinstance",
131
+ "crypto.createhash",
132
+ )
133
+ ):
134
+ if "getinstance" in lower or "createhash" in lower:
135
+ if not re.search(r"""["'](?:md5|sha-?1)["']""", full_call_text, re.IGNORECASE):
136
+ return None
137
+ return (
138
+ "SEC-AST-003",
139
+ SecuritySignalCategory.WEAK_CRYPTO,
140
+ SeverityLevel.INFO,
141
+ QualityConfidence.MEDIUM,
142
+ "CWE-328",
143
+ f"Weak cryptographic hash primitive candidate '{fn}' detected (verify whether used for security vs non-crypto checksums).",
144
+ )
145
+
146
+ # 4. Unsafe command execution patterns
147
+ if language == "Python" and (
148
+ fn in ("os.system", "os.popen")
149
+ or (fn.startswith("subprocess.") and "shell=True" in full_call_text.replace(" ", ""))
150
+ ):
151
+ return (
152
+ "SEC-AST-004",
153
+ SecuritySignalCategory.UNSAFE_COMMAND_EXEC,
154
+ SeverityLevel.WARNING,
155
+ QualityConfidence.MEDIUM,
156
+ "CWE-78",
157
+ f"Shell command execution pattern '{fn}(...)' detected in AST (verify input sanitization).",
158
+ )
159
+ if language == "Java" and fn.endswith(".exec") and "Runtime" in full_call_text:
160
+ return (
161
+ "SEC-AST-004",
162
+ SecuritySignalCategory.UNSAFE_COMMAND_EXEC,
163
+ SeverityLevel.WARNING,
164
+ QualityConfidence.LOW,
165
+ "CWE-78",
166
+ "Runtime.exec() command execution pattern detected in AST.",
167
+ )
168
+ if language in ("C", "C++") and fn in ("system", "popen", "gets", "strcpy"):
169
+ return (
170
+ "SEC-AST-004",
171
+ SecuritySignalCategory.UNSAFE_COMMAND_EXEC,
172
+ SeverityLevel.WARNING,
173
+ QualityConfidence.MEDIUM,
174
+ "CWE-78" if fn in ("system", "popen") else "CWE-120",
175
+ f"Risky C/C++ standard library call '{fn}(...)' detected in AST.",
176
+ )
177
+
178
+ return None
179
+
180
+
181
+ def analyze_file_security_signals(
182
+ *,
183
+ file_path: str,
184
+ content: str,
185
+ language: str,
186
+ ) -> list[SecuritySignal]:
187
+ """Extract bounded, AST-only structural security signals with strict secret redaction."""
188
+ cap = get_language_capability(language)
189
+ if cap.security_signals == CapabilityLevel.UNSUPPORTED:
190
+ return []
191
+
192
+ parser_key = _PARSER_KEY_BY_LANG.get(language)
193
+ _init_treesitter_parsers()
194
+ ts_parser = _TS_PARSERS.get(parser_key) if parser_key else None
195
+ if ts_parser is None:
196
+ return []
197
+
198
+ source_bytes = content.encode("utf-8", errors="replace")
199
+ tree = ts_parser.parse(source_bytes)
200
+ signals: list[SecuritySignal] = []
201
+
202
+ stack: list[tuple[Any, int]] = [(tree.root_node, 0)]
203
+ while stack and len(signals) < 50:
204
+ node, depth = stack.pop()
205
+ if depth > 140:
206
+ continue
207
+ ntype = node.type
208
+ line_start = node.start_point[0] + 1
209
+ line_end = max(line_start, node.end_point[0] + 1)
210
+
211
+ if ntype in _CALL_NODE_TYPES:
212
+ fn_node = (
213
+ node.child_by_field_name("function")
214
+ or node.child_by_field_name("name")
215
+ or node.child_by_field_name("type")
216
+ or node.child_by_field_name("constructor")
217
+ )
218
+ if fn_node is not None:
219
+ fn_text = _node_text(source_bytes, fn_node).strip()
220
+ full_text = _node_text(source_bytes, node)[:300]
221
+ matched = _classify_call_signal(fn_text, full_text, language)
222
+ if matched is not None:
223
+ rid, cat, sev, conf, cwe, expl = matched
224
+ signals.append(
225
+ SecuritySignal(
226
+ signal_id=_signal_id(file_path, rid, line_start, fn_text),
227
+ rule_id=rid,
228
+ category=cat,
229
+ severity=sev,
230
+ confidence=conf,
231
+ language=language,
232
+ file_path=file_path,
233
+ line_start=line_start,
234
+ line_end=line_end,
235
+ symbol_name=fn_text[:80],
236
+ cwe_id=cwe,
237
+ redacted_snippet=redact_secrets_in_text(full_text)[:200],
238
+ explanation=expl,
239
+ )
240
+ )
241
+ elif ntype in _ASSIGN_NODE_TYPES:
242
+ left = node.child_by_field_name("left") or node.child_by_field_name("name") or node.child_by_field_name("declarator")
243
+ right = node.child_by_field_name("right") or node.child_by_field_name("value")
244
+ if left is not None and right is not None:
245
+ var_name = _node_text(source_bytes, left).strip().split(".")[-1]
246
+ rhs_text = _node_text(source_bytes, right).strip()
247
+ is_str_lit = (
248
+ (rhs_text.startswith('"') and rhs_text.endswith('"'))
249
+ or (rhs_text.startswith("'") and rhs_text.endswith("'"))
250
+ )
251
+ if is_str_lit and _SECRET_VAR_RE.search(var_name):
252
+ unquoted = rhs_text[1:-1].strip()
253
+ if len(unquoted) >= 8 and not _PLACEHOLDER_RE.match(unquoted):
254
+ signals.append(
255
+ SecuritySignal(
256
+ signal_id=_signal_id(file_path, "SEC-AST-005", line_start, var_name),
257
+ rule_id="SEC-AST-005",
258
+ category=SecuritySignalCategory.HARDCODED_CREDENTIAL,
259
+ severity=SeverityLevel.CRITICAL,
260
+ confidence=QualityConfidence.MEDIUM,
261
+ language=language,
262
+ file_path=file_path,
263
+ line_start=line_start,
264
+ line_end=line_end,
265
+ symbol_name=var_name,
266
+ cwe_id="CWE-798",
267
+ redacted_snippet=f"{var_name} = \"[REDACTED]\"",
268
+ explanation=(
269
+ f"Potential hardcoded credential assigned to '{var_name}'. "
270
+ "Value has been redacted; verify whether this is a real secret or non-sensitive test literal."
271
+ ),
272
+ )
273
+ )
274
+
275
+ for ch in reversed(node.children):
276
+ stack.append((ch, depth + 1))
277
+
278
+ return signals
@@ -0,0 +1,271 @@
1
+ """Multi-ecosystem Static Test-to-Source Relationship Mapper.
2
+
3
+ Honesty Invariant:
4
+ - Maps static AST imports, symbol references, and naming conventions between test files
5
+ and production code across pytest, unittest, Jest, Vitest, Go testing, Rust #[test],
6
+ JUnit, xUnit, NUnit, and MSTest.
7
+ - NEVER produces fake runtime code coverage percentages.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import defaultdict
13
+ from pathlib import PurePosixPath
14
+
15
+ from repodna.brain.models import SymbolDefinition, SymbolReference
16
+ from repodna.parsers.capabilities import CapabilityLevel, get_language_capability
17
+ from repodna.quality.models import (
18
+ QualityConfidence,
19
+ TestMappingEntry,
20
+ TestMappingSummary,
21
+ TestRelationshipKind,
22
+ )
23
+ from repodna.schemas.models import AnalysisResult, FileNode
24
+
25
+ _TEST_ANNOTATIONS = {
26
+ "Test": "JUnit/NUnit",
27
+ "ParameterizedTest": "JUnit",
28
+ "Fact": "xUnit",
29
+ "Theory": "xUnit",
30
+ "TestMethod": "MSTest",
31
+ "TestClass": "MSTest",
32
+ "TestFixture": "NUnit",
33
+ "test": "Rust #[test]",
34
+ }
35
+
36
+
37
+ def detect_test_file_and_ecosystem(
38
+ file_node: FileNode,
39
+ file_symbols: list[SymbolDefinition],
40
+ content_preview: str = "",
41
+ ) -> tuple[bool, list[str]]:
42
+ """Classify whether `file_node` is a test source file and identify detected test ecosystems."""
43
+ rel = file_node.id.replace("\\", "/")
44
+ lower = rel.lower()
45
+ name = PurePosixPath(rel).name.lower()
46
+ stem = PurePosixPath(rel).stem.lower()
47
+ lang = file_node.language
48
+ ecosystems: set[str] = set()
49
+ is_test = False
50
+
51
+ if "/tests/" in f"/{lower}" or "/__tests__/" in f"/{lower}" or "/test/" in f"/{lower}" or "/spec/" in f"/{lower}":
52
+ is_test = True
53
+
54
+ if lang == "Python":
55
+ if name.startswith("test_") or name.endswith("_test.py"):
56
+ is_test = True
57
+ if "pytest" in content_preview:
58
+ ecosystems.add("pytest")
59
+ is_test = True
60
+ if "unittest" in content_preview:
61
+ ecosystems.add("unittest")
62
+ is_test = True
63
+ if is_test and not ecosystems:
64
+ ecosystems.add("pytest/unittest")
65
+ elif lang in ("TypeScript", "TypeScript (TSX)", "JavaScript", "JavaScript (JSX)"):
66
+ if ".test." in name or ".spec." in name:
67
+ is_test = True
68
+ if "vitest" in content_preview:
69
+ ecosystems.add("Vitest")
70
+ is_test = True
71
+ elif "jest" in content_preview or ("describe(" in content_preview and "expect(" in content_preview):
72
+ ecosystems.add("Jest/Vitest")
73
+ is_test = True
74
+ elif is_test:
75
+ ecosystems.add("Jest/Vitest")
76
+ elif lang == "Go":
77
+ if name.endswith("_test.go"):
78
+ is_test = True
79
+ ecosystems.add("Go testing")
80
+ elif lang == "Rust":
81
+ if "#[test]" in content_preview or "#[cfg(test)]" in content_preview or name.endswith("_test.rs"):
82
+ is_test = True
83
+ ecosystems.add("Rust #[test]")
84
+ elif lang == "Java":
85
+ if stem.endswith(("test", "tests", "it")) or "/src/test/" in f"/{lower}":
86
+ is_test = True
87
+ ecosystems.add("JUnit")
88
+ elif lang == "C#":
89
+ if stem.endswith(("test", "tests", "spec")) or ".tests/" in f"/{lower}":
90
+ is_test = True
91
+ if "using Xunit" in content_preview:
92
+ ecosystems.add("xUnit")
93
+ is_test = True
94
+ if "using NUnit" in content_preview:
95
+ ecosystems.add("NUnit")
96
+ is_test = True
97
+ if "Microsoft.VisualStudio.TestTools" in content_preview:
98
+ ecosystems.add("MSTest")
99
+ is_test = True
100
+ if is_test and not ecosystems:
101
+ ecosystems.add("xUnit/NUnit/MSTest")
102
+ elif lang in ("C", "C++"):
103
+ if stem.startswith("test_") or stem.endswith(("_test", "_tests")):
104
+ is_test = True
105
+ ecosystems.add("C/C++ test")
106
+
107
+ for sym in file_symbols:
108
+ for ann in sym.annotations:
109
+ short = ann.split(".")[-1]
110
+ if short in _TEST_ANNOTATIONS:
111
+ is_test = True
112
+ ecosystems.add(_TEST_ANNOTATIONS[short])
113
+
114
+ return is_test, sorted(ecosystems)
115
+
116
+
117
+ def _normalize_stem(file_path: str) -> str:
118
+ stem = PurePosixPath(file_path).stem.lower()
119
+ for pfx in ("test_", "tests_"):
120
+ if stem.startswith(pfx):
121
+ stem = stem[len(pfx) :]
122
+ for sfx in ("_test", "_tests", ".test", ".spec", "test", "tests", "spec"):
123
+ if stem.endswith(sfx) and len(stem) > len(sfx):
124
+ stem = stem[: -len(sfx)]
125
+ return stem.strip("._-")
126
+
127
+
128
+ def build_static_test_mapping(
129
+ *,
130
+ analysis: AnalysisResult,
131
+ symbols_by_file: dict[str, list[SymbolDefinition]],
132
+ references: list[SymbolReference],
133
+ content_by_file: dict[str, str],
134
+ ) -> TestMappingSummary:
135
+ """Build static test-to-source relationship mapping across all discovered files."""
136
+ test_files: dict[str, list[str]] = {}
137
+ prod_files: list[FileNode] = []
138
+ all_ecosystems: set[str] = set()
139
+
140
+ for fnode in analysis.files:
141
+ syms = symbols_by_file.get(fnode.id, [])
142
+ preview = content_by_file.get(fnode.id, "")[:4096]
143
+ is_t, ecos = detect_test_file_and_ecosystem(fnode, syms, preview)
144
+ if is_t:
145
+ test_files[fnode.id] = ecos
146
+ all_ecosystems.update(ecos)
147
+ else:
148
+ prod_files.append(fnode)
149
+
150
+ # Direct graph edges from test files -> production files
151
+ direct_tests_by_prod: dict[str, set[str]] = defaultdict(set)
152
+ direct_test_syms_by_prod: dict[str, set[str]] = defaultdict(set)
153
+ adjacency: dict[str, set[str]] = defaultdict(set)
154
+
155
+ for edge in analysis.edges:
156
+ adjacency[edge.source].add(edge.target)
157
+ if edge.source in test_files and edge.target not in test_files:
158
+ direct_tests_by_prod[edge.target].add(edge.source)
159
+
160
+ # Also incorporate AST symbol references originating from test files
161
+ for ref in references:
162
+ if ref.file_path in test_files and ref.target_file_path and ref.target_file_path not in test_files:
163
+ direct_tests_by_prod[ref.target_file_path].add(ref.file_path)
164
+ if ref.source_symbol_name:
165
+ direct_test_syms_by_prod[ref.target_file_path].add(ref.source_symbol_name)
166
+
167
+ # 2-hop indirect static reachability from test files
168
+ indirect_tests_by_prod: dict[str, set[str]] = defaultdict(set)
169
+ for tfile in test_files:
170
+ hop1 = adjacency.get(tfile, set())
171
+ for mid in hop1:
172
+ for hop2 in adjacency.get(mid, set()):
173
+ if hop2 not in test_files and tfile not in direct_tests_by_prod.get(hop2, set()):
174
+ indirect_tests_by_prod[hop2].add(tfile)
175
+
176
+ # Naming-convention index for test files
177
+ tests_by_norm_stem: dict[str, list[str]] = defaultdict(list)
178
+ for tfile in test_files:
179
+ ns = _normalize_stem(tfile)
180
+ if ns and len(ns) >= 3:
181
+ tests_by_norm_stem[ns].append(tfile)
182
+
183
+ entries: list[TestMappingEntry] = []
184
+ direct_cnt = indirect_cnt = naming_cnt = none_cnt = unknown_cnt = 0
185
+
186
+ for pf in prod_files:
187
+ cap = get_language_capability(pf.language)
188
+ if cap.test_mapping == CapabilityLevel.UNSUPPORTED:
189
+ unknown_cnt += 1
190
+ entries.append(
191
+ TestMappingEntry(
192
+ production_file=pf.id,
193
+ language=pf.language,
194
+ relationship_kind=TestRelationshipKind.UNKNOWN_UNSUPPORTED,
195
+ confidence=QualityConfidence.UNKNOWN,
196
+ explanation=f"Language '{pf.language}' is unsupported for static test mapping.",
197
+ )
198
+ )
199
+ continue
200
+
201
+ direct = sorted(direct_tests_by_prod.get(pf.id, set()))
202
+ indirect = sorted(indirect_tests_by_prod.get(pf.id, set()))
203
+ pstem = _normalize_stem(pf.id)
204
+ naming = sorted(tests_by_norm_stem.get(pstem, []))
205
+
206
+ if direct:
207
+ direct_cnt += 1
208
+ ecos = sorted({e for tf in direct for e in test_files.get(tf, [])})
209
+ entries.append(
210
+ TestMappingEntry(
211
+ production_file=pf.id,
212
+ language=pf.language,
213
+ relationship_kind=TestRelationshipKind.DIRECT_STATIC_REFERENCE,
214
+ mapped_test_files=direct[:15],
215
+ mapped_test_symbols=sorted(direct_test_syms_by_prod.get(pf.id, set()))[:15],
216
+ ecosystems_detected=ecos,
217
+ confidence=QualityConfidence.HIGH,
218
+ explanation=f"Directly imported or referenced by {len(direct)} test file(s).",
219
+ )
220
+ )
221
+ elif indirect:
222
+ indirect_cnt += 1
223
+ ecos = sorted({e for tf in indirect for e in test_files.get(tf, [])})
224
+ entries.append(
225
+ TestMappingEntry(
226
+ production_file=pf.id,
227
+ language=pf.language,
228
+ relationship_kind=TestRelationshipKind.INDIRECT_STATIC_REFERENCE,
229
+ mapped_test_files=indirect[:15],
230
+ ecosystems_detected=ecos,
231
+ confidence=QualityConfidence.MEDIUM,
232
+ explanation=f"Reached indirectly (2-hop import) from {len(indirect)} test file(s).",
233
+ )
234
+ )
235
+ elif naming:
236
+ naming_cnt += 1
237
+ ecos = sorted({e for tf in naming for e in test_files.get(tf, [])})
238
+ entries.append(
239
+ TestMappingEntry(
240
+ production_file=pf.id,
241
+ language=pf.language,
242
+ relationship_kind=TestRelationshipKind.NAMING_CANDIDATE,
243
+ mapped_test_files=naming[:10],
244
+ ecosystems_detected=ecos,
245
+ confidence=QualityConfidence.LOW,
246
+ explanation=f"Matched by file naming convention to {len(naming)} test file(s) (no direct AST import observed).",
247
+ )
248
+ )
249
+ else:
250
+ none_cnt += 1
251
+ entries.append(
252
+ TestMappingEntry(
253
+ production_file=pf.id,
254
+ language=pf.language,
255
+ relationship_kind=TestRelationshipKind.NO_OBSERVED_RELATIONSHIP,
256
+ confidence=QualityConfidence.MEDIUM,
257
+ explanation="No static import, symbol reference, or naming relationship observed from discovered test files.",
258
+ )
259
+ )
260
+
261
+ return TestMappingSummary(
262
+ total_test_files=len(test_files),
263
+ total_production_files=len(prod_files),
264
+ direct_mapped_count=direct_cnt,
265
+ indirect_mapped_count=indirect_cnt,
266
+ naming_candidate_count=naming_cnt,
267
+ no_observed_relationship_count=none_cnt,
268
+ unknown_unsupported_count=unknown_cnt,
269
+ ecosystems_detected=sorted(all_ecosystems),
270
+ entries=entries,
271
+ )