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
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Deterministic, token-aware Repository Map Compiler for RepoDNA v0.11.0.
|
|
2
|
+
|
|
3
|
+
Inspired by Aider RepoMap and SCIP while strictly adhering to RepoDNA's zero-execution,
|
|
4
|
+
evidence-backed static analysis model:
|
|
5
|
+
- Prioritizes public/exported signatures, source ranges, and evidence references.
|
|
6
|
+
- Never dumps raw full source-code bodies into default repository maps.
|
|
7
|
+
- Explicitly discloses partial/unsupported language coverage limitations.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from collections import defaultdict
|
|
14
|
+
|
|
15
|
+
from repodna.agent.localization import TaskLocalizationEngine
|
|
16
|
+
from repodna.agent.models import (
|
|
17
|
+
AgentEvidenceReference,
|
|
18
|
+
EvidenceValidationStatus,
|
|
19
|
+
FreshnessMetadata,
|
|
20
|
+
RepositoryMap,
|
|
21
|
+
RepositoryMapMode,
|
|
22
|
+
RepositoryMapModule,
|
|
23
|
+
RepositoryMapSymbol,
|
|
24
|
+
TaskLocalization,
|
|
25
|
+
)
|
|
26
|
+
from repodna.agent.safety import build_trust_boundary, sanitize_untrusted_text
|
|
27
|
+
from repodna.agent.task import parse_agent_task
|
|
28
|
+
from repodna.agent.token_budget import (
|
|
29
|
+
TokenCounter,
|
|
30
|
+
build_context_budget,
|
|
31
|
+
clamp_token_budget,
|
|
32
|
+
effective_packing_budget,
|
|
33
|
+
)
|
|
34
|
+
from repodna.brain.indexer import SymbolIndexer
|
|
35
|
+
from repodna.intelligence.service import RepositoryIntelligenceService
|
|
36
|
+
from repodna.quality.models import QualityReport
|
|
37
|
+
from repodna.schemas.models import AnalysisResult, FileNode
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RepositoryMapCompiler:
|
|
41
|
+
"""Compiles deterministic, bounded, token-aware repository maps."""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
analysis: AnalysisResult,
|
|
46
|
+
indexer: SymbolIndexer,
|
|
47
|
+
repo_id: str,
|
|
48
|
+
snapshot_id: str,
|
|
49
|
+
quality_report: QualityReport | None = None,
|
|
50
|
+
live_changed_files: list[str] | None = None,
|
|
51
|
+
core_freshness: str = "fresh",
|
|
52
|
+
quality_freshness: str = "not_evaluated",
|
|
53
|
+
live_session_active: bool = False,
|
|
54
|
+
pending_live_analysis: bool = False,
|
|
55
|
+
) -> None:
|
|
56
|
+
self.analysis = analysis
|
|
57
|
+
self.indexer = indexer
|
|
58
|
+
self.repo_id = repo_id
|
|
59
|
+
self.snapshot_id = snapshot_id
|
|
60
|
+
self.quality_report = quality_report
|
|
61
|
+
self.live_changed_files = [
|
|
62
|
+
f.replace("\\", "/").lstrip("./") for f in (live_changed_files or [])
|
|
63
|
+
]
|
|
64
|
+
self.core_freshness = core_freshness
|
|
65
|
+
self.quality_freshness = quality_freshness
|
|
66
|
+
self.live_session_active = live_session_active
|
|
67
|
+
self.pending_live_analysis = pending_live_analysis
|
|
68
|
+
self._files_by_id: dict[str, FileNode] = {f.id: f for f in analysis.files}
|
|
69
|
+
|
|
70
|
+
def compile(
|
|
71
|
+
self,
|
|
72
|
+
mode: RepositoryMapMode = RepositoryMapMode.OVERVIEW,
|
|
73
|
+
task_text: str | None = None,
|
|
74
|
+
focus_symbol: str | None = None,
|
|
75
|
+
token_budget: int = 2048,
|
|
76
|
+
target_model: str = "generic",
|
|
77
|
+
tokenizer_pref: str = "auto",
|
|
78
|
+
max_modules: int = 25,
|
|
79
|
+
max_symbols_per_module: int = 8,
|
|
80
|
+
) -> RepositoryMap:
|
|
81
|
+
"""Compiles a bounded RepositoryMap honoring the requested token budget."""
|
|
82
|
+
clamped_budget = clamp_token_budget(token_budget)
|
|
83
|
+
eff_budget, _, _ = effective_packing_budget(clamped_budget, target_model, tokenizer_pref)
|
|
84
|
+
|
|
85
|
+
service = RepositoryIntelligenceService(self.analysis)
|
|
86
|
+
cov = service.get_analysis_coverage()
|
|
87
|
+
freshness = FreshnessMetadata(
|
|
88
|
+
repo_id=self.repo_id,
|
|
89
|
+
repository=self.analysis.repo_name,
|
|
90
|
+
snapshot_id=self.snapshot_id,
|
|
91
|
+
revision=self.indexer.revision or "WORKING_TREE",
|
|
92
|
+
core_freshness=self.core_freshness,
|
|
93
|
+
quality_freshness=self.quality_freshness,
|
|
94
|
+
live_session_active=self.live_session_active,
|
|
95
|
+
pending_live_analysis=self.pending_live_analysis,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# Build test & quality lookup maps
|
|
99
|
+
tests_by_prod: dict[str, list[str]] = defaultdict(list)
|
|
100
|
+
quality_by_file: dict[str, list[str]] = defaultdict(list)
|
|
101
|
+
if self.quality_report is not None:
|
|
102
|
+
for entry in self.quality_report.test_mapping.entries:
|
|
103
|
+
for tf in entry.mapped_test_files:
|
|
104
|
+
if tf not in tests_by_prod[entry.production_file]:
|
|
105
|
+
tests_by_prod[entry.production_file].append(tf)
|
|
106
|
+
for finding in self.quality_report.findings:
|
|
107
|
+
if finding.file_path:
|
|
108
|
+
quality_by_file[finding.file_path].append(
|
|
109
|
+
f"{finding.rule_id}:{finding.severity.value}"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Identify entrypoints (fan_in == 0 and fan_out > 0) and architectural boundaries
|
|
113
|
+
entrypoints = sorted(
|
|
114
|
+
f.id for f in self.analysis.files if f.fan_in == 0 and f.fan_out > 0
|
|
115
|
+
)[:15]
|
|
116
|
+
arch_boundaries: list[str] = []
|
|
117
|
+
if self.analysis.cycles:
|
|
118
|
+
arch_boundaries.append(
|
|
119
|
+
f"Detected {len(self.analysis.cycles)} circular dependency SCC(s)."
|
|
120
|
+
)
|
|
121
|
+
for arch_finding in self.analysis.health_report.findings[:6]:
|
|
122
|
+
arch_boundaries.append(f"[{arch_finding.rule_id}] {arch_finding.title}")
|
|
123
|
+
|
|
124
|
+
# Determine module ranking according to map mode
|
|
125
|
+
relevance_by_file: dict[str, float] = {}
|
|
126
|
+
localization: TaskLocalization | None = None
|
|
127
|
+
if mode == RepositoryMapMode.TASK_FOCUSED and task_text:
|
|
128
|
+
parsed = parse_agent_task(task_text)
|
|
129
|
+
loc_engine = TaskLocalizationEngine(
|
|
130
|
+
analysis=self.analysis,
|
|
131
|
+
indexer=self.indexer,
|
|
132
|
+
repo_id=self.repo_id,
|
|
133
|
+
snapshot_id=self.snapshot_id,
|
|
134
|
+
quality_report=self.quality_report,
|
|
135
|
+
live_changed_files=self.live_changed_files,
|
|
136
|
+
live_session_active=self.live_session_active,
|
|
137
|
+
pending_live_analysis=self.pending_live_analysis,
|
|
138
|
+
core_freshness=self.core_freshness,
|
|
139
|
+
quality_freshness=self.quality_freshness,
|
|
140
|
+
)
|
|
141
|
+
localization = loc_engine.localize(parsed)
|
|
142
|
+
for cand in localization.candidates:
|
|
143
|
+
relevance_by_file[cand.file_id] = cand.score
|
|
144
|
+
elif mode == RepositoryMapMode.SYMBOL_FOCUSED and focus_symbol:
|
|
145
|
+
low_sym = focus_symbol.strip().lower()
|
|
146
|
+
for fid, syms in self.indexer._symbols_by_file.items():
|
|
147
|
+
for sym in syms:
|
|
148
|
+
if sym.name.lower() == low_sym:
|
|
149
|
+
relevance_by_file[fid] = max(relevance_by_file.get(fid, 0.0), 50.0)
|
|
150
|
+
elif low_sym in sym.name.lower():
|
|
151
|
+
relevance_by_file[fid] = max(relevance_by_file.get(fid, 0.0), 20.0)
|
|
152
|
+
elif mode == RepositoryMapMode.ARCHITECTURE_FOCUSED:
|
|
153
|
+
for f in self.analysis.files:
|
|
154
|
+
score = (15.0 if f.in_cycle else 0.0) + (10.0 if f.is_hub else 0.0) + f.fan_in * 1.5
|
|
155
|
+
relevance_by_file[f.id] = score
|
|
156
|
+
elif mode == RepositoryMapMode.TEST_FOCUSED:
|
|
157
|
+
for f in self.analysis.files:
|
|
158
|
+
if tests_by_prod.get(f.id):
|
|
159
|
+
relevance_by_file[f.id] = 20.0 + len(tests_by_prod[f.id]) * 3.0
|
|
160
|
+
elif "test" in f.id.lower():
|
|
161
|
+
relevance_by_file[f.id] = 15.0
|
|
162
|
+
elif mode == RepositoryMapMode.CHANGE_FOCUSED:
|
|
163
|
+
live_set = set(self.live_changed_files)
|
|
164
|
+
for f in self.analysis.files:
|
|
165
|
+
if f.id in live_set:
|
|
166
|
+
relevance_by_file[f.id] = 60.0
|
|
167
|
+
elif any(imp in live_set for imp in f.imports_internal) or any(
|
|
168
|
+
dep in live_set for dep in f.imported_by
|
|
169
|
+
):
|
|
170
|
+
relevance_by_file[f.id] = 25.0
|
|
171
|
+
|
|
172
|
+
# Order candidate modules deterministically
|
|
173
|
+
ordered_files = sorted(
|
|
174
|
+
self.analysis.files,
|
|
175
|
+
key=lambda f: (
|
|
176
|
+
-relevance_by_file.get(f.id, 0.0),
|
|
177
|
+
-int(f.is_hub),
|
|
178
|
+
-f.fan_in,
|
|
179
|
+
-f.lines_code,
|
|
180
|
+
f.id,
|
|
181
|
+
),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
coverage_limitations: list[str] = []
|
|
185
|
+
if cov.partial_static_languages:
|
|
186
|
+
coverage_limitations.append(
|
|
187
|
+
f"Partial static resolution only: {', '.join(cov.partial_static_languages)}."
|
|
188
|
+
)
|
|
189
|
+
if cov.unsupported_languages:
|
|
190
|
+
coverage_limitations.append(
|
|
191
|
+
f"Unsupported AST languages (stats only): {', '.join(cov.unsupported_languages)}."
|
|
192
|
+
)
|
|
193
|
+
if self.pending_live_analysis:
|
|
194
|
+
coverage_limitations.append(
|
|
195
|
+
"Pending live analysis detected; map reflects the latest committed snapshot."
|
|
196
|
+
)
|
|
197
|
+
coverage_limitations.append(
|
|
198
|
+
"Repository map provides static AST signatures and ranges; it does not prove complete compiler semantic resolution."
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
redacted_count = 0
|
|
202
|
+
injection_signals: list[str] = []
|
|
203
|
+
all_candidates_count = min(len(ordered_files), max_modules)
|
|
204
|
+
|
|
205
|
+
# Build module candidates (signatures only, never raw bodies)
|
|
206
|
+
candidate_modules: list[RepositoryMapModule] = []
|
|
207
|
+
evidence_map: dict[str, AgentEvidenceReference] = {}
|
|
208
|
+
|
|
209
|
+
for f in ordered_files[:all_candidates_count]:
|
|
210
|
+
syms = self.indexer.find_by_file(f.id)
|
|
211
|
+
# Prioritize exported / public symbols, then classes/functions
|
|
212
|
+
sorted_syms = sorted(
|
|
213
|
+
syms,
|
|
214
|
+
key=lambda s: (-int(s.is_exported), s.line_start, s.name),
|
|
215
|
+
)[:max_symbols_per_module]
|
|
216
|
+
|
|
217
|
+
map_syms: list[RepositoryMapSymbol] = []
|
|
218
|
+
for s in sorted_syms:
|
|
219
|
+
raw_sig = s.signature or f"{s.kind.value} {s.name}"
|
|
220
|
+
safe_sig, sec_c, inj_s = sanitize_untrusted_text(raw_sig)
|
|
221
|
+
redacted_count += sec_c
|
|
222
|
+
injection_signals.extend(inj_s)
|
|
223
|
+
map_syms.append(
|
|
224
|
+
RepositoryMapSymbol(
|
|
225
|
+
symbol_id=s.id,
|
|
226
|
+
name=s.name,
|
|
227
|
+
qualified_name=s.qualified_name or s.name,
|
|
228
|
+
kind=s.kind.value,
|
|
229
|
+
signature=safe_sig[:180],
|
|
230
|
+
line_start=s.line_start,
|
|
231
|
+
line_end=s.line_end,
|
|
232
|
+
evidence_id=s.evidence_id,
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
if s.evidence_id and s.evidence_id not in evidence_map:
|
|
236
|
+
ev = self.indexer.ledger.get_by_id(s.evidence_id)
|
|
237
|
+
if ev is not None:
|
|
238
|
+
safe_snip, ev_sec, ev_inj = sanitize_untrusted_text(ev.code_snippet or "")
|
|
239
|
+
redacted_count += ev_sec
|
|
240
|
+
injection_signals.extend(ev_inj)
|
|
241
|
+
evidence_map[s.evidence_id] = AgentEvidenceReference(
|
|
242
|
+
evidence_id=ev.evidence_id,
|
|
243
|
+
repo_id=self.repo_id,
|
|
244
|
+
snapshot_id=self.snapshot_id,
|
|
245
|
+
revision=ev.repository_revision,
|
|
246
|
+
file_path=ev.file_path,
|
|
247
|
+
line_start=ev.line_start,
|
|
248
|
+
line_end=ev.line_end,
|
|
249
|
+
evidence_type=ev.evidence_type.value,
|
|
250
|
+
symbol_name=ev.symbol_name,
|
|
251
|
+
content_hash=ev.content_hash or "",
|
|
252
|
+
redacted=ev_sec > 0,
|
|
253
|
+
snippet=safe_snip[:240],
|
|
254
|
+
capability_level=ev.support_level.value,
|
|
255
|
+
status=(
|
|
256
|
+
EvidenceValidationStatus.STALE
|
|
257
|
+
if ev.is_stale
|
|
258
|
+
else EvidenceValidationStatus.VERIFIED
|
|
259
|
+
),
|
|
260
|
+
staleness_reason=ev.staleness_reason.value,
|
|
261
|
+
confidence_reason=ev.confidence_reason,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
layer = f.id.split("/")[0] if "/" in f.id else "root"
|
|
265
|
+
candidate_modules.append(
|
|
266
|
+
RepositoryMapModule(
|
|
267
|
+
file_id=f.id,
|
|
268
|
+
language=f.language,
|
|
269
|
+
lines_code=f.lines_code,
|
|
270
|
+
fan_in=f.fan_in,
|
|
271
|
+
fan_out=f.fan_out,
|
|
272
|
+
is_entrypoint=f.id in entrypoints,
|
|
273
|
+
is_hub=f.is_hub,
|
|
274
|
+
in_cycle=f.in_cycle,
|
|
275
|
+
layer=layer,
|
|
276
|
+
relevance_score=round(relevance_by_file.get(f.id, 0.0), 3),
|
|
277
|
+
exported_symbols=map_syms,
|
|
278
|
+
key_dependencies=sorted(f.imports_internal)[:6],
|
|
279
|
+
related_tests=tests_by_prod.get(f.id, [])[:4],
|
|
280
|
+
quality_signals=sorted(set(quality_by_file.get(f.id, [])))[:4],
|
|
281
|
+
)
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
trust = build_trust_boundary(redacted_count, injection_signals)
|
|
285
|
+
|
|
286
|
+
# Measure minimal envelope tokens (0 modules)
|
|
287
|
+
min_envelope_payload = json.dumps(
|
|
288
|
+
{
|
|
289
|
+
"mode": mode.value,
|
|
290
|
+
"repository": self.analysis.repo_name,
|
|
291
|
+
"snapshot_id": self.snapshot_id,
|
|
292
|
+
"supported_languages": cov.supported_languages,
|
|
293
|
+
"entrypoints": entrypoints[:5],
|
|
294
|
+
"coverage_limitations": coverage_limitations,
|
|
295
|
+
},
|
|
296
|
+
sort_keys=True,
|
|
297
|
+
)
|
|
298
|
+
req_min_budget = TokenCounter.count(
|
|
299
|
+
min_envelope_payload, target_model=target_model, tokenizer_pref=tokenizer_pref
|
|
300
|
+
).tokens
|
|
301
|
+
|
|
302
|
+
# Greedy packing of modules within eff_budget
|
|
303
|
+
packed_modules: list[RepositoryMapModule] = []
|
|
304
|
+
omitted_modules = 0
|
|
305
|
+
running_tokens = req_min_budget
|
|
306
|
+
for mod in candidate_modules:
|
|
307
|
+
mod_json = mod.model_dump_json()
|
|
308
|
+
mod_tokens = TokenCounter.count(
|
|
309
|
+
mod_json, target_model=target_model, tokenizer_pref=tokenizer_pref
|
|
310
|
+
).tokens
|
|
311
|
+
if running_tokens + mod_tokens <= eff_budget:
|
|
312
|
+
packed_modules.append(mod)
|
|
313
|
+
running_tokens += mod_tokens
|
|
314
|
+
else:
|
|
315
|
+
omitted_modules += 1
|
|
316
|
+
|
|
317
|
+
used_ev_ids = {
|
|
318
|
+
s.evidence_id
|
|
319
|
+
for m in packed_modules
|
|
320
|
+
for s in m.exported_symbols
|
|
321
|
+
if s.evidence_id
|
|
322
|
+
}
|
|
323
|
+
packed_evidence = [
|
|
324
|
+
evidence_map[eid] for eid in sorted(used_ev_ids) if eid in evidence_map
|
|
325
|
+
][:30]
|
|
326
|
+
|
|
327
|
+
omitted_sections: list[str] = []
|
|
328
|
+
if omitted_modules > 0:
|
|
329
|
+
omitted_sections.append("additional_modules")
|
|
330
|
+
|
|
331
|
+
# Final payload serialization verification
|
|
332
|
+
serialized_core = json.dumps(
|
|
333
|
+
{
|
|
334
|
+
"mode": mode.value,
|
|
335
|
+
"freshness": freshness.model_dump(mode="json"),
|
|
336
|
+
"supported_languages": cov.supported_languages,
|
|
337
|
+
"entrypoints": entrypoints,
|
|
338
|
+
"architectural_boundaries": arch_boundaries,
|
|
339
|
+
"modules": [m.model_dump(mode="json") for m in packed_modules],
|
|
340
|
+
"coverage_limitations": coverage_limitations,
|
|
341
|
+
},
|
|
342
|
+
sort_keys=True,
|
|
343
|
+
)
|
|
344
|
+
# If final serialized payload exceeds clamped_budget, trim modules until compliant or empty
|
|
345
|
+
while packed_modules:
|
|
346
|
+
chk = TokenCounter.count(
|
|
347
|
+
serialized_core, target_model=target_model, tokenizer_pref=tokenizer_pref
|
|
348
|
+
).tokens
|
|
349
|
+
if chk <= clamped_budget:
|
|
350
|
+
break
|
|
351
|
+
packed_modules.pop()
|
|
352
|
+
omitted_modules += 1
|
|
353
|
+
if "additional_modules" not in omitted_sections:
|
|
354
|
+
omitted_sections.append("additional_modules")
|
|
355
|
+
serialized_core = json.dumps(
|
|
356
|
+
{
|
|
357
|
+
"mode": mode.value,
|
|
358
|
+
"freshness": freshness.model_dump(mode="json"),
|
|
359
|
+
"supported_languages": cov.supported_languages,
|
|
360
|
+
"entrypoints": entrypoints,
|
|
361
|
+
"architectural_boundaries": arch_boundaries,
|
|
362
|
+
"modules": [m.model_dump(mode="json") for m in packed_modules],
|
|
363
|
+
"coverage_limitations": coverage_limitations,
|
|
364
|
+
},
|
|
365
|
+
sort_keys=True,
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
budget = build_context_budget(
|
|
369
|
+
serialized_payload=serialized_core,
|
|
370
|
+
requested_budget=clamped_budget,
|
|
371
|
+
required_minimum_budget=req_min_budget,
|
|
372
|
+
target_model=target_model,
|
|
373
|
+
tokenizer_pref=tokenizer_pref,
|
|
374
|
+
omitted_sections=omitted_sections,
|
|
375
|
+
omitted_candidates=omitted_modules,
|
|
376
|
+
total_candidates=all_candidates_count,
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
return RepositoryMap(
|
|
380
|
+
mode=mode,
|
|
381
|
+
freshness=freshness,
|
|
382
|
+
supported_languages=cov.supported_languages,
|
|
383
|
+
partial_static_languages=cov.partial_static_languages,
|
|
384
|
+
unsupported_languages=cov.unsupported_languages,
|
|
385
|
+
entrypoints=entrypoints,
|
|
386
|
+
architectural_boundaries=arch_boundaries,
|
|
387
|
+
modules=packed_modules,
|
|
388
|
+
evidence=packed_evidence,
|
|
389
|
+
budget=budget,
|
|
390
|
+
coverage_limitations=coverage_limitations,
|
|
391
|
+
trust_boundary=trust,
|
|
392
|
+
)
|
repodna/agent/safety.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Trust-boundary safety, secret redaction, and prompt-injection defense-in-depth utilities.
|
|
2
|
+
|
|
3
|
+
NOTE: Heuristic prompt-injection detection is strictly defense-in-depth and cannot
|
|
4
|
+
guarantee complete prevention of indirect prompt injection. RepoDNA enforces hard
|
|
5
|
+
architectural boundaries: zero repository code execution, zero shell execution,
|
|
6
|
+
strict workspace scoping, and explicit untrusted-data framing.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from repodna.agent.models import TrustBoundaryMetadata
|
|
15
|
+
|
|
16
|
+
# Extended secret patterns for agent outputs (always redacted before serialization)
|
|
17
|
+
_EXTRA_SECRET_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
|
|
18
|
+
("OpenAI / Anthropic API Key", re.compile(r"\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,200}\b")),
|
|
19
|
+
("Generic Bearer / Token Assignment", re.compile(r"(?i)(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|password)\s*[:=]\s*['\"][A-Za-z0-9_./+=-]{12,}['\"]")),
|
|
20
|
+
("Google API Key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
|
|
21
|
+
("JWT Token", re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b")),
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# Heuristic prompt injection indicators (defense-in-depth only; documented limitations)
|
|
25
|
+
_INJECTION_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
|
|
26
|
+
(
|
|
27
|
+
"instruction_override",
|
|
28
|
+
re.compile(
|
|
29
|
+
r"(?i)(?:ignore|disregard|forget)\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|prompts|rules)"
|
|
30
|
+
),
|
|
31
|
+
),
|
|
32
|
+
(
|
|
33
|
+
"turkish_instruction_override",
|
|
34
|
+
re.compile(
|
|
35
|
+
r"(?i)(?:önceki|onceki|yukarıdaki|yukaridaki)\s+(?:tüm\s+|tum\s+)?(?:talimatları|talimatlari|kuralları|kurallari)\s+(?:unut|yoksay|görmezden\s+gel|gormezden\s+gel)"
|
|
36
|
+
),
|
|
37
|
+
),
|
|
38
|
+
(
|
|
39
|
+
"system_prompt_spoof",
|
|
40
|
+
re.compile(r"(?i)(?:^|\n)\s*(?:system\s+prompt|system\s+instruction|###\s*system|<\s*system\s*>|you\s+are\s+now\s+in\s+developer\s+mode)"),
|
|
41
|
+
),
|
|
42
|
+
(
|
|
43
|
+
"exfiltration_directive",
|
|
44
|
+
re.compile(r"(?i)(?:exfiltrate|send|post|upload|curl|wget)\s+(?:all\s+)?(?:secrets|env|\.env|credentials|private\s+key|tokens)"),
|
|
45
|
+
),
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def redact_secrets(text: str) -> tuple[str, int]:
|
|
50
|
+
"""Redacts secret-like patterns from text via the unified redactor. Returns (redacted_text, redaction_count)."""
|
|
51
|
+
from repodna.security.validators import redact_secrets_unified
|
|
52
|
+
|
|
53
|
+
return redact_secrets_unified(text)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def detect_prompt_injection_signals(text: str) -> list[str]:
|
|
57
|
+
"""Detects heuristic prompt-injection patterns in untrusted repository text.
|
|
58
|
+
|
|
59
|
+
Returns a list of matched pattern category names.
|
|
60
|
+
"""
|
|
61
|
+
if not text:
|
|
62
|
+
return []
|
|
63
|
+
hits: list[str] = []
|
|
64
|
+
for name, pattern in _INJECTION_PATTERNS:
|
|
65
|
+
if pattern.search(text):
|
|
66
|
+
hits.append(name)
|
|
67
|
+
return hits
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def sanitize_untrusted_text(text: str) -> tuple[str, int, list[str]]:
|
|
71
|
+
"""Sanitizes untrusted repository text for safe inclusion in agent context packs.
|
|
72
|
+
|
|
73
|
+
- Strips null bytes and normalizes newlines.
|
|
74
|
+
- Neutralizes triple-backtick fence breakouts.
|
|
75
|
+
- Redacts secret patterns.
|
|
76
|
+
- Detects (and neutralizes) high-confidence prompt-injection phrases.
|
|
77
|
+
|
|
78
|
+
Returns (safe_text, redacted_secret_count, injection_signals).
|
|
79
|
+
"""
|
|
80
|
+
if not text:
|
|
81
|
+
return "", 0, []
|
|
82
|
+
cleaned = text.replace("\x00", "").replace("\r\n", "\n").replace("\r", "\n")
|
|
83
|
+
cleaned = re.sub(r"`{3,}", "'''", cleaned)
|
|
84
|
+
cleaned, secret_count = redact_secrets(cleaned)
|
|
85
|
+
signals = detect_prompt_injection_signals(cleaned)
|
|
86
|
+
if signals:
|
|
87
|
+
for _, pattern in _INJECTION_PATTERNS:
|
|
88
|
+
cleaned = pattern.sub("[NEUTRALIZED_UNTRUSTED_INSTRUCTION]", cleaned)
|
|
89
|
+
return cleaned, secret_count, signals
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def sha256_short(text: str, length: int = 16) -> str:
|
|
93
|
+
"""Deterministic truncated SHA-256 hex digest."""
|
|
94
|
+
return hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()[:length]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def build_trust_boundary(
|
|
98
|
+
redacted_secrets_count: int = 0,
|
|
99
|
+
injection_signals: list[str] | None = None,
|
|
100
|
+
) -> TrustBoundaryMetadata:
|
|
101
|
+
"""Builds a TrustBoundaryMetadata instance from observed safety counters."""
|
|
102
|
+
unique_signals = sorted(set(injection_signals or []))
|
|
103
|
+
notes = [
|
|
104
|
+
f"Heuristic untrusted-instruction signal detected: {sig} (neutralized; heuristic filter is defense-in-depth only)."
|
|
105
|
+
for sig in unique_signals
|
|
106
|
+
]
|
|
107
|
+
return TrustBoundaryMetadata(
|
|
108
|
+
injection_signals_detected=len(unique_signals),
|
|
109
|
+
injection_signal_notes=notes,
|
|
110
|
+
redacted_secrets_count=redacted_secrets_count,
|
|
111
|
+
)
|