ai-driven-e2e 0.4.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 (49) hide show
  1. ai_driven_e2e-0.4.0.dist-info/METADATA +427 -0
  2. ai_driven_e2e-0.4.0.dist-info/RECORD +49 -0
  3. ai_driven_e2e-0.4.0.dist-info/WHEEL +4 -0
  4. ai_driven_e2e-0.4.0.dist-info/entry_points.txt +2 -0
  5. ai_driven_e2e-0.4.0.dist-info/licenses/LICENSE +21 -0
  6. app/__init__.py +1 -0
  7. app/cli.py +381 -0
  8. app/config.py +105 -0
  9. app/graph.py +86 -0
  10. app/llm.py +246 -0
  11. app/logging.py +22 -0
  12. app/nodes/__init__.py +1 -0
  13. app/nodes/diagnoser.py +28 -0
  14. app/nodes/patch_generator.py +43 -0
  15. app/nodes/reviewer.py +34 -0
  16. app/nodes/selector_verifier.py +75 -0
  17. app/nodes/shadow_verifier.py +106 -0
  18. app/nodes/test_runner.py +36 -0
  19. app/preprocess/__init__.py +1 -0
  20. app/preprocess/aria_snapshot.py +70 -0
  21. app/preprocess/diff_ast_analyzer.py +201 -0
  22. app/preprocess/error_log_parser.py +52 -0
  23. app/preprocess/failure_scanner.py +32 -0
  24. app/prompts/__init__.py +1 -0
  25. app/prompts/diagnoser.py +11 -0
  26. app/prompts/patch_generator.py +14 -0
  27. app/prompts/reviewer.py +18 -0
  28. app/runner.py +31 -0
  29. app/sandbox.py +130 -0
  30. app/schemas.py +99 -0
  31. app/shadow/__init__.py +69 -0
  32. app/shadow/config.py +47 -0
  33. app/shadow/context.py +30 -0
  34. app/shadow/in_memory_snapshot_store.py +36 -0
  35. app/shadow/injector.py +131 -0
  36. app/shadow/interfaces.py +158 -0
  37. app/shadow/matcher.py +94 -0
  38. app/shadow/normalizer.py +119 -0
  39. app/shadow/runtime.py +233 -0
  40. app/shadow/schemas.py +62 -0
  41. app/shadow/scoring.py +114 -0
  42. app/shadow/snapshot_store.py +106 -0
  43. app/shadow/trace_parser.py +266 -0
  44. app/shadow/workspace.py +104 -0
  45. app/state.py +23 -0
  46. app/utils/__init__.py +1 -0
  47. app/utils/files.py +24 -0
  48. app/verify/__init__.py +1 -0
  49. app/verify/selector_check.py +92 -0
app/cli.py ADDED
@@ -0,0 +1,381 @@
1
+ """CLI core: the single entry point for a repair run (also what CI invokes)."""
2
+
3
+ import difflib
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import structlog
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.syntax import Syntax
13
+ from rich.table import Table
14
+ from typer.core import TyperGroup
15
+
16
+ from app.config import settings
17
+ from app.graph import build_graph, build_review_graph
18
+ from app.logging import configure_logging
19
+ from app.preprocess.aria_snapshot import read_failure_snapshot
20
+ from app.preprocess.diff_ast_analyzer import analyze_diff
21
+ from app.preprocess.error_log_parser import parse_error_log
22
+ from app.preprocess.failure_scanner import scan_failing_tests
23
+ from app.runner import run_playwright
24
+ from app.sandbox import (
25
+ SandboxViolation,
26
+ assert_command_allowed,
27
+ assert_read_allowed,
28
+ assert_write_allowed,
29
+ )
30
+ from app.schemas import (
31
+ PatchInstruction,
32
+ RepairSummary,
33
+ ReviewFinding,
34
+ ReviewReport,
35
+ SuiteSummary,
36
+ )
37
+ from app.shadow.runtime import run_shadow
38
+ from app.state import AgentState
39
+ from app.utils.files import atomic_write
40
+
41
+
42
+ class _DefaultCommandGroup(TyperGroup):
43
+ """Route a bare invocation to ``heal`` so ``e2e-healer <path>`` keeps working.
44
+
45
+ Adding the ``review`` subcommand would otherwise force every caller (and the shipped
46
+ action.yml) to spell out ``heal``; instead we inject ``heal`` whenever the first token
47
+ is not a known command or option. Explicit ``heal``/``review`` still route normally.
48
+ """
49
+
50
+ default_command = "heal"
51
+
52
+ def parse_args(self, ctx, args): # types inherited from TyperGroup
53
+ # Inject "heal" for a bare run or a leading non-command token (a test path), so
54
+ # `e2e-healer` and `e2e-healer <path>` still work; leave explicit commands/options.
55
+ if not args or (args[0] not in self.commands and not args[0].startswith("-")):
56
+ args = [self.default_command, *args]
57
+ return super().parse_args(ctx, args)
58
+
59
+
60
+ app = typer.Typer(
61
+ help="AI-driven E2E test self-healing engine", cls=_DefaultCommandGroup, no_args_is_help=False
62
+ )
63
+ console = Console(stderr=True) # human output on stderr; JSON summary on stdout
64
+ logger = structlog.get_logger(__name__)
65
+
66
+
67
+ @app.callback(invoke_without_command=True)
68
+ def main(
69
+ shadow: bool = typer.Option(
70
+ False, "--shadow", help="run the Shadow Testing runtime (under development)"
71
+ ),
72
+ ) -> None:
73
+ """AI-driven E2E test self-healing engine.
74
+
75
+ Runs the repair loop by default (see ``heal``); ``--shadow`` routes into the
76
+ upcoming Shadow Testing runtime instead. Existing behavior is unchanged when
77
+ the flag is absent.
78
+ """
79
+ if not shadow:
80
+ return
81
+ configure_logging(settings.log_level)
82
+ logger.info("shadow_mode_invoked")
83
+ from app.shadow.schemas import ShadowRunResult
84
+
85
+ result = run_shadow()
86
+ if isinstance(result, ShadowRunResult):
87
+ status = "passed" if result.is_success else "failed"
88
+ renderable = (
89
+ f"[bold]{status}[/bold] | matched={result.matched_count} "
90
+ f"missed={result.missed_count} score={result.score:.2f}"
91
+ )
92
+ else:
93
+ renderable = result
94
+ console.print(Panel(renderable, title="Shadow Testing", border_style="yellow"))
95
+ raise typer.Exit(code=0)
96
+
97
+
98
+ def _read_diff(diff_file: Optional[Path], diff_base: Optional[str]) -> str:
99
+ """Return the git diff from a file, else `git diff [base...HEAD]`.
100
+
101
+ ``diff_base`` (e.g. a PR base ref) scopes the diff to `base...HEAD`, which is what
102
+ the CI/PR path needs; without it we fall back to the working-tree `git diff`.
103
+ """
104
+ if diff_file is not None:
105
+ assert_read_allowed(diff_file)
106
+ return diff_file.read_text()
107
+ cmd = ["git", "diff", f"{diff_base}...HEAD"] if diff_base else ["git", "diff"]
108
+ assert_command_allowed(cmd, reason="git_diff")
109
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
110
+ return result.stdout
111
+
112
+
113
+ def _render_diff(original: str, patched: str, path: str) -> None:
114
+ """Print a unified diff of the applied changes to the console (stderr)."""
115
+ text = "".join(
116
+ difflib.unified_diff(
117
+ original.splitlines(keepends=True),
118
+ patched.splitlines(keepends=True),
119
+ fromfile=f"a/{path}",
120
+ tofile=f"b/{path}",
121
+ )
122
+ )
123
+ console.print(Syntax(text, "diff", theme="ansi_dark") if text else "[dim]no changes[/dim]")
124
+
125
+
126
+ def _heal_file(
127
+ test_path: Path, raw_log: str, dom_diff_context: list[dict], dry_run: bool
128
+ ) -> RepairSummary:
129
+ """Run the repair graph on one test file and return its machine-readable summary.
130
+
131
+ Restores the original on failure or in dry-run mode; the diff is rendered to stderr.
132
+ """
133
+ assert_read_allowed(test_path)
134
+ assert_write_allowed(test_path, reason="repair_target")
135
+ original_code = test_path.read_text()
136
+ initial_state: AgentState = {
137
+ "test_script_path": str(test_path),
138
+ "original_code": original_code,
139
+ "current_code": original_code,
140
+ "error_log": parse_error_log(raw_log),
141
+ "dom_diff_context": dom_diff_context,
142
+ "dom_snapshot": read_failure_snapshot(Path(settings.test_results_dir)),
143
+ "analysis_report": "",
144
+ "patch_instructions": {},
145
+ "verification_report": {},
146
+ "review_report": {},
147
+ "loop_count": 0,
148
+ "is_success": False,
149
+ }
150
+
151
+ logger.info("repair_run_started", test_script_path=str(test_path))
152
+ final_state = build_graph().invoke(initial_state)
153
+
154
+ if dry_run or not final_state["is_success"]:
155
+ atomic_write(test_path, original_code)
156
+
157
+ _render_diff(original_code, final_state["current_code"], str(test_path))
158
+
159
+ instructions = final_state["patch_instructions"] or {}
160
+ summary = RepairSummary(
161
+ test_script_path=final_state["test_script_path"],
162
+ is_success=final_state["is_success"],
163
+ loop_count=final_state["loop_count"],
164
+ instructions=[PatchInstruction(**i) for i in instructions.get("instructions", [])],
165
+ )
166
+ logger.info("repair_run_finished", is_success=summary.is_success, loop_count=summary.loop_count)
167
+ return summary
168
+
169
+
170
+ def _heal_suite(suite_target: str, dom_diff_context: list[dict], dry_run: bool) -> SuiteSummary:
171
+ """Run the whole suite (or a directory), then heal each failing test file.
172
+
173
+ ``suite_target`` empty means the whole suite. A per-file re-run gives each file a
174
+ focused failure log before healing; files that pass on re-run are recorded as fixed.
175
+ """
176
+ passed, raw_log = run_playwright(suite_target)
177
+ if passed:
178
+ return SuiteSummary(total_failed=0, healed=0, is_success=True)
179
+
180
+ results: list[RepairSummary] = []
181
+ for rel in scan_failing_tests(raw_log):
182
+ path = Path(rel)
183
+ try:
184
+ assert_read_allowed(path)
185
+ assert_write_allowed(path, reason="suite_repair_target")
186
+ except SandboxViolation as exc:
187
+ logger.warning("failing_test_sandbox_denied", path=rel, error=str(exc))
188
+ continue
189
+ if not path.exists():
190
+ logger.warning("failing_test_not_found", path=rel)
191
+ continue
192
+ rerun_passed, focused_log = run_playwright(rel)
193
+ if rerun_passed: # flaky or already fixed by an earlier file's patch
194
+ results.append(RepairSummary(test_script_path=rel, is_success=True, loop_count=0))
195
+ continue
196
+ results.append(_heal_file(path, focused_log, dom_diff_context, dry_run))
197
+
198
+ healed = sum(1 for r in results if r.is_success)
199
+ return SuiteSummary(
200
+ total_failed=len(results),
201
+ healed=healed,
202
+ is_success=len(results) > 0 and healed == len(results),
203
+ results=results,
204
+ )
205
+
206
+
207
+ def _review_file(test_path: Path, raw_log: str, dom_diff_context: list[dict]) -> ReviewReport:
208
+ """Run the review graph on one test file and return its findings. Never writes the file."""
209
+ assert_read_allowed(test_path)
210
+ current_code = test_path.read_text()
211
+ initial_state: AgentState = {
212
+ "test_script_path": str(test_path),
213
+ "original_code": current_code,
214
+ "current_code": current_code,
215
+ "error_log": parse_error_log(raw_log),
216
+ "dom_diff_context": dom_diff_context,
217
+ "dom_snapshot": read_failure_snapshot(Path(settings.test_results_dir)),
218
+ "analysis_report": "",
219
+ "patch_instructions": {},
220
+ "verification_report": {},
221
+ "review_report": {},
222
+ "loop_count": 0,
223
+ "is_success": False,
224
+ }
225
+
226
+ logger.info("review_run_started", test_script_path=str(test_path))
227
+ final_state = build_review_graph().invoke(initial_state)
228
+
229
+ findings = [ReviewFinding(**f) for f in final_state["review_report"].get("findings", [])]
230
+ report = ReviewReport(
231
+ test_script_path=str(test_path), findings=findings, has_findings=len(findings) > 0
232
+ )
233
+ logger.info("review_run_finished", finding_count=len(findings))
234
+ return report
235
+
236
+
237
+ def _render_findings(report: ReviewReport) -> None:
238
+ """Print the review findings as a rich table to the console (stderr)."""
239
+ if not report.findings:
240
+ console.print("[dim]no findings[/dim]")
241
+ return
242
+ table = Table(title="Source-level review findings", show_lines=True)
243
+ table.add_column("File:Line", style="cyan", no_wrap=True)
244
+ table.add_column("Root cause")
245
+ table.add_column("Suggestion")
246
+ table.add_column("Recommended selector", style="green")
247
+ for finding in report.findings:
248
+ table.add_row(
249
+ f"{finding.file}:{finding.line}",
250
+ finding.root_cause,
251
+ finding.suggestion,
252
+ finding.recommended_selector,
253
+ )
254
+ console.print(table)
255
+
256
+
257
+ @app.command()
258
+ def heal(
259
+ test_path: Optional[Path] = typer.Argument(
260
+ None, help="failing test file; a directory or omitting it heals the whole suite"
261
+ ),
262
+ log_file: Optional[Path] = typer.Option(
263
+ None, "--log", help="raw Playwright failure log (single-file mode); else the test is run"
264
+ ),
265
+ diff_file: Optional[Path] = typer.Option(
266
+ None, "--diff", help="git diff file; defaults to `git diff`"
267
+ ),
268
+ diff_base: Optional[str] = typer.Option(
269
+ None, "--diff-base", help="git ref to diff against as base...HEAD (e.g. a PR base)"
270
+ ),
271
+ dry_run: bool = typer.Option(
272
+ False, "--dry-run", help="run the loop but restore the original file; write nothing"
273
+ ),
274
+ app_url: Optional[str] = typer.Option(
275
+ None, "--app-url", help="URL the Selector Verifier loads to check patched selectors"
276
+ ),
277
+ json_output: bool = typer.Option(False, "--json", help="emit JSON summary to stdout"),
278
+ ) -> None:
279
+ """Repair a failing test (or the whole suite). Exit 0 if everything is fixed, else non-zero."""
280
+ configure_logging(settings.log_level)
281
+ try:
282
+ if app_url is not None:
283
+ settings.app_url = app_url # CLI flag overrides the E2E_HEALER_APP_URL setting
284
+ if test_path is not None:
285
+ assert_read_allowed(test_path)
286
+ if not test_path.exists():
287
+ console.print(f"[red]path not found:[/red] {test_path}")
288
+ raise typer.Exit(code=2)
289
+
290
+ dom_diff_context = [d.model_dump() for d in analyze_diff(_read_diff(diff_file, diff_base))]
291
+
292
+ # Single-file mode: an existing file path.
293
+ if test_path is not None and test_path.is_file():
294
+ assert_write_allowed(test_path, reason="repair_target")
295
+ if log_file is not None:
296
+ assert_read_allowed(log_file)
297
+ raw_log = log_file.read_text()
298
+ else:
299
+ passed, raw_log = run_playwright(str(test_path))
300
+ if passed:
301
+ console.print("[green]test already passes[/green] — nothing to heal")
302
+ raise typer.Exit(code=0)
303
+ summary = _heal_file(test_path, raw_log, dom_diff_context, dry_run)
304
+ if json_output:
305
+ typer.echo(summary.model_dump_json())
306
+ status = "fixed" if summary.is_success else "not fixed"
307
+ console.print(f"[bold]{status}[/bold] after {summary.loop_count} loop(s)")
308
+ raise typer.Exit(code=0 if summary.is_success else 1)
309
+
310
+ # Suite mode: no path or a directory.
311
+ suite = _heal_suite(
312
+ str(test_path) if test_path is not None else "", dom_diff_context, dry_run
313
+ )
314
+ if suite.total_failed == 0 and suite.is_success:
315
+ console.print("[green]suite passes[/green] — nothing to heal")
316
+ raise typer.Exit(code=0)
317
+ if suite.total_failed == 0:
318
+ console.print("[yellow]suite failed but no test files could be parsed/found[/yellow]")
319
+ raise typer.Exit(code=1)
320
+ if json_output:
321
+ typer.echo(suite.model_dump_json())
322
+ console.print(f"[bold]{suite.healed}/{suite.total_failed}[/bold] test(s) healed")
323
+ raise typer.Exit(code=0 if suite.is_success else 1)
324
+ except SandboxViolation as exc:
325
+ console.print(f"[red]sandbox denied:[/red] {exc}")
326
+ raise typer.Exit(code=2) from exc
327
+
328
+
329
+ @app.command()
330
+ def review(
331
+ test_path: Path = typer.Argument(..., help="failing test file to review (never modified)"),
332
+ log_file: Optional[Path] = typer.Option(
333
+ None, "--log", help="raw Playwright failure log; else the test is run to produce one"
334
+ ),
335
+ diff_file: Optional[Path] = typer.Option(
336
+ None, "--diff", help="git diff file; defaults to `git diff`"
337
+ ),
338
+ diff_base: Optional[str] = typer.Option(
339
+ None, "--diff-base", help="git ref to diff against as base...HEAD (e.g. a PR base)"
340
+ ),
341
+ json_output: bool = typer.Option(
342
+ False, "--json", help="emit the ReviewReport JSON to stdout for the CI wrapper"
343
+ ),
344
+ ) -> None:
345
+ """Review a failing test and suggest source-level fixes as PR comments — never edits it.
346
+
347
+ Unlike ``heal``, this diagnoses the root cause and advises how to fix the *source*
348
+ (prefer accessible roles / a stable data-testid). Always exits 0 on a completed review;
349
+ the CI wrapper branches on ``has_findings`` in the JSON.
350
+ """
351
+ configure_logging(settings.log_level)
352
+ try:
353
+ assert_read_allowed(test_path)
354
+ if not test_path.exists():
355
+ console.print(f"[red]path not found:[/red] {test_path}")
356
+ raise typer.Exit(code=2)
357
+
358
+ dom_diff_context = [d.model_dump() for d in analyze_diff(_read_diff(diff_file, diff_base))]
359
+
360
+ if log_file is not None:
361
+ assert_read_allowed(log_file)
362
+ raw_log = log_file.read_text()
363
+ else:
364
+ passed, raw_log = run_playwright(str(test_path))
365
+ if passed:
366
+ console.print("[green]test passes[/green] — nothing to review")
367
+ raise typer.Exit(code=0)
368
+
369
+ report = _review_file(test_path, raw_log, dom_diff_context)
370
+ if json_output:
371
+ typer.echo(report.model_dump_json())
372
+ _render_findings(report)
373
+ console.print(f"[bold]{len(report.findings)}[/bold] source-level suggestion(s)")
374
+ raise typer.Exit(code=0)
375
+ except SandboxViolation as exc:
376
+ console.print(f"[red]sandbox denied:[/red] {exc}")
377
+ raise typer.Exit(code=2) from exc
378
+
379
+
380
+ if __name__ == "__main__":
381
+ app()
app/config.py ADDED
@@ -0,0 +1,105 @@
1
+ """Type-safe configuration via Pydantic Settings."""
2
+
3
+ from typing import Literal
4
+
5
+ from pydantic import Field, model_validator
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+ LLMProvider = Literal["nvidia", "openai", "anthropic", "ollama"]
9
+
10
+
11
+ class Settings(BaseSettings):
12
+ model_config = SettingsConfigDict(env_prefix="E2E_HEALER_", env_file=".env", extra="ignore")
13
+
14
+ # Provider-neutral LLM configuration. `llm_provider` selects the backend; the generic
15
+ # `llm_*` fields are what every provider client reads. The legacy `nvidia_*` fields below
16
+ # are mapped onto the generic ones when provider=nvidia (see _map_legacy_nvidia_fields), so
17
+ # existing NVIDIA-only setups keep working without touching the new variables.
18
+ llm_provider: LLMProvider = Field(
19
+ default="nvidia", description="LLM backend: nvidia | openai | anthropic | ollama"
20
+ )
21
+ llm_api_key: str = Field(default="", description="API key for the selected provider")
22
+ llm_base_url: str = Field(
23
+ default="", description="OpenAI-compatible endpoint (empty = provider SDK default)"
24
+ )
25
+ llm_model: str = Field(default="", description="Structured-Outputs-capable model")
26
+ llm_max_tokens: int = Field(
27
+ default=4096, description="completion token cap (reasoning models need headroom)"
28
+ )
29
+
30
+ # Legacy NVIDIA-specific fields, kept for backward compatibility. Prefer the generic
31
+ # llm_* fields above; these are folded into them when llm_provider is "nvidia".
32
+ nvidia_api_key: str = Field(default="", description="NVIDIA NIM API key (legacy)")
33
+ nvidia_base_url: str = Field(
34
+ default="https://integrate.api.nvidia.com/v1",
35
+ description="NVIDIA OpenAI-compatible endpoint (legacy)",
36
+ )
37
+ nvidia_model: str = Field(
38
+ default="openai/gpt-oss-120b", description="Structured-Outputs-capable model (legacy)"
39
+ )
40
+ nvidia_max_tokens: int = Field(default=4096, description="completion token cap (legacy)")
41
+ max_loops: int = Field(default=3, description="repair loop cap (Router termination)")
42
+ playwright_cmd: str = Field(default="npx playwright test", description="Playwright invocation")
43
+ verify_selectors: bool = Field(
44
+ default=True, description="verify patched selectors against the live DOM before re-running"
45
+ )
46
+ app_url: str = Field(
47
+ default="", description="URL the Selector Verifier loads to check candidate selectors"
48
+ )
49
+ node_cmd: str = Field(
50
+ default="node", description="Node.js executable for the selector verifier"
51
+ )
52
+ test_results_dir: str = Field(
53
+ default="test-results",
54
+ description="Playwright output dir holding error-context.md failure snapshots",
55
+ )
56
+ sandbox_mode: str = Field(
57
+ default="relaxed",
58
+ description="sandbox mode: strict, relaxed, or off",
59
+ )
60
+ workspace_root: str = Field(
61
+ default=".",
62
+ description="root directory for strict sandbox path checks",
63
+ )
64
+ write_globs: str = Field(
65
+ default="*.spec.js,*.spec.jsx,*.spec.ts,*.spec.tsx,"
66
+ "*.test.js,*.test.jsx,*.test.ts,*.test.tsx,"
67
+ "**/*.spec.js,**/*.spec.jsx,**/*.spec.ts,**/*.spec.tsx,"
68
+ "**/*.test.js,**/*.test.jsx,**/*.test.ts,**/*.test.tsx",
69
+ description="comma-separated writable test-file globs",
70
+ )
71
+ deny_globs: str = Field(
72
+ default=".env,.env.*,**/.env,**/.env.*,.git/**,.github/**,"
73
+ "node_modules/**,.venv/**,uv.lock,package-lock.json,pnpm-lock.yaml,yarn.lock",
74
+ description="comma-separated path globs denied by the sandbox",
75
+ )
76
+ allow_temp_helper: bool = Field(
77
+ default=True,
78
+ description="allow the temporary selector verifier helper file",
79
+ )
80
+ log_level: str = Field(default="INFO")
81
+
82
+ @model_validator(mode="after")
83
+ def _map_legacy_nvidia_fields(self) -> "Settings":
84
+ """Fold legacy nvidia_* values into the generic llm_* fields for provider=nvidia.
85
+
86
+ Only fields the user did not set explicitly are back-filled, so an explicit
87
+ llm_* override always wins over the legacy default. This keeps existing
88
+ E2E_HEALER_NVIDIA_* setups working unchanged while the generic fields become the
89
+ single source of truth every provider client reads.
90
+ """
91
+ if self.llm_provider != "nvidia":
92
+ return self
93
+ explicit = self.model_fields_set
94
+ if "llm_api_key" not in explicit and self.nvidia_api_key:
95
+ self.llm_api_key = self.nvidia_api_key
96
+ if "llm_base_url" not in explicit:
97
+ self.llm_base_url = self.nvidia_base_url
98
+ if "llm_model" not in explicit:
99
+ self.llm_model = self.nvidia_model
100
+ if "llm_max_tokens" not in explicit and "nvidia_max_tokens" in explicit:
101
+ self.llm_max_tokens = self.nvidia_max_tokens
102
+ return self
103
+
104
+
105
+ settings = Settings()
app/graph.py ADDED
@@ -0,0 +1,86 @@
1
+ """Assemble the repair StateGraph and its conditional Router edge."""
2
+
3
+ from langgraph.graph import END, START, StateGraph
4
+
5
+ from app.config import settings
6
+ from app.nodes.diagnoser import diagnoser
7
+ from app.nodes.patch_generator import patch_generator
8
+ from app.nodes.reviewer import reviewer
9
+ from app.nodes.selector_verifier import selector_verifier
10
+ from app.nodes.shadow_verifier import shadow_verifier
11
+ from app.nodes.test_runner import test_runner
12
+ from app.state import AgentState
13
+
14
+
15
+ def route(state: AgentState) -> str:
16
+ """Conditional edge: end on success or when the loop cap is hit, else re-diagnose."""
17
+ if state["is_success"] or state["loop_count"] >= settings.max_loops:
18
+ return END
19
+ return "diagnoser"
20
+
21
+
22
+ def route_after_shadow(state: AgentState) -> str:
23
+ """After shadow replay: proceed to live selector verifier on a pass/skip, else re-patch (or end at cap)."""
24
+ report = state.get("shadow_report", {})
25
+ if report.get("ok", True):
26
+ return "selector_verifier"
27
+ if state["loop_count"] >= settings.max_loops:
28
+ return END
29
+ return "patch_generator"
30
+
31
+
32
+ def route_after_verify(state: AgentState) -> str:
33
+ """After verification: run the test if selectors hold, else re-patch (or end at cap).
34
+
35
+ Shares the loop cap with ``route`` so the loop count stays the single termination
36
+ budget; a rejected patch re-enters the Patch Generator rather than wasting a test run.
37
+ """
38
+ if state["verification_report"].get("ok", True):
39
+ return "test_runner"
40
+ if state["loop_count"] >= settings.max_loops:
41
+ return END
42
+ return "patch_generator"
43
+
44
+
45
+ def build_graph():
46
+ """Build and compile the Diagnoser → Patch Generator → Shadow Verifier → Selector Verifier → Test Runner loop."""
47
+ graph = StateGraph(AgentState)
48
+ graph.add_node("diagnoser", diagnoser)
49
+ graph.add_node("patch_generator", patch_generator)
50
+ graph.add_node("shadow_verifier", shadow_verifier)
51
+ graph.add_node("selector_verifier", selector_verifier)
52
+ graph.add_node("test_runner", test_runner)
53
+
54
+ graph.add_edge(START, "diagnoser")
55
+ graph.add_edge("diagnoser", "patch_generator")
56
+ graph.add_edge("patch_generator", "shadow_verifier")
57
+ graph.add_conditional_edges(
58
+ "shadow_verifier",
59
+ route_after_shadow,
60
+ {"selector_verifier": "selector_verifier", "patch_generator": "patch_generator", END: END},
61
+ )
62
+ graph.add_conditional_edges(
63
+ "selector_verifier",
64
+ route_after_verify,
65
+ {"test_runner": "test_runner", "patch_generator": "patch_generator", END: END},
66
+ )
67
+ graph.add_conditional_edges("test_runner", route, {"diagnoser": "diagnoser", END: END})
68
+
69
+ return graph.compile()
70
+
71
+
72
+ def build_review_graph():
73
+ """Build the review-mode graph: Diagnoser → Reviewer → END.
74
+
75
+ Reuses the Diagnoser to infer the root cause, then advises a source-level fix. No patch,
76
+ verify, test-run, or loop — review mode is strictly read-only and advisory.
77
+ """
78
+ graph = StateGraph(AgentState)
79
+ graph.add_node("diagnoser", diagnoser)
80
+ graph.add_node("reviewer", reviewer)
81
+
82
+ graph.add_edge(START, "diagnoser")
83
+ graph.add_edge("diagnoser", "reviewer")
84
+ graph.add_edge("reviewer", END)
85
+
86
+ return graph.compile()