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/agent/patch.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""Bounded Read-Only Unified Diff / Patch Intelligence for RepoDNA v0.11.0.
|
|
2
|
+
|
|
3
|
+
Security & safety guarantees:
|
|
4
|
+
- Treats all patch text as UNTRUSTED input.
|
|
5
|
+
- Rejects path traversal ('..') and absolute paths.
|
|
6
|
+
- Explicitly marks binary patches and unsupported formats as unsupported.
|
|
7
|
+
- Enforces strict limits on patch size, file count, hunk count, and line count.
|
|
8
|
+
- Never executes git apply, shell commands, or repository code.
|
|
9
|
+
- Never modifies any file on disk.
|
|
10
|
+
- Optional in-memory textual projection is strictly exact (fail-closed if context lines mismatch;
|
|
11
|
+
never applies fuzzy patches) and receives a distinct `hypothetical_snapshot_id`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from repodna.agent.models import (
|
|
20
|
+
MAX_PATCH_BYTES,
|
|
21
|
+
MAX_PATCH_FILES,
|
|
22
|
+
MAX_PATCH_HUNKS,
|
|
23
|
+
MAX_PATCH_LINES,
|
|
24
|
+
FreshnessMetadata,
|
|
25
|
+
HypotheticalRisk,
|
|
26
|
+
PatchFileChange,
|
|
27
|
+
PatchInspectionReport,
|
|
28
|
+
)
|
|
29
|
+
from repodna.agent.safety import build_trust_boundary, sanitize_untrusted_text, sha256_short
|
|
30
|
+
from repodna.schemas.models import AnalysisResult
|
|
31
|
+
from repodna.security.validators import SecurityValidationError, validate_and_resolve_evidence_path
|
|
32
|
+
|
|
33
|
+
_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
|
|
34
|
+
_DEF_RE = re.compile(
|
|
35
|
+
r"^\s*(?:async\s+)?(?:def|class|function|interface|struct|enum|type|fn|func|public|private|protected|internal)\s+([A-Za-z_][A-Za-z0-9_]*)"
|
|
36
|
+
)
|
|
37
|
+
_IMPORT_RE = re.compile(
|
|
38
|
+
r"^\s*(?:import\s+.+|from\s+\S+\s+import\s+.+|using\s+\S+;|#include\s+.+|use\s+\S+)"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _normalize_diff_path(raw: str) -> tuple[str | None, bool]:
|
|
43
|
+
"""Normalizes a diff header path (stripping a/ or b/). Returns (norm_path_or_none, is_safe)."""
|
|
44
|
+
cleaned = raw.strip().strip('"').split("\t", 1)[0].strip()
|
|
45
|
+
if cleaned in ("/dev/null", "dev/null", ""):
|
|
46
|
+
return None, True
|
|
47
|
+
if cleaned.startswith(("a/", "b/")):
|
|
48
|
+
cleaned = cleaned[2:]
|
|
49
|
+
cleaned = cleaned.replace("\\", "/")
|
|
50
|
+
if cleaned.startswith("/") or (len(cleaned) >= 2 and cleaned[1] == ":"):
|
|
51
|
+
return cleaned, False
|
|
52
|
+
parts = cleaned.split("/")
|
|
53
|
+
if any(p == ".." for p in parts):
|
|
54
|
+
return cleaned, False
|
|
55
|
+
return cleaned.lstrip("./"), True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _try_exact_in_memory_projection(
|
|
59
|
+
original_lines: list[str],
|
|
60
|
+
hunks: list[tuple[int, int, list[str]]],
|
|
61
|
+
) -> tuple[str | None, str | None]:
|
|
62
|
+
"""Fail-closed exact in-memory unified diff projection. Never applies fuzzy matching."""
|
|
63
|
+
result = list(original_lines)
|
|
64
|
+
offset = 0
|
|
65
|
+
for old_start, _old_count, hunk_lines in hunks:
|
|
66
|
+
idx = max(0, old_start - 1 + offset)
|
|
67
|
+
new_chunk: list[str] = []
|
|
68
|
+
cursor = idx
|
|
69
|
+
for hline in hunk_lines:
|
|
70
|
+
if not hline:
|
|
71
|
+
continue
|
|
72
|
+
prefix = hline[0]
|
|
73
|
+
body = hline[1:]
|
|
74
|
+
if prefix == " ":
|
|
75
|
+
if cursor >= len(result) or result[cursor] != body:
|
|
76
|
+
return None, f"Exact context mismatch at line {cursor + 1}; fail-closed (no fuzzy patching)."
|
|
77
|
+
new_chunk.append(body)
|
|
78
|
+
cursor += 1
|
|
79
|
+
elif prefix == "-":
|
|
80
|
+
if cursor >= len(result) or result[cursor] != body:
|
|
81
|
+
return None, f"Exact deletion mismatch at line {cursor + 1}; fail-closed (no fuzzy patching)."
|
|
82
|
+
cursor += 1
|
|
83
|
+
elif prefix == "+":
|
|
84
|
+
new_chunk.append(body)
|
|
85
|
+
elif prefix == "\\":
|
|
86
|
+
continue
|
|
87
|
+
result[idx:cursor] = new_chunk
|
|
88
|
+
offset += len(new_chunk) - (cursor - idx)
|
|
89
|
+
return "\n".join(result), None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def inspect_unified_diff(
|
|
93
|
+
patch_text: str,
|
|
94
|
+
analysis: AnalysisResult,
|
|
95
|
+
repo_id: str,
|
|
96
|
+
snapshot_id: str,
|
|
97
|
+
repo_root: Path | None = None,
|
|
98
|
+
revision: str = "WORKING_TREE",
|
|
99
|
+
) -> PatchInspectionReport:
|
|
100
|
+
"""Parses and analyzes a unified diff strictly read-only with bounded limits."""
|
|
101
|
+
raw_bytes = patch_text.encode("utf-8", errors="replace")
|
|
102
|
+
patch_byte_len = len(raw_bytes)
|
|
103
|
+
hyp_snapshot_id = f"hyp_{sha256_short(f'{snapshot_id}:{sha256_short(patch_text, 16)}', 14)}"
|
|
104
|
+
|
|
105
|
+
freshness = FreshnessMetadata(
|
|
106
|
+
repo_id=repo_id,
|
|
107
|
+
repository=analysis.repo_name,
|
|
108
|
+
snapshot_id=snapshot_id,
|
|
109
|
+
revision=revision,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
limitations: list[str] = [
|
|
113
|
+
"Patch inspection is strictly read-only and never modifies working-tree files or runs git apply."
|
|
114
|
+
]
|
|
115
|
+
if patch_byte_len > MAX_PATCH_BYTES:
|
|
116
|
+
limitations.append(
|
|
117
|
+
f"Patch rejected: size {patch_byte_len:,} bytes exceeds maximum limit of {MAX_PATCH_BYTES:,} bytes."
|
|
118
|
+
)
|
|
119
|
+
return PatchInspectionReport(
|
|
120
|
+
freshness=freshness,
|
|
121
|
+
hypothetical_snapshot_id=hyp_snapshot_id,
|
|
122
|
+
patch_bytes=patch_byte_len,
|
|
123
|
+
limitations=limitations,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
lines = patch_text.replace("\r\n", "\n").replace("\r", "\n").splitlines()
|
|
127
|
+
if len(lines) > MAX_PATCH_LINES:
|
|
128
|
+
limitations.append(
|
|
129
|
+
f"Patch rejected: {len(lines):,} lines exceeds maximum limit of {MAX_PATCH_LINES:,} lines."
|
|
130
|
+
)
|
|
131
|
+
return PatchInspectionReport(
|
|
132
|
+
freshness=freshness,
|
|
133
|
+
hypothetical_snapshot_id=hyp_snapshot_id,
|
|
134
|
+
patch_bytes=patch_byte_len,
|
|
135
|
+
limitations=limitations,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
_, redacted_count, injection_signals = sanitize_untrusted_text(patch_text)
|
|
139
|
+
|
|
140
|
+
files_by_id = {f.id: f for f in analysis.files}
|
|
141
|
+
file_changes: list[PatchFileChange] = []
|
|
142
|
+
unsupported_files: list[str] = []
|
|
143
|
+
rejected_paths: list[str] = []
|
|
144
|
+
|
|
145
|
+
total_hunks = 0
|
|
146
|
+
total_added = 0
|
|
147
|
+
total_deleted = 0
|
|
148
|
+
|
|
149
|
+
current_old: str | None = None
|
|
150
|
+
current_new: str | None = None
|
|
151
|
+
current_is_binary = False
|
|
152
|
+
current_added = 0
|
|
153
|
+
current_deleted = 0
|
|
154
|
+
current_hunks_list: list[tuple[int, int, list[str]]] = []
|
|
155
|
+
active_hunk: tuple[int, int, list[str]] | None = None
|
|
156
|
+
added_syms: list[str] = []
|
|
157
|
+
removed_syms: list[str] = []
|
|
158
|
+
added_imports: list[str] = []
|
|
159
|
+
removed_imports: list[str] = []
|
|
160
|
+
|
|
161
|
+
def _flush_current() -> None:
|
|
162
|
+
nonlocal current_old, current_new, current_is_binary, current_added, current_deleted
|
|
163
|
+
nonlocal current_hunks_list, active_hunk, added_syms, removed_syms, added_imports, removed_imports
|
|
164
|
+
if active_hunk is not None:
|
|
165
|
+
current_hunks_list.append(active_hunk)
|
|
166
|
+
active_hunk = None
|
|
167
|
+
if current_old is None and current_new is None:
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
target_path = current_new or current_old or ""
|
|
171
|
+
if current_is_binary:
|
|
172
|
+
unsupported_files.append(target_path)
|
|
173
|
+
file_changes.append(
|
|
174
|
+
PatchFileChange(
|
|
175
|
+
file_path=target_path,
|
|
176
|
+
old_path=current_old if current_old != target_path else None,
|
|
177
|
+
change_type="binary",
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
else:
|
|
181
|
+
if current_old is None and current_new is not None:
|
|
182
|
+
ctype = "added"
|
|
183
|
+
elif current_new is None and current_old is not None:
|
|
184
|
+
ctype = "deleted"
|
|
185
|
+
elif current_old and current_new and current_old != current_new:
|
|
186
|
+
ctype = "renamed"
|
|
187
|
+
else:
|
|
188
|
+
ctype = "modified"
|
|
189
|
+
|
|
190
|
+
# Potential signature changes: symbol appears in both removed and added lines
|
|
191
|
+
sig_changes = sorted(set(added_syms) & set(removed_syms))
|
|
192
|
+
|
|
193
|
+
# Optional exact in-memory projection (fail-closed)
|
|
194
|
+
proj_ok = False
|
|
195
|
+
proj_err: str | None = None
|
|
196
|
+
if repo_root is not None and ctype in ("modified", "renamed") and current_hunks_list:
|
|
197
|
+
try:
|
|
198
|
+
resolved, _ = validate_and_resolve_evidence_path(repo_root, target_path)
|
|
199
|
+
if resolved.exists():
|
|
200
|
+
orig_text = resolved.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
|
|
201
|
+
projected, proj_err = _try_exact_in_memory_projection(
|
|
202
|
+
orig_text.splitlines(), current_hunks_list
|
|
203
|
+
)
|
|
204
|
+
proj_ok = projected is not None
|
|
205
|
+
else:
|
|
206
|
+
proj_err = "Target file does not exist on disk for projection."
|
|
207
|
+
except SecurityValidationError as exc:
|
|
208
|
+
proj_err = exc.message
|
|
209
|
+
except OSError as exc:
|
|
210
|
+
proj_err = str(exc)
|
|
211
|
+
|
|
212
|
+
file_changes.append(
|
|
213
|
+
PatchFileChange(
|
|
214
|
+
file_path=target_path,
|
|
215
|
+
old_path=current_old if current_old != target_path else None,
|
|
216
|
+
change_type=ctype,
|
|
217
|
+
added_lines=current_added,
|
|
218
|
+
deleted_lines=current_deleted,
|
|
219
|
+
hunk_count=len(current_hunks_list),
|
|
220
|
+
added_symbols=sorted(set(added_syms))[:25],
|
|
221
|
+
removed_symbols=sorted(set(removed_syms))[:25],
|
|
222
|
+
potential_signature_changes=sig_changes[:20],
|
|
223
|
+
added_imports=sorted(set(added_imports))[:20],
|
|
224
|
+
removed_imports=sorted(set(removed_imports))[:20],
|
|
225
|
+
projection_applied=proj_ok,
|
|
226
|
+
projection_error=proj_err,
|
|
227
|
+
)
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
current_old = None
|
|
231
|
+
current_new = None
|
|
232
|
+
current_is_binary = False
|
|
233
|
+
current_added = 0
|
|
234
|
+
current_deleted = 0
|
|
235
|
+
current_hunks_list = []
|
|
236
|
+
added_syms = []
|
|
237
|
+
removed_syms = []
|
|
238
|
+
added_imports = []
|
|
239
|
+
removed_imports = []
|
|
240
|
+
|
|
241
|
+
skip_current_file = False
|
|
242
|
+
|
|
243
|
+
for line in lines:
|
|
244
|
+
if line.startswith("diff --git "):
|
|
245
|
+
_flush_current()
|
|
246
|
+
skip_current_file = False
|
|
247
|
+
if len(file_changes) >= MAX_PATCH_FILES:
|
|
248
|
+
limitations.append(f"Reached maximum file limit ({MAX_PATCH_FILES}); remaining diff truncated.")
|
|
249
|
+
break
|
|
250
|
+
continue
|
|
251
|
+
|
|
252
|
+
if line.startswith("Binary files ") or line.startswith("GIT binary patch"):
|
|
253
|
+
current_is_binary = True
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
if line.startswith("--- "):
|
|
257
|
+
if current_old is not None or current_new is not None:
|
|
258
|
+
_flush_current()
|
|
259
|
+
skip_current_file = False
|
|
260
|
+
raw_old = line[4:]
|
|
261
|
+
norm_old, safe_old = _normalize_diff_path(raw_old)
|
|
262
|
+
if not safe_old:
|
|
263
|
+
rejected_paths.append(raw_old.strip())
|
|
264
|
+
skip_current_file = True
|
|
265
|
+
continue
|
|
266
|
+
current_old = norm_old
|
|
267
|
+
continue
|
|
268
|
+
|
|
269
|
+
if line.startswith("+++ "):
|
|
270
|
+
if skip_current_file:
|
|
271
|
+
continue
|
|
272
|
+
raw_new = line[4:]
|
|
273
|
+
norm_new, safe_new = _normalize_diff_path(raw_new)
|
|
274
|
+
if not safe_new:
|
|
275
|
+
rejected_paths.append(raw_new.strip())
|
|
276
|
+
skip_current_file = True
|
|
277
|
+
current_old = None
|
|
278
|
+
continue
|
|
279
|
+
current_new = norm_new
|
|
280
|
+
continue
|
|
281
|
+
|
|
282
|
+
if skip_current_file or current_is_binary:
|
|
283
|
+
continue
|
|
284
|
+
|
|
285
|
+
hunk_match = _HUNK_HEADER_RE.match(line)
|
|
286
|
+
if hunk_match:
|
|
287
|
+
if active_hunk is not None:
|
|
288
|
+
current_hunks_list.append(active_hunk)
|
|
289
|
+
total_hunks += 1
|
|
290
|
+
if total_hunks > MAX_PATCH_HUNKS:
|
|
291
|
+
limitations.append(f"Reached maximum hunk limit ({MAX_PATCH_HUNKS}); remaining hunks skipped.")
|
|
292
|
+
active_hunk = None
|
|
293
|
+
break
|
|
294
|
+
old_start = int(hunk_match.group(1))
|
|
295
|
+
old_count = int(hunk_match.group(2) or "1")
|
|
296
|
+
active_hunk = (old_start, old_count, [])
|
|
297
|
+
continue
|
|
298
|
+
|
|
299
|
+
if active_hunk is not None and line[:1] in ("+", "-", " ", "\\"):
|
|
300
|
+
active_hunk[2].append(line)
|
|
301
|
+
if line.startswith("+") and not line.startswith("+++"):
|
|
302
|
+
current_added += 1
|
|
303
|
+
total_added += 1
|
|
304
|
+
body = line[1:]
|
|
305
|
+
dm = _DEF_RE.match(body)
|
|
306
|
+
if dm:
|
|
307
|
+
added_syms.append(dm.group(1))
|
|
308
|
+
if _IMPORT_RE.match(body):
|
|
309
|
+
safe_imp, _, _ = sanitize_untrusted_text(body.strip())
|
|
310
|
+
added_imports.append(safe_imp[:140])
|
|
311
|
+
elif line.startswith("-") and not line.startswith("---"):
|
|
312
|
+
current_deleted += 1
|
|
313
|
+
total_deleted += 1
|
|
314
|
+
body = line[1:]
|
|
315
|
+
dm = _DEF_RE.match(body)
|
|
316
|
+
if dm:
|
|
317
|
+
removed_syms.append(dm.group(1))
|
|
318
|
+
if _IMPORT_RE.match(body):
|
|
319
|
+
safe_imp, _, _ = sanitize_untrusted_text(body.strip())
|
|
320
|
+
removed_imports.append(safe_imp[:140])
|
|
321
|
+
|
|
322
|
+
_flush_current()
|
|
323
|
+
|
|
324
|
+
# Correlate changed files against existing architecture constraints and quality risks
|
|
325
|
+
touched_files = {fc.file_path for fc in file_changes}
|
|
326
|
+
arch_constraints: list[str] = []
|
|
327
|
+
quality_risks: list[str] = []
|
|
328
|
+
hypothetical_risks: list[HypotheticalRisk] = []
|
|
329
|
+
|
|
330
|
+
for af in analysis.health_report.findings:
|
|
331
|
+
overlap = sorted(set(af.affected_files) & touched_files)
|
|
332
|
+
if overlap:
|
|
333
|
+
arch_constraints.append(f"[{af.rule_id}] {af.title} (touches {', '.join(overlap[:3])})")
|
|
334
|
+
|
|
335
|
+
for fc in file_changes:
|
|
336
|
+
node = files_by_id.get(fc.file_path)
|
|
337
|
+
if node and node.is_hub and (fc.potential_signature_changes or fc.removed_symbols):
|
|
338
|
+
hypothetical_risks.append(
|
|
339
|
+
HypotheticalRisk(
|
|
340
|
+
risk_id=f"hyp_patch_hub_{sha256_short(fc.file_path, 8)}",
|
|
341
|
+
category="hub_signature_change",
|
|
342
|
+
severity="warning",
|
|
343
|
+
is_hypothetical=True,
|
|
344
|
+
description=(
|
|
345
|
+
f"Hypothetical breaking-change risk: patch modifies/removes symbols in hub '{fc.file_path}' "
|
|
346
|
+
f"(fan_in={node.fan_in})."
|
|
347
|
+
),
|
|
348
|
+
involved_modules=[fc.file_path],
|
|
349
|
+
)
|
|
350
|
+
)
|
|
351
|
+
if fc.added_imports:
|
|
352
|
+
quality_risks.append(
|
|
353
|
+
f"{fc.file_path}: adds {len(fc.added_imports)} import line(s); verify no new circular dependencies post-edit."
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
if rejected_paths:
|
|
357
|
+
limitations.append(
|
|
358
|
+
f"Rejected {len(rejected_paths)} unsafe path(s) (path traversal or absolute path)."
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
return PatchInspectionReport(
|
|
362
|
+
freshness=freshness,
|
|
363
|
+
hypothetical_snapshot_id=hyp_snapshot_id,
|
|
364
|
+
read_only_guarantee=True,
|
|
365
|
+
patch_bytes=patch_byte_len,
|
|
366
|
+
total_files=len(file_changes),
|
|
367
|
+
total_hunks=total_hunks,
|
|
368
|
+
total_added_lines=total_added,
|
|
369
|
+
total_deleted_lines=total_deleted,
|
|
370
|
+
file_changes=file_changes,
|
|
371
|
+
unsupported_files=sorted(set(unsupported_files)),
|
|
372
|
+
rejected_paths=sorted(set(rejected_paths)),
|
|
373
|
+
relevant_architectural_constraints=arch_constraints[:20],
|
|
374
|
+
relevant_quality_risks=quality_risks[:20],
|
|
375
|
+
hypothetical_risks=hypothetical_risks[:20],
|
|
376
|
+
limitations=limitations,
|
|
377
|
+
trust_boundary=build_trust_boundary(redacted_count, injection_signals),
|
|
378
|
+
)
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Snapshot-Backed Change Postflight Verification Engine for RepoDNA v0.11.0.
|
|
2
|
+
|
|
3
|
+
Compares a verified BEFORE snapshot against an AFTER snapshot after edits are made:
|
|
4
|
+
- Computes actual changed files, changed symbols, added/removed dependency edges,
|
|
5
|
+
new/resolved circular dependencies, architecture contract regressions, quality regressions,
|
|
6
|
+
resolved quality findings, test relationship changes, coverage delta, and intent-vs-actual scope.
|
|
7
|
+
- Returns INCONCLUSIVE honestly if the before snapshot is missing or unavailable.
|
|
8
|
+
- Verdict PASS strictly means static architectural/quality checks passed; it NEVER implies
|
|
9
|
+
repository unit tests passed or runtime behavior is proven correct.
|
|
10
|
+
- Never attributes file edits to a specific human or agent automatically.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from repodna.agent.models import (
|
|
18
|
+
ChangeIntent,
|
|
19
|
+
FreshnessMetadata,
|
|
20
|
+
PostflightVerdict,
|
|
21
|
+
VerificationResult,
|
|
22
|
+
)
|
|
23
|
+
from repodna.brain.indexer import SymbolIndexer
|
|
24
|
+
from repodna.intelligence.service import RepositoryIntelligenceService
|
|
25
|
+
from repodna.quality.models import QualityReport
|
|
26
|
+
from repodna.schemas.models import AnalysisResult
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _extract_edges(analysis: AnalysisResult) -> set[tuple[str, str]]:
|
|
30
|
+
edges: set[tuple[str, str]] = set()
|
|
31
|
+
for f in analysis.files:
|
|
32
|
+
for imp in f.imports_internal:
|
|
33
|
+
edges.add((f.id, imp))
|
|
34
|
+
return edges
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _extract_cycle_keys(analysis: AnalysisResult) -> dict[tuple[str, ...], list[str]]:
|
|
38
|
+
out: dict[tuple[str, ...], list[str]] = {}
|
|
39
|
+
for cyc in analysis.cycles:
|
|
40
|
+
key = tuple(sorted(cyc.nodes))
|
|
41
|
+
out[key] = sorted(cyc.nodes)
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _extract_symbol_signatures(indexer: SymbolIndexer | None) -> dict[tuple[str, str, str], str]:
|
|
46
|
+
if indexer is None:
|
|
47
|
+
return {}
|
|
48
|
+
out: dict[tuple[str, str, str], str] = {}
|
|
49
|
+
for fid, syms in indexer._symbols_by_file.items():
|
|
50
|
+
for s in syms:
|
|
51
|
+
out[(fid, s.name, s.kind.value)] = s.signature or f"{s.line_start}:{s.line_end}"
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ChangePostflightEngine:
|
|
56
|
+
"""Deterministic before/after snapshot postflight verifier."""
|
|
57
|
+
|
|
58
|
+
def verify(
|
|
59
|
+
self,
|
|
60
|
+
repo_id: str,
|
|
61
|
+
after_analysis: AnalysisResult,
|
|
62
|
+
after_snapshot_id: str,
|
|
63
|
+
before_analysis: AnalysisResult | None = None,
|
|
64
|
+
before_snapshot_id: str | None = None,
|
|
65
|
+
before_indexer: SymbolIndexer | None = None,
|
|
66
|
+
after_indexer: SymbolIndexer | None = None,
|
|
67
|
+
before_quality: QualityReport | None = None,
|
|
68
|
+
after_quality: QualityReport | None = None,
|
|
69
|
+
change_intent: ChangeIntent | None = None,
|
|
70
|
+
stale_evidence_ids: list[str] | None = None,
|
|
71
|
+
revision: str = "WORKING_TREE",
|
|
72
|
+
core_freshness: str = "fresh",
|
|
73
|
+
quality_freshness: str = "not_evaluated",
|
|
74
|
+
) -> VerificationResult:
|
|
75
|
+
"""Evaluates before vs after snapshots and produces a typed VerificationResult."""
|
|
76
|
+
freshness = FreshnessMetadata(
|
|
77
|
+
repo_id=repo_id,
|
|
78
|
+
repository=after_analysis.repo_name,
|
|
79
|
+
snapshot_id=after_snapshot_id,
|
|
80
|
+
revision=revision,
|
|
81
|
+
core_freshness=core_freshness,
|
|
82
|
+
quality_freshness=quality_freshness,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
limitations: list[str] = [
|
|
86
|
+
"RepoDNA postflight verification is static only; it does not execute repository tests or confirm runtime behavior.",
|
|
87
|
+
"File changes are observed from repository snapshots without attributing authorship to any person or agent.",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
if before_analysis is None or not before_snapshot_id:
|
|
91
|
+
limitations.append(
|
|
92
|
+
"Before-snapshot is missing or evicted; cannot compute verified before/after architectural delta."
|
|
93
|
+
)
|
|
94
|
+
return VerificationResult(
|
|
95
|
+
verdict=PostflightVerdict.INCONCLUSIVE,
|
|
96
|
+
repo_id=repo_id,
|
|
97
|
+
before_snapshot_id=before_snapshot_id,
|
|
98
|
+
after_snapshot_id=after_snapshot_id,
|
|
99
|
+
freshness=freshness,
|
|
100
|
+
stale_evidence_ids=sorted(set(stale_evidence_ids or [])),
|
|
101
|
+
limitations=limitations,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# 1. File-level changes (added, removed, or LOC/imports changed)
|
|
105
|
+
before_files = {f.id: f for f in before_analysis.files}
|
|
106
|
+
after_files = {f.id: f for f in after_analysis.files}
|
|
107
|
+
all_fids = sorted(set(before_files.keys()) | set(after_files.keys()))
|
|
108
|
+
actual_changed_files: list[str] = []
|
|
109
|
+
for fid in all_fids:
|
|
110
|
+
bf = before_files.get(fid)
|
|
111
|
+
af = after_files.get(fid)
|
|
112
|
+
if bf is None or af is None:
|
|
113
|
+
actual_changed_files.append(fid)
|
|
114
|
+
elif (
|
|
115
|
+
bf.lines_code != af.lines_code
|
|
116
|
+
or sorted(bf.imports_internal) != sorted(af.imports_internal)
|
|
117
|
+
or bf.fan_in != af.fan_in
|
|
118
|
+
or bf.fan_out != af.fan_out
|
|
119
|
+
):
|
|
120
|
+
actual_changed_files.append(fid)
|
|
121
|
+
|
|
122
|
+
# 2. Symbol-level changes
|
|
123
|
+
b_syms = _extract_symbol_signatures(before_indexer)
|
|
124
|
+
a_syms = _extract_symbol_signatures(after_indexer)
|
|
125
|
+
changed_symbols: list[str] = []
|
|
126
|
+
for key in sorted(set(b_syms.keys()) | set(a_syms.keys())):
|
|
127
|
+
if b_syms.get(key) != a_syms.get(key):
|
|
128
|
+
changed_symbols.append(f"{key[0]}::{key[1]} ({key[2]})")
|
|
129
|
+
if key[0] not in actual_changed_files:
|
|
130
|
+
actual_changed_files.append(key[0])
|
|
131
|
+
actual_changed_files = sorted(set(actual_changed_files))
|
|
132
|
+
|
|
133
|
+
# 3. Dependency edge delta
|
|
134
|
+
b_edges = _extract_edges(before_analysis)
|
|
135
|
+
a_edges = _extract_edges(after_analysis)
|
|
136
|
+
added_edges = sorted(a_edges - b_edges)
|
|
137
|
+
removed_edges = sorted(b_edges - a_edges)
|
|
138
|
+
|
|
139
|
+
# 4. Circular dependency delta
|
|
140
|
+
b_cycles = _extract_cycle_keys(before_analysis)
|
|
141
|
+
a_cycles = _extract_cycle_keys(after_analysis)
|
|
142
|
+
new_cycles = [a_cycles[k] for k in sorted(set(a_cycles.keys()) - set(b_cycles.keys()))]
|
|
143
|
+
resolved_cycles = [b_cycles[k] for k in sorted(set(b_cycles.keys()) - set(a_cycles.keys()))]
|
|
144
|
+
|
|
145
|
+
# 5. Architecture / contract finding regressions
|
|
146
|
+
b_finding_keys = {
|
|
147
|
+
(f.rule_id, tuple(sorted(f.affected_files))) for f in before_analysis.health_report.findings
|
|
148
|
+
}
|
|
149
|
+
contract_regressions: list[dict[str, Any]] = []
|
|
150
|
+
for arch_f in after_analysis.health_report.findings:
|
|
151
|
+
arch_key = (arch_f.rule_id, tuple(sorted(arch_f.affected_files)))
|
|
152
|
+
if arch_key not in b_finding_keys:
|
|
153
|
+
contract_regressions.append(
|
|
154
|
+
{
|
|
155
|
+
"rule_id": arch_f.rule_id,
|
|
156
|
+
"severity": arch_f.severity.value,
|
|
157
|
+
"title": arch_f.title,
|
|
158
|
+
"affected_files": arch_f.affected_files[:10],
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
# 6. Quality finding delta (with coverage-loss guard!)
|
|
163
|
+
b_cov = RepositoryIntelligenceService(before_analysis).get_analysis_coverage()
|
|
164
|
+
a_cov = RepositoryIntelligenceService(after_analysis).get_analysis_coverage()
|
|
165
|
+
coverage_delta: dict[str, Any] = {
|
|
166
|
+
"before_ast_loc_coverage_pct": b_cov.ast_loc_coverage_pct,
|
|
167
|
+
"after_ast_loc_coverage_pct": a_cov.ast_loc_coverage_pct,
|
|
168
|
+
"delta_ast_loc_coverage_pct": round(
|
|
169
|
+
a_cov.ast_loc_coverage_pct - b_cov.ast_loc_coverage_pct, 2
|
|
170
|
+
),
|
|
171
|
+
"coverage_dropped": a_cov.ast_loc_coverage_pct < b_cov.ast_loc_coverage_pct - 0.5,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
quality_regressions: list[dict[str, Any]] = []
|
|
175
|
+
resolved_quality: list[dict[str, Any]] = []
|
|
176
|
+
test_rel_changes: list[str] = []
|
|
177
|
+
|
|
178
|
+
if before_quality is not None and after_quality is not None:
|
|
179
|
+
b_q = {
|
|
180
|
+
(f.rule_id, f.file_path, f.symbol_name): f for f in before_quality.findings
|
|
181
|
+
}
|
|
182
|
+
a_q = {
|
|
183
|
+
(f.rule_id, f.file_path, f.symbol_name): f for f in after_quality.findings
|
|
184
|
+
}
|
|
185
|
+
for k in sorted(set(a_q.keys()) - set(b_q.keys()), key=lambda x: str(x)):
|
|
186
|
+
qf = a_q[k]
|
|
187
|
+
quality_regressions.append(
|
|
188
|
+
{
|
|
189
|
+
"finding_id": qf.finding_id,
|
|
190
|
+
"rule_id": qf.rule_id,
|
|
191
|
+
"severity": qf.severity.value,
|
|
192
|
+
"file_path": qf.file_path,
|
|
193
|
+
"explanation": qf.explanation,
|
|
194
|
+
}
|
|
195
|
+
)
|
|
196
|
+
# Rule 5 from previous releases: coverage loss is NEVER finding resolution!
|
|
197
|
+
if not coverage_delta["coverage_dropped"]:
|
|
198
|
+
for k in sorted(set(b_q.keys()) - set(a_q.keys()), key=lambda x: str(x)):
|
|
199
|
+
qf = b_q[k]
|
|
200
|
+
resolved_quality.append(
|
|
201
|
+
{
|
|
202
|
+
"finding_id": qf.finding_id,
|
|
203
|
+
"rule_id": qf.rule_id,
|
|
204
|
+
"file_path": qf.file_path,
|
|
205
|
+
"explanation": qf.explanation,
|
|
206
|
+
}
|
|
207
|
+
)
|
|
208
|
+
else:
|
|
209
|
+
limitations.append(
|
|
210
|
+
"AST coverage dropped between snapshots; missing quality findings are NOT marked as resolved."
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# Static test relationship changes
|
|
214
|
+
b_tests = {e.production_file: set(e.mapped_test_files) for e in before_quality.test_mapping.entries}
|
|
215
|
+
a_tests = {e.production_file: set(e.mapped_test_files) for e in after_quality.test_mapping.entries}
|
|
216
|
+
for pf in sorted(set(b_tests.keys()) | set(a_tests.keys())):
|
|
217
|
+
if b_tests.get(pf, set()) != a_tests.get(pf, set()):
|
|
218
|
+
test_rel_changes.append(
|
|
219
|
+
f"{pf}: tests {len(b_tests.get(pf, set()))} -> {len(a_tests.get(pf, set()))}"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
# 7. Intent vs actual scope comparison
|
|
223
|
+
unexpected_modules: list[str] = []
|
|
224
|
+
intent_vs_actual: dict[str, Any] = {}
|
|
225
|
+
if change_intent is not None:
|
|
226
|
+
intended_set = {f.replace("\\", "/").lstrip("./") for f in change_intent.intended_files}
|
|
227
|
+
actual_set = set(actual_changed_files)
|
|
228
|
+
unexpected_modules = sorted(actual_set - intended_set)
|
|
229
|
+
untouched_intended = sorted(intended_set - actual_set)
|
|
230
|
+
intent_vs_actual = {
|
|
231
|
+
"intended_files": sorted(intended_set),
|
|
232
|
+
"actual_changed_files": sorted(actual_set),
|
|
233
|
+
"unexpected_changed_files": unexpected_modules,
|
|
234
|
+
"untouched_intended_files": untouched_intended,
|
|
235
|
+
"scope_match": len(unexpected_modules) == 0 and len(untouched_intended) == 0,
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
# 8. Verdict calculation (consistent with PR Architecture Guardian)
|
|
239
|
+
has_critical_regression = bool(new_cycles) or any(
|
|
240
|
+
r.get("severity", "").lower() in ("critical", "high", "error")
|
|
241
|
+
for r in contract_regressions
|
|
242
|
+
) or any(
|
|
243
|
+
q.get("severity", "").lower() in ("critical", "high", "error")
|
|
244
|
+
for q in quality_regressions
|
|
245
|
+
)
|
|
246
|
+
has_warning = bool(contract_regressions) or bool(quality_regressions) or bool(unexpected_modules) or bool(coverage_delta["coverage_dropped"])
|
|
247
|
+
|
|
248
|
+
if has_critical_regression:
|
|
249
|
+
verdict = PostflightVerdict.FAIL
|
|
250
|
+
elif coverage_delta["coverage_dropped"]:
|
|
251
|
+
verdict = PostflightVerdict.WARNING
|
|
252
|
+
elif has_warning:
|
|
253
|
+
verdict = PostflightVerdict.WARNING
|
|
254
|
+
else:
|
|
255
|
+
verdict = PostflightVerdict.PASS
|
|
256
|
+
|
|
257
|
+
return VerificationResult(
|
|
258
|
+
verdict=verdict,
|
|
259
|
+
repo_id=repo_id,
|
|
260
|
+
before_snapshot_id=before_snapshot_id,
|
|
261
|
+
after_snapshot_id=after_snapshot_id,
|
|
262
|
+
freshness=freshness,
|
|
263
|
+
actual_changed_files=actual_changed_files[:100],
|
|
264
|
+
actual_changed_symbols=changed_symbols[:100],
|
|
265
|
+
added_dependency_edges=added_edges[:100],
|
|
266
|
+
removed_dependency_edges=removed_edges[:100],
|
|
267
|
+
new_cycles=new_cycles[:20],
|
|
268
|
+
resolved_cycles=resolved_cycles[:20],
|
|
269
|
+
contract_regressions=contract_regressions[:30],
|
|
270
|
+
quality_regressions=quality_regressions[:30],
|
|
271
|
+
resolved_quality_findings=resolved_quality[:30],
|
|
272
|
+
test_relationship_changes=test_rel_changes[:30],
|
|
273
|
+
coverage_delta=coverage_delta,
|
|
274
|
+
unexpected_affected_modules=unexpected_modules[:50],
|
|
275
|
+
intent_vs_actual=intent_vs_actual,
|
|
276
|
+
stale_evidence_ids=sorted(set(stale_evidence_ids or [])),
|
|
277
|
+
limitations=limitations,
|
|
278
|
+
)
|