depfix-ai 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. depfix/__init__.py +27 -0
  2. depfix/agent/__init__.py +5 -0
  3. depfix/agent/fix_agent.py +236 -0
  4. depfix/agent/scan_agent.py +1026 -0
  5. depfix/agent/scan_tools.py +395 -0
  6. depfix/agent/tools.py +86 -0
  7. depfix/api/__init__.py +1 -0
  8. depfix/apply/__init__.py +11 -0
  9. depfix/apply/models.py +87 -0
  10. depfix/apply/workspace.py +260 -0
  11. depfix/catalog/__init__.py +43 -0
  12. depfix/catalog/detections.py +256 -0
  13. depfix/catalog/learned.py +428 -0
  14. depfix/classify/__init__.py +39 -0
  15. depfix/classify/classifier.py +185 -0
  16. depfix/classify/llm.py +226 -0
  17. depfix/classify/models.py +33 -0
  18. depfix/classify/notes.py +197 -0
  19. depfix/classify/severity.py +5 -0
  20. depfix/classify/spec_rules.py +222 -0
  21. depfix/classify/store.py +194 -0
  22. depfix/classify/synthesize.py +115 -0
  23. depfix/classify/triage.py +133 -0
  24. depfix/classify/usage_candidates.py +307 -0
  25. depfix/cli.py +3144 -0
  26. depfix/clone/__init__.py +5 -0
  27. depfix/clone/service.py +285 -0
  28. depfix/codemods/__init__.py +52 -0
  29. depfix/codemods/base.py +81 -0
  30. depfix/codemods/config_literal.py +64 -0
  31. depfix/codemods/import_path.py +100 -0
  32. depfix/codemods/javascript.py +380 -0
  33. depfix/codemods/lockfile.py +644 -0
  34. depfix/codemods/registry.py +156 -0
  35. depfix/codemods/symbols.py +112 -0
  36. depfix/codemods/text.py +287 -0
  37. depfix/config.py +587 -0
  38. depfix/core/__init__.py +34 -0
  39. depfix/core/agent.py +239 -0
  40. depfix/core/explain.py +179 -0
  41. depfix/core/fix_service.py +837 -0
  42. depfix/core/models.py +309 -0
  43. depfix/core/pipeline.py +340 -0
  44. depfix/core/redaction.py +132 -0
  45. depfix/core/serde.py +61 -0
  46. depfix/core/shortcuts.py +448 -0
  47. depfix/core/upgrade.py +164 -0
  48. depfix/core/upgrade_service.py +286 -0
  49. depfix/defaults.py +98 -0
  50. depfix/doctor.py +432 -0
  51. depfix/ecosystems/__init__.py +39 -0
  52. depfix/ecosystems/base.py +169 -0
  53. depfix/ecosystems/callsites.py +246 -0
  54. depfix/ecosystems/go_lockfile.py +88 -0
  55. depfix/ecosystems/go_manifests.py +202 -0
  56. depfix/ecosystems/go_runtime.py +71 -0
  57. depfix/ecosystems/manifests.py +510 -0
  58. depfix/ecosystems/pypi_manifests.py +185 -0
  59. depfix/ecosystems/python_lockfile.py +85 -0
  60. depfix/ecosystems/python_runtime.py +133 -0
  61. depfix/ecosystems/registry.py +57 -0
  62. depfix/ecosystems/ruby_lockfile.py +41 -0
  63. depfix/ecosystems/ruby_manifests.py +107 -0
  64. depfix/ecosystems/ruby_runtime.py +106 -0
  65. depfix/ecosystems/ruby_validator.py +27 -0
  66. depfix/ecosystems/specs.py +320 -0
  67. depfix/ecosystems/symbol_index.py +239 -0
  68. depfix/evals/__init__.py +41 -0
  69. depfix/evals/loader.py +164 -0
  70. depfix/evals/models.py +160 -0
  71. depfix/evals/runner.py +278 -0
  72. depfix/evals/scoring.py +161 -0
  73. depfix/fixers/__init__.py +7 -0
  74. depfix/fixers/bedrock.py +251 -0
  75. depfix/fixers/gemini.py +313 -0
  76. depfix/fixers/ollama.py +242 -0
  77. depfix/gh/__init__.py +34 -0
  78. depfix/gh/app.py +394 -0
  79. depfix/gh/branch.py +191 -0
  80. depfix/gh/models.py +76 -0
  81. depfix/gh/pr.py +523 -0
  82. depfix/migrations/__init__.py +15 -0
  83. depfix/migrations/env.py +58 -0
  84. depfix/migrations/script.py.mako +28 -0
  85. depfix/migrations/versions/0001_baseline.py +298 -0
  86. depfix/migrations/versions/0002_change_attempt.py +51 -0
  87. depfix/migrations/versions/0003_change_event_body_url.py +27 -0
  88. depfix/migrations/versions/0004_fix_run_confidence.py +32 -0
  89. depfix/migrations/versions/0005_edit_provenance.py +37 -0
  90. depfix/migrations/versions/0006_pr_outcome.py +41 -0
  91. depfix/migrations/versions/0007_severity.py +29 -0
  92. depfix/migrations/versions/0008_repo_scan_change.py +54 -0
  93. depfix/migrations/versions/0009_fix_run_cost_stages.py +35 -0
  94. depfix/obs/__init__.py +8 -0
  95. depfix/obs/cost.py +109 -0
  96. depfix/obs/logging.py +123 -0
  97. depfix/obs/metrics.py +65 -0
  98. depfix/orchestrator/__init__.py +19 -0
  99. depfix/orchestrator/budget.py +55 -0
  100. depfix/orchestrator/grouping.py +132 -0
  101. depfix/orchestrator/models.py +176 -0
  102. depfix/orchestrator/plan.py +329 -0
  103. depfix/orchestrator/policy.py +249 -0
  104. depfix/orchestrator/reconcile.py +88 -0
  105. depfix/orchestrator/runner.py +2048 -0
  106. depfix/providers/__init__.py +12 -0
  107. depfix/providers/loader.py +131 -0
  108. depfix/providers/models.py +33 -0
  109. depfix/redaction.py +242 -0
  110. depfix/registry/__init__.py +31 -0
  111. depfix/registry/client.py +109 -0
  112. depfix/registry/models.py +26 -0
  113. depfix/registry/pypi_client.py +75 -0
  114. depfix/registry/pypi_models.py +15 -0
  115. depfix/registry/rubygems_client.py +73 -0
  116. depfix/repoconfig/__init__.py +21 -0
  117. depfix/repoconfig/loader.py +137 -0
  118. depfix/repoconfig/models.py +134 -0
  119. depfix/retry/__init__.py +11 -0
  120. depfix/retry/loop.py +178 -0
  121. depfix/scanners/__init__.py +90 -0
  122. depfix/scanners/alignment.py +239 -0
  123. depfix/scanners/applicability.py +131 -0
  124. depfix/scanners/base.py +145 -0
  125. depfix/scanners/callsites.py +767 -0
  126. depfix/scanners/drift_summary.py +109 -0
  127. depfix/scanners/judge.py +114 -0
  128. depfix/scanners/language.py +62 -0
  129. depfix/scanners/languages/__init__.py +0 -0
  130. depfix/scanners/languages/elixir.py +163 -0
  131. depfix/scanners/languages/go.py +208 -0
  132. depfix/scanners/languages/java.py +158 -0
  133. depfix/scanners/languages/kotlin.py +177 -0
  134. depfix/scanners/languages/php.py +180 -0
  135. depfix/scanners/languages/python.py +237 -0
  136. depfix/scanners/languages/ruby.py +130 -0
  137. depfix/scanners/limits.py +25 -0
  138. depfix/scanners/manifest.py +428 -0
  139. depfix/scanners/masking.py +141 -0
  140. depfix/scanners/matching.py +154 -0
  141. depfix/scanners/models.py +221 -0
  142. depfix/scanners/reachability.py +89 -0
  143. depfix/scanners/registry.py +135 -0
  144. depfix/scanners/removals.py +144 -0
  145. depfix/scanners/repo.py +846 -0
  146. depfix/scanners/report.py +69 -0
  147. depfix/scanners/severity.py +36 -0
  148. depfix/scanners/store.py +257 -0
  149. depfix/scanners/strategy.py +46 -0
  150. depfix/scanners/typeresolve.py +212 -0
  151. depfix/scanners/workspace.py +38 -0
  152. depfix/severity.py +48 -0
  153. depfix/sources/__init__.py +60 -0
  154. depfix/sources/asyncapi_spec.py +87 -0
  155. depfix/sources/base.py +46 -0
  156. depfix/sources/changelog_file.py +137 -0
  157. depfix/sources/changelog_html.py +102 -0
  158. depfix/sources/factory.py +146 -0
  159. depfix/sources/fixture_change.py +70 -0
  160. depfix/sources/github_release.py +118 -0
  161. depfix/sources/http.py +52 -0
  162. depfix/sources/models.py +235 -0
  163. depfix/sources/npm_dist_tag.py +95 -0
  164. depfix/sources/openapi_diff.py +586 -0
  165. depfix/sources/openapi_spec.py +54 -0
  166. depfix/sources/pypi_dist_tag.py +82 -0
  167. depfix/sources/redis_commands.py +76 -0
  168. depfix/sources/release_age.py +94 -0
  169. depfix/sources/release_notes.py +63 -0
  170. depfix/sources/repo_exports.py +224 -0
  171. depfix/sources/rss.py +140 -0
  172. depfix/sources/rubygems_dist_tag.py +74 -0
  173. depfix/sources/security_advisory.py +226 -0
  174. depfix/sources/semver.py +63 -0
  175. depfix/sources/smithy_spec.py +107 -0
  176. depfix/sources/spec_base.py +178 -0
  177. depfix/sources/ts_exports.py +218 -0
  178. depfix/storage/__init__.py +60 -0
  179. depfix/storage/attempt_store.py +125 -0
  180. depfix/storage/db.py +305 -0
  181. depfix/storage/fix_store.py +151 -0
  182. depfix/storage/lock.py +69 -0
  183. depfix/storage/schema.py +629 -0
  184. depfix/validators/__init__.py +50 -0
  185. depfix/validators/go.py +88 -0
  186. depfix/validators/javascript.py +201 -0
  187. depfix/validators/python.py +74 -0
  188. depfix/validators/ruby.py +90 -0
  189. depfix/validators/typescript.py +175 -0
  190. depfix/verify/__init__.py +58 -0
  191. depfix/verify/attribution.py +142 -0
  192. depfix/verify/characterize.py +422 -0
  193. depfix/verify/confidence.py +88 -0
  194. depfix/verify/contract.py +304 -0
  195. depfix/verify/coverage.py +210 -0
  196. depfix/verify/impact.py +406 -0
  197. depfix/verify/manager.py +458 -0
  198. depfix/verify/models.py +146 -0
  199. depfix/verify/parsers.py +356 -0
  200. depfix/verify/runner.py +397 -0
  201. depfix/verify/sandbox.py +191 -0
  202. depfix/verify/selection.py +235 -0
  203. depfix/verify/severity.py +20 -0
  204. depfix/verify/smoke.py +414 -0
  205. depfix/verify/static_check.py +226 -0
  206. depfix/verify/typecheck.py +237 -0
  207. depfix/verify/verifier.py +960 -0
  208. depfix/watcher/__init__.py +5 -0
  209. depfix/watcher/runner.py +478 -0
  210. depfix/workers/__init__.py +1 -0
  211. depfix_ai-0.2.0.dist-info/METADATA +207 -0
  212. depfix_ai-0.2.0.dist-info/RECORD +215 -0
  213. depfix_ai-0.2.0.dist-info/WHEEL +5 -0
  214. depfix_ai-0.2.0.dist-info/entry_points.txt +2 -0
  215. depfix_ai-0.2.0.dist-info/top_level.txt +1 -0
depfix/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """depfix — AI-powered fixer for breaking dependency changes."""
2
+
3
+ from depfix.core.agent import DependencyFixAgent
4
+ from depfix.core.models import (
5
+ AgentResult,
6
+ BreakingChange,
7
+ ChangeKind,
8
+ ClassificationSource,
9
+ FileUsage,
10
+ FixResult,
11
+ Usage,
12
+ ValidationResult,
13
+ )
14
+
15
+ __all__ = [
16
+ "AgentResult",
17
+ "BreakingChange",
18
+ "ChangeKind",
19
+ "ClassificationSource",
20
+ "DependencyFixAgent",
21
+ "FileUsage",
22
+ "FixResult",
23
+ "Usage",
24
+ "ValidationResult",
25
+ ]
26
+
27
+ __version__ = "0.2.0"
@@ -0,0 +1,5 @@
1
+ """Bounded, opt-in tool-assisted fix generation."""
2
+
3
+ from depfix.agent.fix_agent import FixAgent, make_fix_strategy
4
+
5
+ __all__ = ["FixAgent", "make_fix_strategy"]
@@ -0,0 +1,236 @@
1
+ """Bounded, test-grounded tool-assisted fix generation.
2
+
3
+ This strategy changes only how a candidate edit is produced. The existing
4
+ pipeline still validates it, verifies it against the target repository, and
5
+ decides whether it can be committed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import logging
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime
15
+ from typing import Any
16
+
17
+ import httpx
18
+
19
+ from depfix.agent.tools import FixToolset, ToolResult, tool_specs
20
+ from depfix.config import Settings
21
+ from depfix.core.models import BreakingChange, FileUsage, LLMCall
22
+ from depfix.fixers.gemini import FixGenerator
23
+ from depfix.fixers.ollama import OllamaFixGenerator
24
+ from depfix.redaction import redact_file_usage
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ @dataclass
30
+ class AgentTranscript:
31
+ tool_calls: list[tuple[str, str]] = field(default_factory=list)
32
+ steps_used: int = 0
33
+ stopped_reason: str = ""
34
+
35
+
36
+ class FixAgent:
37
+ """A drop-in fixer with at most ``max_steps`` checkout read operations."""
38
+
39
+ def __init__(self, completer: FixGenerator | OllamaFixGenerator, *, max_steps: int = 6) -> None:
40
+ self._completer = completer
41
+ self._max_steps = max_steps
42
+ self.llm_calls: list[LLMCall] = []
43
+ self.last_transcript: AgentTranscript | None = None
44
+
45
+ @property
46
+ def total_cost(self) -> float:
47
+ return sum(call.cost_estimate for call in self.llm_calls)
48
+
49
+ @property
50
+ def total_tokens(self) -> int:
51
+ return sum(call.total_tokens for call in self.llm_calls)
52
+
53
+ def generate_fix(
54
+ self,
55
+ file_usage: FileUsage,
56
+ breaking_change: BreakingChange,
57
+ *,
58
+ feedback: str | None = None,
59
+ toolset: FixToolset | None = None,
60
+ ) -> tuple[str, float, LLMCall]:
61
+ """Ask for bounded tool calls, then one complete replacement file."""
62
+ if toolset is None:
63
+ code, confidence, call = self._completer.generate_fix(
64
+ file_usage, breaking_change, feedback=feedback
65
+ )
66
+ self.llm_calls.append(call)
67
+ return code, confidence, call
68
+
69
+ # Build prompts from the redacted copy; restore secrets in the output.
70
+ safe_usage, redaction = redact_file_usage(file_usage)
71
+ safe_feedback = redaction.cover(feedback) if feedback else None
72
+
73
+ transcript = AgentTranscript()
74
+ self.last_transcript = transcript
75
+ context: list[str] = []
76
+ for step in range(self._max_steps):
77
+ transcript.steps_used = step + 1
78
+ response, call = self._complete(
79
+ self._prompt(safe_usage, breaking_change, safe_feedback, context, final=False)
80
+ )
81
+ parsed = self._json_response(response)
82
+ tool = parsed.get("tool")
83
+ if tool is None:
84
+ code = str(parsed.get("code", ""))
85
+ if code:
86
+ return self._proposal(
87
+ redaction.restore(code), file_usage, breaking_change, call
88
+ )
89
+ context.append(
90
+ "The previous response was invalid; return the required JSON object."
91
+ )
92
+ continue
93
+ result = self._dispatch(toolset, str(tool), parsed.get("arguments", {}))
94
+ transcript.tool_calls.append(
95
+ (str(tool), json.dumps(parsed.get("arguments", {}), sort_keys=True))
96
+ )
97
+ context.append(
98
+ f"TOOL {tool} RESULT (ok={result.ok}):\n{redaction.cover(result.content)}"
99
+ )
100
+ if self._is_stalling(toolset):
101
+ transcript.stopped_reason = "stall detected"
102
+ break
103
+ else:
104
+ transcript.stopped_reason = "max_steps reached"
105
+
106
+ response, call = self._complete(
107
+ self._prompt(safe_usage, breaking_change, safe_feedback, context, final=True)
108
+ )
109
+ code = self._json_response(response).get("code") # type: ignore[assignment]
110
+ if not isinstance(code, str) or not code:
111
+ raise RuntimeError("fix agent did not return a complete replacement file")
112
+ return self._proposal(redaction.restore(code), file_usage, breaking_change, call)
113
+
114
+ def _complete(self, prompt: str) -> tuple[str, LLMCall]:
115
+ """Complete one constrained JSON turn and account for its cost."""
116
+ started = time.time()
117
+ if isinstance(self._completer, FixGenerator):
118
+ model = self._completer.model
119
+ response = self._completer.client.models.generate_content(
120
+ model=model,
121
+ contents=prompt,
122
+ config={"temperature": self._completer.temperature},
123
+ )
124
+ try:
125
+ raw = response.text
126
+ except Exception:
127
+ candidates = getattr(response, "candidates", None) or []
128
+ parts = getattr(candidates[0].content, "parts", []) if candidates else []
129
+ raw = "".join(getattr(part, "text", "") for part in parts)
130
+ usage = getattr(response, "usage_metadata", None)
131
+ input_tokens = int(getattr(usage, "prompt_token_count", 0) or 0)
132
+ output_tokens = int(getattr(usage, "candidates_token_count", 0) or 0)
133
+ cost = self._completer._calculate_cost(input_tokens, output_tokens)
134
+ else:
135
+ model = self._completer.model
136
+ with httpx.Client(timeout=self._completer.timeout) as client:
137
+ response = client.post( # type: ignore[assignment]
138
+ f"{self._completer.base_url}/api/generate",
139
+ json={
140
+ "model": model,
141
+ "prompt": prompt,
142
+ "stream": False,
143
+ "format": "json",
144
+ "options": {"temperature": self._completer.temperature},
145
+ },
146
+ )
147
+ response.raise_for_status() # type: ignore[attr-defined]
148
+ data = response.json()
149
+ raw = str(data.get("response", "")) # type: ignore[attr-defined]
150
+ input_tokens = int(data.get("prompt_eval_count", 0) or 0) # type: ignore[attr-defined]
151
+ output_tokens = int(data.get("eval_count", 0) or 0) # type: ignore[attr-defined]
152
+ cost = 0.0
153
+ call = LLMCall(
154
+ timestamp=datetime.now(),
155
+ prompt=prompt,
156
+ response=raw, # type: ignore[arg-type]
157
+ model=model,
158
+ input_tokens=input_tokens,
159
+ output_tokens=output_tokens,
160
+ cost_estimate=cost,
161
+ duration_ms=int((time.time() - started) * 1000),
162
+ )
163
+ self.llm_calls.append(call)
164
+ return raw, call # type: ignore[return-value]
165
+
166
+ @staticmethod
167
+ def _json_response(response: str) -> dict[str, Any]:
168
+ try:
169
+ parsed = json.loads(response)
170
+ except json.JSONDecodeError:
171
+ return {}
172
+ return parsed if isinstance(parsed, dict) else {}
173
+
174
+ @staticmethod
175
+ def _dispatch(toolset: FixToolset, name: str, arguments: object) -> ToolResult:
176
+ args = arguments if isinstance(arguments, dict) else {}
177
+ if name == "read_file":
178
+ return toolset.read_file(str(args.get("relpath", "")))
179
+ if name == "find_usages":
180
+ return toolset.find_usages(str(args.get("symbol", "")))
181
+ return ToolResult.error(f"unknown tool: {name}")
182
+
183
+ @staticmethod
184
+ def _is_stalling(toolset: FixToolset) -> bool:
185
+ return len(toolset.call_log) != len(set(toolset.call_log))
186
+
187
+ def _proposal(
188
+ self, code: str, usage: FileUsage, change: BreakingChange, call: LLMCall
189
+ ) -> tuple[str, float, LLMCall]:
190
+ confidence = self._completer._calculate_confidence(
191
+ usage.file_content, code, usage.usages, change
192
+ )
193
+ return code, confidence, call
194
+
195
+ @staticmethod
196
+ def _prompt(
197
+ usage: FileUsage,
198
+ change: BreakingChange,
199
+ feedback: str | None,
200
+ context: list[str],
201
+ *,
202
+ final: bool,
203
+ ) -> str:
204
+ locations = "\n".join(
205
+ f"- line {item.line_number}: {item.line_content.strip()}" for item in usage.usages
206
+ )
207
+ mode = (
208
+ 'Return exactly {"tool": null, "code": "COMPLETE FILE"}.'
209
+ if final
210
+ else (
211
+ "Return exactly one JSON object: either a tool request like "
212
+ '{"tool":"read_file","arguments":{"relpath":"src/x.ts"}} or '
213
+ '{"tool":"find_usages","arguments":{"symbol":"client.method"}}, '
214
+ 'or {"tool":null,"code":"COMPLETE FILE"}.'
215
+ )
216
+ )
217
+ feedback_text = f"\nPrevious verification feedback:\n{feedback}" if feedback else ""
218
+ context_text = "\n\n".join(context) or "(no extra repository context)"
219
+ return f"""You are fixing one dependency migration.
220
+ Package: {change.package}; old API: {change.old_api}; new API: {change.new_api}
221
+ Migration guide: {change.migration_guide}
222
+ Target usages:\n{locations}
223
+ Current file ({usage.filepath}):\n{usage.file_content}
224
+ Read-only tools: {json.dumps(tool_specs())}
225
+ Collected context:\n{context_text}{feedback_text}
226
+ You may only request the listed tools. Preserve unrelated code.
227
+ Tokens of the form DEPFIX_REDACTED_<hex> stand for redacted secrets; copy each one through unchanged. {mode}"""
228
+
229
+
230
+ def make_fix_strategy(
231
+ settings: Settings, fixer: FixGenerator | OllamaFixGenerator
232
+ ) -> FixGenerator | OllamaFixGenerator | FixAgent:
233
+ """Return the configured strategy; single-shot remains the default."""
234
+ if settings.fix_strategy == "agent":
235
+ return FixAgent(fixer, max_steps=settings.fix_agent_max_steps)
236
+ return fixer