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,379 @@
|
|
|
1
|
+
"""Agent Context Builder with mode selection, token estimation, and deterministic truncation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from repodna.brain.indexer import SymbolIndexer
|
|
9
|
+
from repodna.brain.retrieval import SmartRetrievalEngine
|
|
10
|
+
from repodna.context.models import AgentContextResponse
|
|
11
|
+
from repodna.intelligence.service import RepositoryIntelligenceService
|
|
12
|
+
from repodna.schemas.models import AnalysisResult
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AgentContextBuilder:
|
|
16
|
+
"""Builds controlled, token-budgeted architectural context for LLM agents."""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def count_tokens(cls, text: str) -> tuple[int, str]:
|
|
20
|
+
"""
|
|
21
|
+
Counts tokens using a real tokenizer (tiktoken) if available, or deterministic heuristic.
|
|
22
|
+
Returns (token_count, method_name).
|
|
23
|
+
"""
|
|
24
|
+
if not text:
|
|
25
|
+
return 0, "empty"
|
|
26
|
+
try:
|
|
27
|
+
import tiktoken
|
|
28
|
+
|
|
29
|
+
enc = tiktoken.get_encoding("cl100k_base")
|
|
30
|
+
return len(enc.encode(text)), "tiktoken_cl100k"
|
|
31
|
+
except Exception:
|
|
32
|
+
return max(1, len(text) // 4), "heuristic_chars"
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def estimate_tokens(cls, text: str) -> int:
|
|
36
|
+
"""Approximates tokens assuming ~4 characters per token on average for English/code."""
|
|
37
|
+
count, _ = cls.count_tokens(text)
|
|
38
|
+
return count
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def build_context(
|
|
42
|
+
cls,
|
|
43
|
+
analysis: AnalysisResult,
|
|
44
|
+
mode: str = "compact",
|
|
45
|
+
query: str | None = None,
|
|
46
|
+
target_files: list[str] | None = None,
|
|
47
|
+
max_tokens: int | None = None,
|
|
48
|
+
max_chars: int | None = None,
|
|
49
|
+
page: int = 0,
|
|
50
|
+
page_size: int = 15,
|
|
51
|
+
revision: str | None = "HEAD",
|
|
52
|
+
indexer: SymbolIndexer | None = None,
|
|
53
|
+
minimal_contract: bool = False,
|
|
54
|
+
) -> AgentContextResponse:
|
|
55
|
+
resolved_revision = revision or (indexer.revision if indexer and indexer.revision else None) or "WORKING_TREE"
|
|
56
|
+
service = RepositoryIntelligenceService(analysis)
|
|
57
|
+
overview = service.get_repository_overview()
|
|
58
|
+
cov = service.get_analysis_coverage()
|
|
59
|
+
|
|
60
|
+
coverage_data = {
|
|
61
|
+
"confidence": cov.confidence,
|
|
62
|
+
"confidence_reason": cov.confidence_reason,
|
|
63
|
+
"ast_loc_coverage_pct": cov.ast_loc_coverage_pct,
|
|
64
|
+
"ast_file_coverage_pct": cov.ast_file_coverage_pct,
|
|
65
|
+
"supported_languages": cov.supported_languages,
|
|
66
|
+
"partial_static_languages": cov.partial_static_languages,
|
|
67
|
+
"unsupported_languages": cov.unsupported_languages,
|
|
68
|
+
"unverified_rules": cov.unverified_rules,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
requested_scope = {
|
|
72
|
+
"mode": mode,
|
|
73
|
+
"query": query,
|
|
74
|
+
"target_files": target_files,
|
|
75
|
+
"page": page,
|
|
76
|
+
"page_size": page_size,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
evidence: list[str] = []
|
|
80
|
+
evidence_records: list[dict[str, Any]] = []
|
|
81
|
+
limitations: list[str] = []
|
|
82
|
+
relevant_modules: list[dict[str, Any]] = []
|
|
83
|
+
|
|
84
|
+
if cov.partial_static_languages:
|
|
85
|
+
limitations.append(
|
|
86
|
+
f"Languages {cov.partial_static_languages} were analyzed using partial static patterns. Full AST dependency edges are not guaranteed."
|
|
87
|
+
)
|
|
88
|
+
if cov.unsupported_languages:
|
|
89
|
+
limitations.append(
|
|
90
|
+
f"Languages {cov.unsupported_languages} are unsupported for AST graph analysis. Only basic file stats were gathered."
|
|
91
|
+
)
|
|
92
|
+
if cov.unverified_rules:
|
|
93
|
+
limitations.append(
|
|
94
|
+
f"Rules {cov.unverified_rules} could not be fully verified due to partial dependency coverage."
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# Raw code tokens calculation across candidate / total codebase
|
|
98
|
+
total_raw_code_tokens = sum(max(1, f.lines_code * 8) for f in analysis.files)
|
|
99
|
+
|
|
100
|
+
# Zero or negative token budget: return safe minimal truncated response
|
|
101
|
+
if max_tokens is not None and max_tokens <= 0:
|
|
102
|
+
limitations.append(
|
|
103
|
+
f"Requested token budget ({max_tokens}) is zero or negative. Returned minimal truncated response."
|
|
104
|
+
)
|
|
105
|
+
return AgentContextResponse(
|
|
106
|
+
repository=analysis.repo_name,
|
|
107
|
+
revision=resolved_revision,
|
|
108
|
+
generated_at=datetime.now(UTC),
|
|
109
|
+
analysis_version="0.5.0",
|
|
110
|
+
mode=mode,
|
|
111
|
+
analysis_coverage=coverage_data,
|
|
112
|
+
confidence_level=cov.confidence,
|
|
113
|
+
requested_scope=requested_scope,
|
|
114
|
+
summary="Requested token budget is zero or negative.",
|
|
115
|
+
relevant_modules=[],
|
|
116
|
+
evidence=[],
|
|
117
|
+
evidence_records=[],
|
|
118
|
+
limitations=limitations,
|
|
119
|
+
truncated=True,
|
|
120
|
+
continuation_token=f"page={page}",
|
|
121
|
+
estimated_tokens=0,
|
|
122
|
+
raw_tokens_estimate=total_raw_code_tokens,
|
|
123
|
+
token_savings_pct=100.0,
|
|
124
|
+
estimated_savings_pct=100.0,
|
|
125
|
+
is_savings_estimated=True,
|
|
126
|
+
token_counting_method="heuristic_zero_budget",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
if mode == "compact":
|
|
130
|
+
summary = overview.summary_text
|
|
131
|
+
hubs_and_large = sorted(
|
|
132
|
+
analysis.files, key=lambda f: (-int(f.is_hub), -f.fan_in, -f.lines_code, f.id)
|
|
133
|
+
)
|
|
134
|
+
start_idx = page * page_size
|
|
135
|
+
page_files = hubs_and_large[start_idx : start_idx + page_size]
|
|
136
|
+
|
|
137
|
+
for f in page_files:
|
|
138
|
+
relevant_modules.append(
|
|
139
|
+
{
|
|
140
|
+
"id": f.id,
|
|
141
|
+
"language": f.language,
|
|
142
|
+
"lines_code": f.lines_code,
|
|
143
|
+
"fan_in": f.fan_in,
|
|
144
|
+
"fan_out": f.fan_out,
|
|
145
|
+
"instability": f.instability,
|
|
146
|
+
"is_hub": f.is_hub,
|
|
147
|
+
"in_cycle": f.in_cycle,
|
|
148
|
+
"cycle_ids": f.cycle_ids,
|
|
149
|
+
}
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
for finding in analysis.health_report.findings[:3]:
|
|
153
|
+
evidence.append(
|
|
154
|
+
f"[{finding.rule_id}] {finding.title} ({finding.severity.value.upper()}): {finding.remediation}"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
has_more = (start_idx + page_size) < len(hubs_and_large)
|
|
158
|
+
|
|
159
|
+
elif mode == "focused":
|
|
160
|
+
if query:
|
|
161
|
+
if indexer is not None:
|
|
162
|
+
retrieval_engine = SmartRetrievalEngine(indexer=indexer, analysis=analysis)
|
|
163
|
+
search_res = retrieval_engine.search(query=query, limit=page_size * (page + 1))
|
|
164
|
+
summary = search_res.summary_text
|
|
165
|
+
start_idx = page * page_size
|
|
166
|
+
paged_matches = search_res.matches[start_idx : start_idx + page_size]
|
|
167
|
+
has_more = (start_idx + page_size) < len(search_res.matches)
|
|
168
|
+
|
|
169
|
+
for m in paged_matches:
|
|
170
|
+
relevant_modules.append(
|
|
171
|
+
{
|
|
172
|
+
"id": m.file_id,
|
|
173
|
+
"language": m.language,
|
|
174
|
+
"lines_code": m.lines_code,
|
|
175
|
+
"fan_in": m.fan_in,
|
|
176
|
+
"fan_out": m.fan_out,
|
|
177
|
+
"is_hub": m.is_hub,
|
|
178
|
+
"in_cycle": m.in_cycle,
|
|
179
|
+
"relevance_score": m.score,
|
|
180
|
+
"relevance_tier": m.relevance_tier,
|
|
181
|
+
"match_reasons": m.match_reasons,
|
|
182
|
+
"matching_symbols": [s.model_dump() for s in m.matched_symbols],
|
|
183
|
+
}
|
|
184
|
+
)
|
|
185
|
+
for ev_item in m.evidence_items:
|
|
186
|
+
evidence_records.append(ev_item.model_dump())
|
|
187
|
+
evidence.append(f"[{ev_item.evidence_id}] {ev_item.file_path}:{ev_item.line_start} {ev_item.confidence_reason}")
|
|
188
|
+
else:
|
|
189
|
+
matches_resp = service.find_relevant_modules(query, limit=page_size * (page + 1))
|
|
190
|
+
summary = matches_resp.summary_text
|
|
191
|
+
start_idx = page * page_size
|
|
192
|
+
legacy_matches = matches_resp.matches[start_idx : start_idx + page_size]
|
|
193
|
+
has_more = (start_idx + page_size) < len(matches_resp.matches)
|
|
194
|
+
|
|
195
|
+
for lm in legacy_matches:
|
|
196
|
+
node = service._files_by_id.get(lm.file_id)
|
|
197
|
+
relevant_modules.append(
|
|
198
|
+
{
|
|
199
|
+
"id": lm.file_id,
|
|
200
|
+
"language": lm.language,
|
|
201
|
+
"lines_code": node.lines_code if node else 0,
|
|
202
|
+
"fan_in": lm.fan_in,
|
|
203
|
+
"fan_out": lm.fan_out,
|
|
204
|
+
"is_hub": node.is_hub if node else False,
|
|
205
|
+
"in_cycle": node.in_cycle if node else False,
|
|
206
|
+
"cycle_ids": node.cycle_ids if node else [],
|
|
207
|
+
"relevance_score": lm.relevance_score,
|
|
208
|
+
"match_reasons": lm.match_reasons,
|
|
209
|
+
}
|
|
210
|
+
)
|
|
211
|
+
for lm in legacy_matches:
|
|
212
|
+
for reason in lm.match_reasons:
|
|
213
|
+
evidence.append(f"[{lm.file_id}] {reason}")
|
|
214
|
+
|
|
215
|
+
elif target_files:
|
|
216
|
+
impact = service.get_change_impact(target_files)
|
|
217
|
+
summary = impact.summary_text
|
|
218
|
+
has_more = False
|
|
219
|
+
|
|
220
|
+
for tf in target_files:
|
|
221
|
+
try:
|
|
222
|
+
dtls = service.get_module_details(tf)
|
|
223
|
+
relevant_modules.append(
|
|
224
|
+
{
|
|
225
|
+
"id": dtls.file_id,
|
|
226
|
+
"language": dtls.language,
|
|
227
|
+
"lines_code": dtls.lines_code,
|
|
228
|
+
"fan_in": dtls.fan_in,
|
|
229
|
+
"fan_out": dtls.fan_out,
|
|
230
|
+
"instability": dtls.instability,
|
|
231
|
+
"is_hub": dtls.is_hub,
|
|
232
|
+
"in_cycle": dtls.in_cycle,
|
|
233
|
+
"cycle_ids": dtls.cycle_ids,
|
|
234
|
+
"dependencies_internal": dtls.dependencies_internal,
|
|
235
|
+
"dependents_internal": dtls.dependents_internal,
|
|
236
|
+
}
|
|
237
|
+
)
|
|
238
|
+
except KeyError:
|
|
239
|
+
limitations.append(f"Target file '{tf}' not recognized in repository index.")
|
|
240
|
+
|
|
241
|
+
for risk in impact.risk_factors:
|
|
242
|
+
evidence.append(risk)
|
|
243
|
+
else:
|
|
244
|
+
summary = overview.summary_text
|
|
245
|
+
has_more = False
|
|
246
|
+
|
|
247
|
+
else: # "deep" mode
|
|
248
|
+
arch_map = service.get_architecture_map(level="clusters")
|
|
249
|
+
summary = (
|
|
250
|
+
f"{overview.summary_text}\n\n"
|
|
251
|
+
f"{arch_map.summary_text}\n"
|
|
252
|
+
f"Total Package Clusters: {arch_map.total_clusters}"
|
|
253
|
+
)
|
|
254
|
+
start_idx = page * page_size
|
|
255
|
+
sorted_all = sorted(analysis.files, key=lambda f: (-f.fan_in, f.id))
|
|
256
|
+
page_files = sorted_all[start_idx : start_idx + page_size]
|
|
257
|
+
has_more = (start_idx + page_size) < len(sorted_all)
|
|
258
|
+
|
|
259
|
+
for f in page_files:
|
|
260
|
+
relevant_modules.append(
|
|
261
|
+
{
|
|
262
|
+
"id": f.id,
|
|
263
|
+
"language": f.language,
|
|
264
|
+
"lines_code": f.lines_code,
|
|
265
|
+
"fan_in": f.fan_in,
|
|
266
|
+
"fan_out": f.fan_out,
|
|
267
|
+
"instability": f.instability,
|
|
268
|
+
"is_hub": f.is_hub,
|
|
269
|
+
"in_cycle": f.in_cycle,
|
|
270
|
+
"cycle_ids": f.cycle_ids,
|
|
271
|
+
"symbols": [s.name for s in f.symbols[:5]],
|
|
272
|
+
}
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
for finding in analysis.health_report.findings:
|
|
276
|
+
for ev_str in finding.evidence:
|
|
277
|
+
evidence.append(f"[{finding.rule_id}] {ev_str}")
|
|
278
|
+
|
|
279
|
+
continuation_token = f"page={page + 1}" if has_more else None
|
|
280
|
+
truncated = has_more
|
|
281
|
+
|
|
282
|
+
# Check character and token budget limits
|
|
283
|
+
char_budget = max_chars or (max_tokens * 4 if max_tokens else None)
|
|
284
|
+
target_tokens = max_tokens or (char_budget // 4 if char_budget else None)
|
|
285
|
+
|
|
286
|
+
if char_budget or target_tokens:
|
|
287
|
+
test_resp = AgentContextResponse(
|
|
288
|
+
repository=analysis.repo_name,
|
|
289
|
+
revision=resolved_revision,
|
|
290
|
+
generated_at=datetime.now(UTC),
|
|
291
|
+
analysis_version="0.5.0",
|
|
292
|
+
mode=mode,
|
|
293
|
+
analysis_coverage=coverage_data,
|
|
294
|
+
confidence_level=cov.confidence,
|
|
295
|
+
requested_scope=requested_scope,
|
|
296
|
+
summary=summary,
|
|
297
|
+
relevant_modules=relevant_modules,
|
|
298
|
+
evidence=evidence,
|
|
299
|
+
evidence_records=evidence_records,
|
|
300
|
+
limitations=limitations,
|
|
301
|
+
truncated=truncated,
|
|
302
|
+
continuation_token=continuation_token,
|
|
303
|
+
minimal_contract=minimal_contract,
|
|
304
|
+
)
|
|
305
|
+
md_text = test_resp.as_markdown()
|
|
306
|
+
curr_tokens, method_used = cls.count_tokens(md_text)
|
|
307
|
+
|
|
308
|
+
max_prune_steps = len(evidence_records) + len(evidence) + len(relevant_modules) + 10
|
|
309
|
+
step = 0
|
|
310
|
+
while step < max_prune_steps:
|
|
311
|
+
step += 1
|
|
312
|
+
exceeds_chars = bool(char_budget and len(md_text) > char_budget)
|
|
313
|
+
exceeds_tokens = bool(target_tokens and curr_tokens > target_tokens)
|
|
314
|
+
if not (exceeds_chars or exceeds_tokens):
|
|
315
|
+
break
|
|
316
|
+
|
|
317
|
+
truncated = True
|
|
318
|
+
continuation_token = f"page={page + 1}"
|
|
319
|
+
|
|
320
|
+
# Pruning hierarchy: evidence_records -> evidence -> relevant_modules -> summary
|
|
321
|
+
if evidence_records:
|
|
322
|
+
evidence_records.pop()
|
|
323
|
+
elif evidence:
|
|
324
|
+
evidence.pop()
|
|
325
|
+
elif relevant_modules:
|
|
326
|
+
relevant_modules.pop()
|
|
327
|
+
elif len(summary) > 30 and not summary.endswith("[TRUNCATED DUE TO BUDGET]"):
|
|
328
|
+
summary = summary[:30] + "... [TRUNCATED DUE TO BUDGET]"
|
|
329
|
+
elif minimal_contract and summary:
|
|
330
|
+
summary = ""
|
|
331
|
+
else:
|
|
332
|
+
# Minimal metadata alone exceeds budget
|
|
333
|
+
msg = f"Header metadata alone exceeds requested budget of {target_tokens} tokens."
|
|
334
|
+
if msg not in limitations:
|
|
335
|
+
limitations.append(msg)
|
|
336
|
+
break
|
|
337
|
+
|
|
338
|
+
test_resp.summary = summary
|
|
339
|
+
test_resp.relevant_modules = relevant_modules
|
|
340
|
+
test_resp.evidence = evidence
|
|
341
|
+
test_resp.evidence_records = evidence_records
|
|
342
|
+
test_resp.limitations = limitations
|
|
343
|
+
test_resp.truncated = truncated
|
|
344
|
+
test_resp.continuation_token = continuation_token
|
|
345
|
+
md_text = test_resp.as_markdown()
|
|
346
|
+
curr_tokens, method_used = cls.count_tokens(md_text)
|
|
347
|
+
|
|
348
|
+
final_resp = AgentContextResponse(
|
|
349
|
+
repository=analysis.repo_name,
|
|
350
|
+
revision=resolved_revision,
|
|
351
|
+
generated_at=datetime.now(UTC),
|
|
352
|
+
analysis_version="0.5.0",
|
|
353
|
+
mode=mode,
|
|
354
|
+
analysis_coverage=coverage_data,
|
|
355
|
+
confidence_level=cov.confidence,
|
|
356
|
+
requested_scope=requested_scope,
|
|
357
|
+
summary=summary,
|
|
358
|
+
relevant_modules=relevant_modules,
|
|
359
|
+
evidence=evidence,
|
|
360
|
+
evidence_records=evidence_records,
|
|
361
|
+
limitations=limitations,
|
|
362
|
+
truncated=truncated,
|
|
363
|
+
continuation_token=continuation_token,
|
|
364
|
+
minimal_contract=minimal_contract,
|
|
365
|
+
)
|
|
366
|
+
final_md = final_resp.as_markdown()
|
|
367
|
+
final_tokens, method = cls.count_tokens(final_md)
|
|
368
|
+
savings = (
|
|
369
|
+
max(0.0, (1.0 - (final_tokens / max(1, total_raw_code_tokens))) * 100.0)
|
|
370
|
+
if total_raw_code_tokens > final_tokens
|
|
371
|
+
else 0.0
|
|
372
|
+
)
|
|
373
|
+
final_resp.estimated_tokens = final_tokens
|
|
374
|
+
final_resp.raw_tokens_estimate = total_raw_code_tokens
|
|
375
|
+
final_resp.token_savings_pct = round(savings, 1)
|
|
376
|
+
final_resp.estimated_savings_pct = round(savings, 1)
|
|
377
|
+
final_resp.is_savings_estimated = (method != "tiktoken_cl100k")
|
|
378
|
+
final_resp.token_counting_method = method
|
|
379
|
+
return final_resp
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Typed Pydantic schemas for the Agent-Ready Context Engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
_PROMPT_INJECTION_PATTERN = re.compile(
|
|
13
|
+
r"(?i)\b(system\s+instruction|system\s+prompt|ignore\s+(all\s+)?previous\s+instructions|disregard\s+(all\s+)?prior\s+instructions|you\s+are\s+now\s+in\s+developer\s+mode)\b"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sanitize_untrusted_context_text(text: str) -> str:
|
|
18
|
+
"""Neutralizes markdown fence breakouts, null bytes, and high-confidence prompt injection phrasing in untrusted code metadata."""
|
|
19
|
+
if not text:
|
|
20
|
+
return ""
|
|
21
|
+
cleaned = text.replace("\x00", "").replace("\r\n", "\n").replace("\r", "\n")
|
|
22
|
+
cleaned = re.sub(r"`{3,}", "'''", cleaned)
|
|
23
|
+
cleaned = _PROMPT_INJECTION_PATTERN.sub("[REDACTED_INJECTION_KEYWORD]", cleaned)
|
|
24
|
+
return cleaned
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AgentContextResponse(BaseModel):
|
|
28
|
+
repository: str
|
|
29
|
+
revision: str
|
|
30
|
+
generated_at: datetime
|
|
31
|
+
analysis_version: str = "0.5.0"
|
|
32
|
+
mode: str = "compact" # "compact", "focused", "deep"
|
|
33
|
+
analysis_coverage: dict[str, Any]
|
|
34
|
+
confidence_level: str
|
|
35
|
+
requested_scope: dict[str, Any]
|
|
36
|
+
summary: str
|
|
37
|
+
relevant_modules: list[dict[str, Any]] = Field(default_factory=list)
|
|
38
|
+
evidence: list[str] = Field(default_factory=list)
|
|
39
|
+
evidence_records: list[dict[str, Any]] = Field(default_factory=list)
|
|
40
|
+
limitations: list[str] = Field(default_factory=list)
|
|
41
|
+
truncated: bool = False
|
|
42
|
+
continuation_token: str | None = None
|
|
43
|
+
estimated_tokens: int = 0
|
|
44
|
+
raw_tokens_estimate: int = 0
|
|
45
|
+
token_savings_pct: float = 0.0
|
|
46
|
+
estimated_savings_pct: float = 0.0
|
|
47
|
+
is_savings_estimated: bool = True
|
|
48
|
+
token_counting_method: str = "heuristic_chars"
|
|
49
|
+
minimal_contract: bool = False
|
|
50
|
+
|
|
51
|
+
def as_markdown(self) -> str:
|
|
52
|
+
"""Renders an agent-friendly, token-efficient Markdown document."""
|
|
53
|
+
if self.minimal_contract:
|
|
54
|
+
trunc_tag = " [TRUNCATED]" if self.truncated else ""
|
|
55
|
+
lines = [f"# {self.repository} ({self.revision}){trunc_tag}"]
|
|
56
|
+
if self.summary and len(self.summary) <= 60:
|
|
57
|
+
lines.append(sanitize_untrusted_context_text(self.summary))
|
|
58
|
+
if self.relevant_modules:
|
|
59
|
+
for mod in self.relevant_modules[:3]:
|
|
60
|
+
lines.append(f"- `{mod.get('id', '')}`")
|
|
61
|
+
return "\n".join(lines)
|
|
62
|
+
lines = [
|
|
63
|
+
f"# RepoDNA Context [{self.mode.upper()}] â {self.repository} ({self.revision})",
|
|
64
|
+
f"**Confidence:** {self.confidence_level.upper()} | **Analysis Version:** v{self.analysis_version}",
|
|
65
|
+
f"**AST Coverage:** {self.analysis_coverage.get('ast_loc_coverage_pct', 0.0):.1f}% LOC | **Languages:** {', '.join(self.analysis_coverage.get('supported_languages', [])) or 'None'}",
|
|
66
|
+
]
|
|
67
|
+
if self.raw_tokens_estimate > 0:
|
|
68
|
+
savings_val = self.estimated_savings_pct or self.token_savings_pct
|
|
69
|
+
lines.append(
|
|
70
|
+
f"**Token Budget:** ~{self.estimated_tokens:,} tokens "
|
|
71
|
+
f"({savings_val:.1f}% estimated reduction vs {self.raw_tokens_estimate:,} raw code tokens [method: {self.token_counting_method}])"
|
|
72
|
+
)
|
|
73
|
+
lines.extend(["", "## Architectural Summary", sanitize_untrusted_context_text(self.summary), ""])
|
|
74
|
+
|
|
75
|
+
if self.relevant_modules:
|
|
76
|
+
lines.append(f"## Modules ({len(self.relevant_modules)})")
|
|
77
|
+
for mod in self.relevant_modules:
|
|
78
|
+
lines.append(
|
|
79
|
+
f"- `{mod.get('id', '')}` ({mod.get('language', '')}, {mod.get('lines_code', 0)} LOC) â "
|
|
80
|
+
f"Fan-In: {mod.get('fan_in', 0)}, Fan-Out: {mod.get('fan_out', 0)}, Instability: {mod.get('instability', 0.0):.2f}"
|
|
81
|
+
)
|
|
82
|
+
if mod.get("in_cycle"):
|
|
83
|
+
lines.append(f" * â ī¸ Circular Dependency participant: {', '.join(mod.get('cycle_ids', []))}")
|
|
84
|
+
if mod.get("is_hub"):
|
|
85
|
+
lines.append(" * đī¸ Architectural Hub (high afferent coupling)")
|
|
86
|
+
if mod.get("matching_symbols"):
|
|
87
|
+
sym_names = [
|
|
88
|
+
sanitize_untrusted_context_text(str(s.get("name")))
|
|
89
|
+
for s in mod.get("matching_symbols", [])
|
|
90
|
+
if isinstance(s, dict) and s.get("name")
|
|
91
|
+
]
|
|
92
|
+
if sym_names:
|
|
93
|
+
lines.append(f" * Verified Symbols: {', '.join(sym_names[:4])}")
|
|
94
|
+
if mod.get("match_reasons"):
|
|
95
|
+
reasons = [sanitize_untrusted_context_text(r) for r in mod.get("match_reasons", [])]
|
|
96
|
+
if reasons:
|
|
97
|
+
lines.append(f" * Why relevant: {'; '.join(reasons[:2])}")
|
|
98
|
+
lines.append("")
|
|
99
|
+
|
|
100
|
+
if self.evidence_records:
|
|
101
|
+
lines.append(f"## Evidence Citations ({len(self.evidence_records)})")
|
|
102
|
+
for ev in self.evidence_records:
|
|
103
|
+
ev_id = ev.get("evidence_id", "")
|
|
104
|
+
f_path = ev.get("file_path", "")
|
|
105
|
+
l_start = ev.get("line_start", 1)
|
|
106
|
+
l_end = ev.get("line_end", 1)
|
|
107
|
+
sym = sanitize_untrusted_context_text(ev.get("symbol_name") or ev.get("evidence_type", ""))
|
|
108
|
+
conf = sanitize_untrusted_context_text(ev.get("confidence_reason", ""))
|
|
109
|
+
stale_mark = " [STALE]" if ev.get("is_stale") else ""
|
|
110
|
+
lines.append(f"- `[{ev_id}]` `{f_path}:{l_start}-{l_end}` **{sym}**{stale_mark} â {conf}")
|
|
111
|
+
lines.append("")
|
|
112
|
+
elif self.evidence:
|
|
113
|
+
lines.append(f"## Evidence & Violations ({len(self.evidence)})")
|
|
114
|
+
for ev_str in self.evidence:
|
|
115
|
+
lines.append(f"- {sanitize_untrusted_context_text(ev_str)}")
|
|
116
|
+
lines.append("")
|
|
117
|
+
|
|
118
|
+
if self.limitations:
|
|
119
|
+
lines.append("## Analysis Limitations")
|
|
120
|
+
for lim in self.limitations:
|
|
121
|
+
lines.append(f"- âšī¸ {sanitize_untrusted_context_text(lim)}")
|
|
122
|
+
lines.append("")
|
|
123
|
+
|
|
124
|
+
if self.truncated:
|
|
125
|
+
lines.append(
|
|
126
|
+
f"> â ī¸ **Response Truncated to fit token budget.** "
|
|
127
|
+
f"Next page continuation token: `{self.continuation_token}`"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return "\n".join(lines)
|
|
131
|
+
|
|
132
|
+
def as_json(self, indent: int = 2) -> str:
|
|
133
|
+
return json.dumps(self.model_dump(mode="json"), indent=indent)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""RepoDNA Architecture Contract package."""
|
|
2
|
+
|
|
3
|
+
from repodna.contract.evaluator import ContractEvaluator
|
|
4
|
+
from repodna.contract.loader import (
|
|
5
|
+
find_contract_file,
|
|
6
|
+
init_starter_contract,
|
|
7
|
+
load_baseline_file,
|
|
8
|
+
load_contract_file,
|
|
9
|
+
load_contract_from_yaml,
|
|
10
|
+
)
|
|
11
|
+
from repodna.contract.models import (
|
|
12
|
+
ArchitectureContract,
|
|
13
|
+
ContractEvaluationReport,
|
|
14
|
+
ContractMode,
|
|
15
|
+
ContractPolicy,
|
|
16
|
+
ContractRule,
|
|
17
|
+
ContractSeverity,
|
|
18
|
+
ContractUnknown,
|
|
19
|
+
ContractViolation,
|
|
20
|
+
UnknownBehavior,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"ArchitectureContract",
|
|
25
|
+
"ContractPolicy",
|
|
26
|
+
"ContractRule",
|
|
27
|
+
"ContractMode",
|
|
28
|
+
"ContractSeverity",
|
|
29
|
+
"UnknownBehavior",
|
|
30
|
+
"ContractViolation",
|
|
31
|
+
"ContractUnknown",
|
|
32
|
+
"ContractEvaluationReport",
|
|
33
|
+
"ContractEvaluator",
|
|
34
|
+
"load_contract_from_yaml",
|
|
35
|
+
"load_contract_file",
|
|
36
|
+
"find_contract_file",
|
|
37
|
+
"init_starter_contract",
|
|
38
|
+
"load_baseline_file",
|
|
39
|
+
]
|