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.
- repodna/__init__.py +3 -0
- repodna/__main__.py +10 -0
- repodna/advisor/__init__.py +17 -0
- repodna/advisor/engine.py +502 -0
- repodna/advisor/models.py +101 -0
- repodna/agent/__init__.py +87 -0
- repodna/agent/context.py +558 -0
- repodna/agent/deltas.py +198 -0
- repodna/agent/evidence.py +134 -0
- repodna/agent/expansion.py +447 -0
- repodna/agent/localization.py +518 -0
- repodna/agent/models.py +695 -0
- repodna/agent/patch.py +378 -0
- repodna/agent/postflight.py +278 -0
- repodna/agent/preflight.py +336 -0
- repodna/agent/ranking.py +318 -0
- repodna/agent/repo_map.py +392 -0
- repodna/agent/safety.py +111 -0
- repodna/agent/service.py +574 -0
- repodna/agent/sessions.py +264 -0
- repodna/agent/task.py +660 -0
- repodna/agent/telemetry.py +101 -0
- repodna/agent/token_budget.py +231 -0
- repodna/api/__init__.py +1 -0
- repodna/api/agent_routes.py +248 -0
- repodna/api/app.py +2904 -0
- repodna/benchmarks/__init__.py +29 -0
- repodna/benchmarks/baselines.py +126 -0
- repodna/benchmarks/budget_bench.py +162 -0
- repodna/benchmarks/engine.py +418 -0
- repodna/benchmarks/evaluator.py +310 -0
- repodna/benchmarks/metrics.py +206 -0
- repodna/benchmarks/models.py +194 -0
- repodna/benchmarks/scalability.py +166 -0
- repodna/brain/__init__.py +46 -0
- repodna/brain/evidence.py +276 -0
- repodna/brain/extractor.py +1207 -0
- repodna/brain/indexer.py +766 -0
- repodna/brain/models.py +275 -0
- repodna/brain/multilang_extractors.py +889 -0
- repodna/brain/retrieval.py +469 -0
- repodna/brain/tracer.py +203 -0
- repodna/cli/__init__.py +1 -0
- repodna/cli/__main__.py +10 -0
- repodna/cli/agent_cmd.py +228 -0
- repodna/cli/installer.py +590 -0
- repodna/cli/main.py +2173 -0
- repodna/cli/plugin_cmd.py +130 -0
- repodna/cli/workspace_cmd.py +211 -0
- repodna/context/__init__.py +9 -0
- repodna/context/builder.py +379 -0
- repodna/context/models.py +133 -0
- repodna/contract/__init__.py +39 -0
- repodna/contract/evaluator.py +318 -0
- repodna/contract/loader.py +260 -0
- repodna/contract/models.py +185 -0
- repodna/core/__init__.py +1 -0
- repodna/core/analyzer.py +1424 -0
- repodna/diff/__init__.py +35 -0
- repodna/diff/engine.py +332 -0
- repodna/diff/models.py +117 -0
- repodna/diff/snapshot.py +248 -0
- repodna/ecosystem/__init__.py +27 -0
- repodna/ecosystem/contracts.py +129 -0
- repodna/ecosystem/doctor.py +253 -0
- repodna/git_insights/__init__.py +1 -0
- repodna/git_insights/analyzer.py +273 -0
- repodna/graph/__init__.py +1 -0
- repodna/graph/engine.py +562 -0
- repodna/guardian/__init__.py +17 -0
- repodna/guardian/engine.py +369 -0
- repodna/guardian/models.py +104 -0
- repodna/history/__init__.py +40 -0
- repodna/history/cache.py +240 -0
- repodna/history/diff.py +394 -0
- repodna/history/engine.py +557 -0
- repodna/history/evidence.py +160 -0
- repodna/history/models.py +258 -0
- repodna/history/timeline.py +164 -0
- repodna/intelligence/__init__.py +33 -0
- repodna/intelligence/models.py +165 -0
- repodna/intelligence/service.py +570 -0
- repodna/live/__init__.py +94 -0
- repodna/live/alerts.py +443 -0
- repodna/live/coordinator.py +351 -0
- repodna/live/diff.py +444 -0
- repodna/live/events.py +471 -0
- repodna/live/filtering.py +329 -0
- repodna/live/history.py +637 -0
- repodna/live/models.py +505 -0
- repodna/live/observer.py +653 -0
- repodna/live/reconciliation.py +253 -0
- repodna/live/session.py +1547 -0
- repodna/mcp/__init__.py +5 -0
- repodna/mcp/__main__.py +6 -0
- repodna/mcp/agent_tools.py +258 -0
- repodna/mcp/server.py +3283 -0
- repodna/mcp/workspace_tools.py +200 -0
- repodna/parsers/__init__.py +13 -0
- repodna/parsers/base.py +126 -0
- repodna/parsers/capabilities.py +361 -0
- repodna/parsers/project_metadata.py +232 -0
- repodna/parsers/resolver.py +621 -0
- repodna/parsers/treesitter_parser.py +830 -0
- repodna/passport/__init__.py +64 -0
- repodna/passport/generator.py +546 -0
- repodna/passport/migrator.py +139 -0
- repodna/passport/models.py +224 -0
- repodna/passport/validator.py +143 -0
- repodna/performance/__init__.py +89 -0
- repodna/performance/cache.py +1584 -0
- repodna/performance/identity.py +341 -0
- repodna/performance/incremental.py +317 -0
- repodna/performance/models.py +157 -0
- repodna/performance/parallel.py +291 -0
- repodna/plugins/__init__.py +47 -0
- repodna/plugins/evaluator.py +334 -0
- repodna/plugins/models.py +113 -0
- repodna/plugins/validator.py +256 -0
- repodna/quality/__init__.py +91 -0
- repodna/quality/complexity.py +352 -0
- repodna/quality/config.py +159 -0
- repodna/quality/debt.py +73 -0
- repodna/quality/duplicates.py +330 -0
- repodna/quality/engine.py +282 -0
- repodna/quality/impact.py +198 -0
- repodna/quality/models.py +427 -0
- repodna/quality/rules.py +364 -0
- repodna/quality/sarif.py +107 -0
- repodna/quality/security_signals.py +278 -0
- repodna/quality/test_mapping.py +271 -0
- repodna/quality/unused.py +201 -0
- repodna/reports/__init__.py +1 -0
- repodna/reports/exporter.py +374 -0
- repodna/rules/__init__.py +1 -0
- repodna/rules/health.py +436 -0
- repodna/schemas/__init__.py +1 -0
- repodna/schemas/models.py +348 -0
- repodna/security/__init__.py +1 -0
- repodna/security/safe_yaml.py +81 -0
- repodna/security/validators.py +583 -0
- repodna/skills/__init__.py +0 -0
- repodna/skills/repodna/SKILL.md +59 -0
- repodna/skills/repodna/__init__.py +0 -0
- repodna/skills/repodna/examples/workflows.md +85 -0
- repodna/skills/repodna/references/architecture-rules.md +26 -0
- repodna/storage/__init__.py +1 -0
- repodna/storage/workspace.py +199 -0
- repodna/webui/__init__.py +1 -0
- repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
- repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
- repodna/webui/assets/index-ByZ5e5pe.js +506 -0
- repodna/webui/assets/index-CDj3e8hw.css +1 -0
- repodna/webui/index.html +21 -0
- repodna/workspace/__init__.py +131 -0
- repodna/workspace/compatibility.py +317 -0
- repodna/workspace/context.py +175 -0
- repodna/workspace/contracts.py +369 -0
- repodna/workspace/federation.py +411 -0
- repodna/workspace/identity.py +202 -0
- repodna/workspace/impact.py +111 -0
- repodna/workspace/manifest.py +266 -0
- repodna/workspace/models.py +461 -0
- repodna/workspace/packages.py +494 -0
- repodna/workspace/policies.py +142 -0
- repodna/workspace/services.py +238 -0
- repodna/workspace/topology.py +316 -0
- repodna_engine-1.0.1.dist-info/METADATA +129 -0
- repodna_engine-1.0.1.dist-info/RECORD +173 -0
- repodna_engine-1.0.1.dist-info/WHEEL +5 -0
- repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
- repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
- repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
repodna/diff/snapshot.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Git revision snapshot manager for immutable architecture diffing with security hardening."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import tarfile
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from repodna.core.analyzer import run_repository_analysis
|
|
13
|
+
from repodna.schemas.models import AnalysisResult, ScanLimits, ScanRequest, SourceType
|
|
14
|
+
from repodna.security.validators import SecurityValidationError, is_safe_subpath
|
|
15
|
+
|
|
16
|
+
# Strict ref pattern preventing flag injection or malformed shell arguments
|
|
17
|
+
SAFE_GIT_REF_PATTERN = re.compile(r"^[a-zA-Z0-9_\-.~^/]+$")
|
|
18
|
+
WINDOWS_RESERVED_NAMES = {
|
|
19
|
+
"CON", "PRN", "AUX", "NUL",
|
|
20
|
+
*(f"COM{i}" for i in range(1, 10)),
|
|
21
|
+
*(f"LPT{i}" for i in range(1, 10)),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SnapshotManager:
|
|
26
|
+
"""Manages immutable analysis snapshots extracted from Git revisions."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, repo_path: Path | str) -> None:
|
|
29
|
+
self.repo_path = Path(repo_path).resolve()
|
|
30
|
+
if not (self.repo_path / ".git").exists():
|
|
31
|
+
raise ValueError(f"Directory '{self.repo_path}' is not a valid Git repository.")
|
|
32
|
+
|
|
33
|
+
def resolve_commit_metadata(self, git_ref: str) -> tuple[str, str, str]:
|
|
34
|
+
"""Returns (commit_sha, author, date_iso) for a git ref, ensuring commit exists."""
|
|
35
|
+
if git_ref in ("working_tree", "worktree", "current"):
|
|
36
|
+
git_ref = "HEAD"
|
|
37
|
+
|
|
38
|
+
if not SAFE_GIT_REF_PATTERN.match(git_ref) or git_ref.startswith("-"):
|
|
39
|
+
raise SecurityValidationError("INVALID_GIT_REF", f"Invalid git reference syntax: '{git_ref}'")
|
|
40
|
+
|
|
41
|
+
# Verify revision actually points to a valid commit object
|
|
42
|
+
verify_cmd = ["git", "-C", str(self.repo_path), "rev-parse", "--verify", "--quiet", f"{git_ref}^{{commit}}"]
|
|
43
|
+
try:
|
|
44
|
+
verified_sha = subprocess.check_output(verify_cmd, stderr=subprocess.PIPE, text=True, timeout=5.0).strip()
|
|
45
|
+
if not verified_sha:
|
|
46
|
+
raise SecurityValidationError("UNKNOWN_GIT_REF", f"Git commit revision '{git_ref}' does not exist.")
|
|
47
|
+
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
|
|
48
|
+
raise SecurityValidationError("UNKNOWN_GIT_REF", f"Git commit revision '{git_ref}' does not exist.") from exc
|
|
49
|
+
|
|
50
|
+
cmd = ["git", "-C", str(self.repo_path), "log", "-1", "--format=%H|%an|%cI", verified_sha, "--"]
|
|
51
|
+
try:
|
|
52
|
+
out = subprocess.check_output(cmd, stderr=subprocess.PIPE, text=True, timeout=10.0).strip()
|
|
53
|
+
parts = out.split("|", 2)
|
|
54
|
+
if len(parts) == 3:
|
|
55
|
+
return parts[0], parts[1], parts[2]
|
|
56
|
+
return verified_sha, "unknown", ""
|
|
57
|
+
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
|
|
58
|
+
raise ValueError(f"Failed to resolve git metadata for '{git_ref}': {exc}") from exc
|
|
59
|
+
|
|
60
|
+
def find_git_renames(self, base_ref: str, head_ref: str) -> dict[str, str]:
|
|
61
|
+
"""Finds verified renames tracked by Git between base and head revisions."""
|
|
62
|
+
try:
|
|
63
|
+
base_sha, _, _ = self.resolve_commit_metadata(base_ref)
|
|
64
|
+
head_sha, _, _ = self.resolve_commit_metadata(head_ref)
|
|
65
|
+
cmd = ["git", "-C", str(self.repo_path), "diff", "-M", "--name-status", base_sha, head_sha]
|
|
66
|
+
out = subprocess.check_output(cmd, stderr=subprocess.PIPE, text=True, timeout=15.0)
|
|
67
|
+
renames: dict[str, str] = {}
|
|
68
|
+
for line in out.splitlines():
|
|
69
|
+
parts = line.strip().split("\t")
|
|
70
|
+
if len(parts) >= 3 and parts[0].startswith("R"):
|
|
71
|
+
# R100\told_path\tnew_path
|
|
72
|
+
renames[parts[1]] = parts[2]
|
|
73
|
+
return renames
|
|
74
|
+
except Exception:
|
|
75
|
+
return {}
|
|
76
|
+
|
|
77
|
+
def create_snapshot(
|
|
78
|
+
self,
|
|
79
|
+
git_ref: str,
|
|
80
|
+
limits: ScanLimits | None = None,
|
|
81
|
+
) -> tuple[AnalysisResult, str | None, bool]:
|
|
82
|
+
"""
|
|
83
|
+
Creates an immutable AnalysisResult snapshot of a repository at a specific git ref.
|
|
84
|
+
Extracts repository tree into a sandboxed tempdir with strict memory and security bounds.
|
|
85
|
+
Returns: (analysis_result, commit_sha_or_none, is_working_tree)
|
|
86
|
+
"""
|
|
87
|
+
scan_limits = limits or ScanLimits()
|
|
88
|
+
|
|
89
|
+
if git_ref in ("working_tree", "worktree", "current"):
|
|
90
|
+
# Analyze active working tree
|
|
91
|
+
sha, _, _ = self.resolve_commit_metadata("HEAD")
|
|
92
|
+
req = ScanRequest(
|
|
93
|
+
source_type=SourceType.LOCAL,
|
|
94
|
+
target=str(self.repo_path),
|
|
95
|
+
limits=scan_limits,
|
|
96
|
+
)
|
|
97
|
+
analysis = run_repository_analysis(req)
|
|
98
|
+
return analysis, sha, True
|
|
99
|
+
|
|
100
|
+
# Extract git revision via git archive with bounded streaming into disk spool
|
|
101
|
+
sha, _, _ = self.resolve_commit_metadata(git_ref)
|
|
102
|
+
|
|
103
|
+
with tempfile.TemporaryDirectory(prefix="repodna_snap_") as tmp_dir:
|
|
104
|
+
tmp_path = Path(tmp_dir).resolve()
|
|
105
|
+
archive_cmd = ["git", "-C", str(self.repo_path), "archive", "--format=tar", sha]
|
|
106
|
+
spool_file = tempfile.NamedTemporaryFile(prefix="repodna_tar_", suffix=".tar", delete=False)
|
|
107
|
+
spool_path = Path(spool_file.name)
|
|
108
|
+
try:
|
|
109
|
+
proc = subprocess.Popen(
|
|
110
|
+
archive_cmd,
|
|
111
|
+
stdout=subprocess.PIPE,
|
|
112
|
+
stderr=subprocess.PIPE,
|
|
113
|
+
)
|
|
114
|
+
assert proc.stdout is not None
|
|
115
|
+
total_stream_bytes = 0
|
|
116
|
+
chunk_size = 64 * 1024
|
|
117
|
+
while True:
|
|
118
|
+
chunk = proc.stdout.read(chunk_size)
|
|
119
|
+
if not chunk:
|
|
120
|
+
break
|
|
121
|
+
total_stream_bytes += len(chunk)
|
|
122
|
+
if total_stream_bytes > scan_limits.max_total_size_bytes:
|
|
123
|
+
proc.kill()
|
|
124
|
+
proc.wait()
|
|
125
|
+
raise SecurityValidationError(
|
|
126
|
+
"MAX_SIZE_EXCEEDED",
|
|
127
|
+
f"Archive stream size ({total_stream_bytes} bytes) exceeds limit of {scan_limits.max_total_size_bytes} bytes.",
|
|
128
|
+
)
|
|
129
|
+
spool_file.write(chunk)
|
|
130
|
+
|
|
131
|
+
spool_file.flush()
|
|
132
|
+
spool_file.close()
|
|
133
|
+
|
|
134
|
+
_, stderr_data = proc.communicate(timeout=10.0)
|
|
135
|
+
if proc.returncode != 0:
|
|
136
|
+
raise RuntimeError(f"git archive failed (code {proc.returncode}): {stderr_data.decode('utf-8', errors='replace')}")
|
|
137
|
+
|
|
138
|
+
# Strict security inspection of tar members before extraction
|
|
139
|
+
total_bytes = 0
|
|
140
|
+
total_files = 0
|
|
141
|
+
symlink_targets: dict[Path, str] = {}
|
|
142
|
+
|
|
143
|
+
with tarfile.open(spool_path, mode="r:*") as tar:
|
|
144
|
+
for member in tar.getmembers():
|
|
145
|
+
# 1. Member type check: disallow devices, FIFOs, hardlinks
|
|
146
|
+
if not (member.isreg() or member.isdir() or member.issym()):
|
|
147
|
+
raise SecurityValidationError(
|
|
148
|
+
"UNSAFE_TAR_MEMBER_TYPE",
|
|
149
|
+
f"Archive member '{member.name}' has prohibited type.",
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
# 2. Path normalization & traversal checks
|
|
153
|
+
norm_name = os.path.normpath(member.name).replace("\\", "/")
|
|
154
|
+
if (
|
|
155
|
+
norm_name.startswith(("/", "\\"))
|
|
156
|
+
or (len(norm_name) > 1 and norm_name[1] == ":")
|
|
157
|
+
or norm_name.startswith("../")
|
|
158
|
+
or "/../" in norm_name
|
|
159
|
+
):
|
|
160
|
+
raise SecurityValidationError(
|
|
161
|
+
"PATH_TRAVERSAL_IN_ARCHIVE",
|
|
162
|
+
f"Archive member '{member.name}' attempts path traversal.",
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# 3. Windows reserved names check
|
|
166
|
+
for part in Path(norm_name).parts:
|
|
167
|
+
stem = part.split(".")[0].upper()
|
|
168
|
+
if stem in WINDOWS_RESERVED_NAMES:
|
|
169
|
+
raise SecurityValidationError(
|
|
170
|
+
"UNSAFE_ARCHIVE_FILENAME",
|
|
171
|
+
f"Archive member '{member.name}' contains prohibited Windows reserved name '{stem}'.",
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
member_dest = (tmp_path / norm_name).resolve()
|
|
175
|
+
if not is_safe_subpath(tmp_path, member_dest):
|
|
176
|
+
raise SecurityValidationError(
|
|
177
|
+
"PATH_TRAVERSAL_IN_ARCHIVE",
|
|
178
|
+
f"Archive member '{member.name}' resolves outside destination root.",
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# 4. Symlink security
|
|
182
|
+
if member.issym():
|
|
183
|
+
linkname = member.linkname
|
|
184
|
+
if (
|
|
185
|
+
os.path.isabs(linkname)
|
|
186
|
+
or (len(linkname) > 1 and linkname[1] == ":")
|
|
187
|
+
or linkname.startswith(("/", "\\"))
|
|
188
|
+
):
|
|
189
|
+
raise SecurityValidationError(
|
|
190
|
+
"SYMLINK_ESCAPE_IN_ARCHIVE",
|
|
191
|
+
f"Archive symlink '{member.name}' -> '{linkname}' has absolute or UNC target.",
|
|
192
|
+
)
|
|
193
|
+
link_dest = (member_dest.parent / linkname).resolve()
|
|
194
|
+
if not is_safe_subpath(tmp_path, link_dest):
|
|
195
|
+
raise SecurityValidationError(
|
|
196
|
+
"SYMLINK_ESCAPE_IN_ARCHIVE",
|
|
197
|
+
f"Archive symlink '{member.name}' -> '{linkname}' escapes root.",
|
|
198
|
+
)
|
|
199
|
+
symlink_targets[member_dest] = linkname
|
|
200
|
+
|
|
201
|
+
total_files += 1
|
|
202
|
+
total_bytes += member.size
|
|
203
|
+
|
|
204
|
+
if total_files > scan_limits.max_files:
|
|
205
|
+
raise SecurityValidationError(
|
|
206
|
+
"MAX_FILES_EXCEEDED",
|
|
207
|
+
f"Archive contains {total_files} files, exceeding limit {scan_limits.max_files}.",
|
|
208
|
+
)
|
|
209
|
+
if total_bytes > scan_limits.max_total_size_bytes:
|
|
210
|
+
raise SecurityValidationError(
|
|
211
|
+
"MAX_SIZE_EXCEEDED",
|
|
212
|
+
f"Archive uncompressed size exceeds limit of {scan_limits.max_total_size_bytes} bytes.",
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# 5. Nested symlink check
|
|
216
|
+
for sym_dest, orig_link in symlink_targets.items():
|
|
217
|
+
chain_dest = sym_dest.parent / orig_link
|
|
218
|
+
hops = 0
|
|
219
|
+
while chain_dest in symlink_targets and hops < 10:
|
|
220
|
+
chain_dest = chain_dest.parent / symlink_targets[chain_dest]
|
|
221
|
+
hops += 1
|
|
222
|
+
if hops >= 10 or not is_safe_subpath(tmp_path, chain_dest.resolve()):
|
|
223
|
+
raise SecurityValidationError(
|
|
224
|
+
"SYMLINK_ESCAPE_IN_ARCHIVE",
|
|
225
|
+
f"Archive symlink chain for '{sym_dest.name}' escapes root or forms excessive loop.",
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
tar.extractall(path=tmp_path, filter="data" if hasattr(tarfile, "data_filter") else None)
|
|
229
|
+
|
|
230
|
+
except SecurityValidationError:
|
|
231
|
+
raise
|
|
232
|
+
except Exception as exc:
|
|
233
|
+
raise RuntimeError(f"Failed to extract revision '{git_ref}' ({sha}): {exc}") from exc
|
|
234
|
+
finally:
|
|
235
|
+
if spool_path.exists():
|
|
236
|
+
try:
|
|
237
|
+
spool_path.unlink()
|
|
238
|
+
except OSError:
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
req = ScanRequest(
|
|
242
|
+
source_type=SourceType.LOCAL,
|
|
243
|
+
target=str(tmp_path),
|
|
244
|
+
limits=scan_limits,
|
|
245
|
+
)
|
|
246
|
+
analysis = run_repository_analysis(req)
|
|
247
|
+
analysis.target_display = f"{self.repo_path.name} @ {git_ref} ({sha[:8]})"
|
|
248
|
+
return analysis, sha, False
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Shared versioned contracts and ecosystem diagnostics for RepoDNA v0.12.0."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from repodna.ecosystem.contracts import (
|
|
6
|
+
ECOSYSTEM_PROTOCOL_VERSION,
|
|
7
|
+
MIN_SUPPORTED_PROTOCOL_VERSION,
|
|
8
|
+
CLIExitCode,
|
|
9
|
+
DoctorCheckItem,
|
|
10
|
+
EcosystemDoctorReport,
|
|
11
|
+
EcosystemHandshakeResponse,
|
|
12
|
+
build_ecosystem_handshake,
|
|
13
|
+
check_protocol_compatibility,
|
|
14
|
+
)
|
|
15
|
+
from repodna.ecosystem.doctor import run_ecosystem_doctor
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"CLIExitCode",
|
|
19
|
+
"DoctorCheckItem",
|
|
20
|
+
"ECOSYSTEM_PROTOCOL_VERSION",
|
|
21
|
+
"EcosystemDoctorReport",
|
|
22
|
+
"EcosystemHandshakeResponse",
|
|
23
|
+
"MIN_SUPPORTED_PROTOCOL_VERSION",
|
|
24
|
+
"build_ecosystem_handshake",
|
|
25
|
+
"check_protocol_compatibility",
|
|
26
|
+
"run_ecosystem_doctor",
|
|
27
|
+
]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Shared versioned API contracts and standardized CLI exit codes for RepoDNA Ecosystem.
|
|
2
|
+
|
|
3
|
+
Separates protocol compatibility (`ECOSYSTEM_PROTOCOL_VERSION`) from product release version
|
|
4
|
+
(`repodna.__version__`) so VS Code extensions, GitHub Actions, Docker deployments, and CLI
|
|
5
|
+
clients can negotiate capabilities safely and fail cleanly on incompatible versions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from enum import IntEnum
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
|
|
16
|
+
from repodna import __version__
|
|
17
|
+
|
|
18
|
+
ECOSYSTEM_PROTOCOL_VERSION = "1.0"
|
|
19
|
+
MIN_SUPPORTED_PROTOCOL_VERSION = "1.0"
|
|
20
|
+
PLUGIN_SCHEMA_VERSION = "1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CLIExitCode(IntEnum):
|
|
24
|
+
"""Standardized, documented CLI & CI exit codes."""
|
|
25
|
+
|
|
26
|
+
SUCCESS = 0
|
|
27
|
+
POLICY_VIOLATION = 1
|
|
28
|
+
INVALID_CONFIG = 2
|
|
29
|
+
INCOMPLETE_ANALYSIS = 3
|
|
30
|
+
INTERNAL_ERROR = 4
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class EcosystemHandshakeResponse(BaseModel):
|
|
34
|
+
"""Typed identity & capability handshake returned by /api/ecosystem/handshake.
|
|
35
|
+
|
|
36
|
+
Used by the VS Code extension and CI clients to verify that a local loopback port is
|
|
37
|
+
genuinely a compatible RepoDNA backend before transmitting any workspace path.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
service: str = "repodna-backend"
|
|
41
|
+
product_version: str = __version__
|
|
42
|
+
protocol_version: str = ECOSYSTEM_PROTOCOL_VERSION
|
|
43
|
+
min_protocol_version: str = MIN_SUPPORTED_PROTOCOL_VERSION
|
|
44
|
+
client_protocol_requested: str | None = None
|
|
45
|
+
compatible: bool = True
|
|
46
|
+
compatibility_message: str = "Compatible"
|
|
47
|
+
read_only: bool = True
|
|
48
|
+
local_first: bool = True
|
|
49
|
+
zero_execution: bool = True
|
|
50
|
+
mcp_tool_count: int = 47
|
|
51
|
+
plugin_schema_version: str = PLUGIN_SCHEMA_VERSION
|
|
52
|
+
capabilities: dict[str, Any] = Field(default_factory=dict)
|
|
53
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DoctorCheckItem(BaseModel):
|
|
57
|
+
"""Single non-mutating diagnostic check in EcosystemDoctorReport."""
|
|
58
|
+
|
|
59
|
+
name: str
|
|
60
|
+
status: str # ok | warning | unavailable | error
|
|
61
|
+
detail: str
|
|
62
|
+
remediation: str | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class EcosystemDoctorReport(BaseModel):
|
|
66
|
+
"""Comprehensive, read-only, secret-free environment diagnostics report."""
|
|
67
|
+
|
|
68
|
+
product_version: str = __version__
|
|
69
|
+
protocol_version: str = ECOSYSTEM_PROTOCOL_VERSION
|
|
70
|
+
python_version: str
|
|
71
|
+
platform: str
|
|
72
|
+
overall_status: str # healthy | degraded | unhealthy
|
|
73
|
+
checks: list[DoctorCheckItem] = Field(default_factory=list)
|
|
74
|
+
supported_languages: list[str] = Field(default_factory=list)
|
|
75
|
+
plugin_schema_version: str = PLUGIN_SCHEMA_VERSION
|
|
76
|
+
generated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_protocol_compatibility(client_protocol: str | None) -> tuple[bool, str]:
|
|
80
|
+
"""Validates major-version compatibility between client and backend protocol versions."""
|
|
81
|
+
if not client_protocol:
|
|
82
|
+
return True, f"Backend speaks ecosystem protocol v{ECOSYSTEM_PROTOCOL_VERSION}."
|
|
83
|
+
parts = client_protocol.strip().split(".")
|
|
84
|
+
if len(parts) < 1 or not parts[0].isdigit():
|
|
85
|
+
return False, f"Invalid client protocol version '{client_protocol}'; expected '<major>.<minor>'."
|
|
86
|
+
client_major = int(parts[0])
|
|
87
|
+
server_major = int(ECOSYSTEM_PROTOCOL_VERSION.split(".")[0])
|
|
88
|
+
if client_major != server_major:
|
|
89
|
+
return (
|
|
90
|
+
False,
|
|
91
|
+
f"Incompatible ecosystem protocol: client requested v{client_protocol}, "
|
|
92
|
+
f"backend supports v{ECOSYSTEM_PROTOCOL_VERSION} (min v{MIN_SUPPORTED_PROTOCOL_VERSION}). "
|
|
93
|
+
"Please update RepoDNA or the IDE extension to matching major protocol versions.",
|
|
94
|
+
)
|
|
95
|
+
return True, f"Compatible (client v{client_protocol}, backend v{ECOSYSTEM_PROTOCOL_VERSION})."
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def build_ecosystem_handshake(client_protocol: str | None = None) -> EcosystemHandshakeResponse:
|
|
99
|
+
"""Builds the canonical EcosystemHandshakeResponse."""
|
|
100
|
+
from repodna.parsers.capabilities import get_full_capability_matrix
|
|
101
|
+
|
|
102
|
+
compatible, msg = check_protocol_compatibility(client_protocol)
|
|
103
|
+
langs = sorted(
|
|
104
|
+
{
|
|
105
|
+
str(entry.get("language", ""))
|
|
106
|
+
for entry in get_full_capability_matrix()
|
|
107
|
+
if str(entry.get("support_level", "")).lower() == "full_ast"
|
|
108
|
+
and entry.get("language")
|
|
109
|
+
}
|
|
110
|
+
)
|
|
111
|
+
return EcosystemHandshakeResponse(
|
|
112
|
+
product_version=__version__,
|
|
113
|
+
protocol_version=ECOSYSTEM_PROTOCOL_VERSION,
|
|
114
|
+
min_protocol_version=MIN_SUPPORTED_PROTOCOL_VERSION,
|
|
115
|
+
client_protocol_requested=client_protocol,
|
|
116
|
+
compatible=compatible,
|
|
117
|
+
compatibility_message=msg,
|
|
118
|
+
capabilities={
|
|
119
|
+
"architecture_analysis": True,
|
|
120
|
+
"quality_intelligence": True,
|
|
121
|
+
"live_architecture": True,
|
|
122
|
+
"agent_intelligence": True,
|
|
123
|
+
"declarative_plugins": True,
|
|
124
|
+
"multi_repository_workspace": True,
|
|
125
|
+
"sarif_export": True,
|
|
126
|
+
"mcp_server": True,
|
|
127
|
+
"supported_ast_languages": langs,
|
|
128
|
+
},
|
|
129
|
+
)
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Read-only, secret-free Ecosystem Environment Doctor for RepoDNA v0.12.0."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import importlib.metadata
|
|
7
|
+
import platform
|
|
8
|
+
import shutil
|
|
9
|
+
import sqlite3
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from repodna.ecosystem.contracts import (
|
|
15
|
+
PLUGIN_SCHEMA_VERSION,
|
|
16
|
+
DoctorCheckItem,
|
|
17
|
+
EcosystemDoctorReport,
|
|
18
|
+
)
|
|
19
|
+
from repodna.parsers.capabilities import get_full_capability_matrix
|
|
20
|
+
from repodna.performance.identity import get_default_cache_dir
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run_ecosystem_doctor(
|
|
24
|
+
*,
|
|
25
|
+
check_docker: bool = False,
|
|
26
|
+
repo_root: Path | None = None,
|
|
27
|
+
) -> EcosystemDoctorReport:
|
|
28
|
+
"""Runs non-mutating environment checks across Python, grammars, cache, live, MCP, VS Code, and plugins.
|
|
29
|
+
|
|
30
|
+
Never modifies system configuration and never logs credentials or API tokens.
|
|
31
|
+
"""
|
|
32
|
+
checks: list[DoctorCheckItem] = []
|
|
33
|
+
|
|
34
|
+
# 1. Python version
|
|
35
|
+
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
|
36
|
+
py_ok = sys.version_info >= (3, 12)
|
|
37
|
+
checks.append(
|
|
38
|
+
DoctorCheckItem(
|
|
39
|
+
name="python_version",
|
|
40
|
+
status="ok" if py_ok else "error",
|
|
41
|
+
detail=f"Python {py_ver} ({sys.executable})",
|
|
42
|
+
remediation=None if py_ok else "Install Python 3.12 or newer.",
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# 2. Required dependencies
|
|
47
|
+
required_pkgs = ["fastapi", "uvicorn", "pydantic", "tree_sitter", "yaml", "pathspec", "watchfiles", "mcp"]
|
|
48
|
+
missing_req = []
|
|
49
|
+
for mod in required_pkgs:
|
|
50
|
+
try:
|
|
51
|
+
importlib.import_module(mod)
|
|
52
|
+
except Exception:
|
|
53
|
+
missing_req.append(mod)
|
|
54
|
+
checks.append(
|
|
55
|
+
DoctorCheckItem(
|
|
56
|
+
name="required_dependencies",
|
|
57
|
+
status="ok" if not missing_req else "error",
|
|
58
|
+
detail="All core dependencies importable." if not missing_req else f"Missing: {', '.join(missing_req)}",
|
|
59
|
+
remediation=(
|
|
60
|
+
None
|
|
61
|
+
if not missing_req
|
|
62
|
+
else "Reinstall RepoDNA from the official GitHub Release wheel or source checkout (pip install -e .). Do NOT run 'pip install repodna' from PyPI (name occupied by an unrelated project)."
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# 3. Optional dependencies (tiktoken)
|
|
68
|
+
try:
|
|
69
|
+
importlib.import_module("tiktoken")
|
|
70
|
+
tok_ver = importlib.metadata.version("tiktoken")
|
|
71
|
+
checks.append(
|
|
72
|
+
DoctorCheckItem(
|
|
73
|
+
name="optional_tokenizer",
|
|
74
|
+
status="ok",
|
|
75
|
+
detail=f"tiktoken {tok_ver} available for exact OpenAI BPE counts.",
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
except Exception:
|
|
79
|
+
checks.append(
|
|
80
|
+
DoctorCheckItem(
|
|
81
|
+
name="optional_tokenizer",
|
|
82
|
+
status="unavailable",
|
|
83
|
+
detail="tiktoken not installed; using deterministic heuristic_code_v1 (estimated mode).",
|
|
84
|
+
remediation="Optional: install exact OpenAI tokenizer with 'pip install tiktoken'",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# 4. Tree-sitter language grammars
|
|
89
|
+
matrix = get_full_capability_matrix()
|
|
90
|
+
supported_langs = sorted(
|
|
91
|
+
{
|
|
92
|
+
str(m.get("language", ""))
|
|
93
|
+
for m in matrix
|
|
94
|
+
if str(m.get("support_level", "")).lower() == "full_ast"
|
|
95
|
+
and m.get("language")
|
|
96
|
+
}
|
|
97
|
+
)
|
|
98
|
+
checks.append(
|
|
99
|
+
DoctorCheckItem(
|
|
100
|
+
name="language_grammars",
|
|
101
|
+
status="ok" if len(supported_langs) >= 9 else "warning",
|
|
102
|
+
detail=f"{len(supported_langs)} full-AST languages active: {', '.join(supported_langs)}",
|
|
103
|
+
remediation=None if len(supported_langs) >= 9 else "Verify tree-sitter language grammar packages are installed.",
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# 5. Cache directory & SQLite WAL readiness (non-mutating probe)
|
|
108
|
+
cache_dir = get_default_cache_dir()
|
|
109
|
+
try:
|
|
110
|
+
sqlite_ver = sqlite3.sqlite_version
|
|
111
|
+
checks.append(
|
|
112
|
+
DoctorCheckItem(
|
|
113
|
+
name="sqlite_and_cache",
|
|
114
|
+
status="ok",
|
|
115
|
+
detail=f"SQLite {sqlite_ver}; cache dir: {cache_dir}",
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
checks.append(
|
|
120
|
+
DoctorCheckItem(
|
|
121
|
+
name="sqlite_and_cache",
|
|
122
|
+
status="error",
|
|
123
|
+
detail=f"SQLite unavailable: {exc}",
|
|
124
|
+
remediation="Ensure Python stdlib sqlite3 is functional.",
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# 6. Live Architecture watcher capability
|
|
129
|
+
try:
|
|
130
|
+
import watchfiles
|
|
131
|
+
|
|
132
|
+
wf_ver = getattr(watchfiles, "__version__", "installed")
|
|
133
|
+
checks.append(
|
|
134
|
+
DoctorCheckItem(
|
|
135
|
+
name="live_watcher",
|
|
136
|
+
status="ok",
|
|
137
|
+
detail=f"Native watchfiles observer available ({wf_ver}).",
|
|
138
|
+
)
|
|
139
|
+
)
|
|
140
|
+
except Exception:
|
|
141
|
+
checks.append(
|
|
142
|
+
DoctorCheckItem(
|
|
143
|
+
name="live_watcher",
|
|
144
|
+
status="warning",
|
|
145
|
+
detail="watchfiles unavailable; polling fallback only.",
|
|
146
|
+
remediation="Install watchfiles>=1.0.0 for native filesystem watching.",
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# 7. MCP configuration presence (read-only check; never prints config contents/secrets)
|
|
151
|
+
root = (repo_root or Path.cwd()).resolve()
|
|
152
|
+
mcp_configs = [
|
|
153
|
+
p
|
|
154
|
+
for p in (
|
|
155
|
+
root / ".agents" / "mcp_config.json",
|
|
156
|
+
root / ".codex" / "config.toml",
|
|
157
|
+
root / ".vscode" / "mcp.json",
|
|
158
|
+
Path.home() / ".gemini" / "config" / "mcp_config.json",
|
|
159
|
+
)
|
|
160
|
+
if p.exists()
|
|
161
|
+
]
|
|
162
|
+
checks.append(
|
|
163
|
+
DoctorCheckItem(
|
|
164
|
+
name="mcp_configuration",
|
|
165
|
+
status="ok" if mcp_configs else "unavailable",
|
|
166
|
+
detail=(
|
|
167
|
+
f"Detected {len(mcp_configs)} agent MCP config file(s)."
|
|
168
|
+
if mcp_configs
|
|
169
|
+
else "No project/user MCP config detected yet."
|
|
170
|
+
),
|
|
171
|
+
remediation=None if mcp_configs else "Run: repodna setup --agent antigravity",
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# 8. VS Code CLI availability
|
|
176
|
+
code_bin = shutil.which("code") or shutil.which("code.cmd")
|
|
177
|
+
checks.append(
|
|
178
|
+
DoctorCheckItem(
|
|
179
|
+
name="vscode_cli",
|
|
180
|
+
status="ok" if code_bin else "unavailable",
|
|
181
|
+
detail=f"VS Code CLI found at {code_bin}" if code_bin else "VS Code CLI ('code') not found on PATH.",
|
|
182
|
+
remediation=None if code_bin else "Install VS Code and add 'code' to PATH to install the RepoDNA VSIX.",
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# 9. Plugin schema compatibility
|
|
187
|
+
checks.append(
|
|
188
|
+
DoctorCheckItem(
|
|
189
|
+
name="plugin_sdk",
|
|
190
|
+
status="ok",
|
|
191
|
+
detail=f"Declarative zero-execution Plugin SDK active (schema v{PLUGIN_SCHEMA_VERSION}).",
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# 10. Optional Docker availability (only when explicitly requested)
|
|
196
|
+
if check_docker:
|
|
197
|
+
docker_bin = shutil.which("docker")
|
|
198
|
+
if not docker_bin:
|
|
199
|
+
checks.append(
|
|
200
|
+
DoctorCheckItem(
|
|
201
|
+
name="docker",
|
|
202
|
+
status="unavailable",
|
|
203
|
+
detail="Docker CLI not found on PATH.",
|
|
204
|
+
remediation="Install Docker Engine / Docker Desktop to run containerized RepoDNA.",
|
|
205
|
+
)
|
|
206
|
+
)
|
|
207
|
+
else:
|
|
208
|
+
try:
|
|
209
|
+
res = subprocess.run(
|
|
210
|
+
[docker_bin, "info", "--format", "{{.ServerVersion}}"],
|
|
211
|
+
capture_output=True,
|
|
212
|
+
text=True,
|
|
213
|
+
timeout=4,
|
|
214
|
+
check=False,
|
|
215
|
+
)
|
|
216
|
+
if res.returncode == 0 and res.stdout.strip():
|
|
217
|
+
checks.append(
|
|
218
|
+
DoctorCheckItem(
|
|
219
|
+
name="docker",
|
|
220
|
+
status="ok",
|
|
221
|
+
detail=f"Docker daemon reachable (server {res.stdout.strip()}).",
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
else:
|
|
225
|
+
checks.append(
|
|
226
|
+
DoctorCheckItem(
|
|
227
|
+
name="docker",
|
|
228
|
+
status="unavailable",
|
|
229
|
+
detail="Docker CLI installed, but Docker daemon is not running.",
|
|
230
|
+
remediation="Start Docker daemon to build or run the RepoDNA container.",
|
|
231
|
+
)
|
|
232
|
+
)
|
|
233
|
+
except Exception as exc:
|
|
234
|
+
checks.append(
|
|
235
|
+
DoctorCheckItem(
|
|
236
|
+
name="docker",
|
|
237
|
+
status="unavailable",
|
|
238
|
+
detail=f"Docker check failed: {exc}",
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
has_error = any(c.status == "error" for c in checks)
|
|
243
|
+
has_warn = any(c.status == "warning" for c in checks)
|
|
244
|
+
overall = "unhealthy" if has_error else ("degraded" if has_warn else "healthy")
|
|
245
|
+
|
|
246
|
+
return EcosystemDoctorReport(
|
|
247
|
+
python_version=py_ver,
|
|
248
|
+
platform=f"{platform.system()} {platform.release()} ({platform.machine()})",
|
|
249
|
+
overall_status=overall,
|
|
250
|
+
checks=checks,
|
|
251
|
+
supported_languages=supported_langs,
|
|
252
|
+
plugin_schema_version=PLUGIN_SCHEMA_VERSION,
|
|
253
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Git insights package."""
|