fusiontest 0.2.48__tar.gz → 0.2.53__tar.gz

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 (77) hide show
  1. {fusiontest-0.2.48 → fusiontest-0.2.53}/PKG-INFO +2 -1
  2. {fusiontest-0.2.48 → fusiontest-0.2.53}/README.md +1 -0
  3. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/cli.py +131 -6
  4. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/action_model.py +4 -1
  5. fusiontest-0.2.53/fusiontest/core/evidence.py +164 -0
  6. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/reproduce.py +1 -0
  7. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/runner.py +58 -12
  8. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/secrets.py +12 -0
  9. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/desktop/playwright_adapter.py +166 -3
  10. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/discovery/goal_generator.py +8 -3
  11. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/discovery/intent.py +7 -4
  12. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/PKG-INFO +2 -1
  13. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/SOURCES.txt +1 -0
  14. {fusiontest-0.2.48 → fusiontest-0.2.53}/pyproject.toml +1 -1
  15. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/__init__.py +0 -0
  16. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/agent/__init__.py +0 -0
  17. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/agent/mcp_server.py +0 -0
  18. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/agent/verify.py +0 -0
  19. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/__init__.py +0 -0
  20. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/security.py +0 -0
  21. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/sites/shop/bugs.js +0 -0
  22. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/sites/shop/help.html +0 -0
  23. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/sites/shop/index.html +0 -0
  24. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/billing-security-spa.yaml +0 -0
  25. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/billing-security.yaml +0 -0
  26. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/diffs/order-retry.diff +0 -0
  27. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/diffs/sale-banner.diff +0 -0
  28. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/diffs/stock-check.diff +0 -0
  29. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/shop-bugs.yaml +0 -0
  30. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/shop-hard.yaml +0 -0
  31. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/shop-intent.yaml +0 -0
  32. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/shop.yaml +0 -0
  33. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/bench/suites/todomvc.yaml +0 -0
  34. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/__init__.py +0 -0
  35. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/app_errors.py +0 -0
  36. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/bugs.py +0 -0
  37. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/goal_verifier.py +0 -0
  38. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/netguard.py +0 -0
  39. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/promise_checker.py +0 -0
  40. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/replay.py +0 -0
  41. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/screen_parser.py +0 -0
  42. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/shared_traces.py +0 -0
  43. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/core/tokens.py +0 -0
  44. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/__init__.py +0 -0
  45. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/fusiontest_dashboard.yaml +0 -0
  46. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/github.yaml +0 -0
  47. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/hacker_news.yaml +0 -0
  48. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/httpbin.yaml +0 -0
  49. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/todomvc.yaml +0 -0
  50. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/demos/wikipedia.yaml +0 -0
  51. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/desktop/__init__.py +0 -0
  52. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/desktop/macos_adapter.py +0 -0
  53. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/desktop/windows_adapter.py +0 -0
  54. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/discovery/__init__.py +0 -0
  55. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/guardrails/__init__.py +0 -0
  56. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/guardrails/engine.py +0 -0
  57. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/mobile/__init__.py +0 -0
  58. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/mobile/android_adapter.py +0 -0
  59. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/mobile/ios_adapter.py +0 -0
  60. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/reporting/__init__.py +0 -0
  61. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/reporting/reporter.py +0 -0
  62. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/__init__.py +0 -0
  63. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/browser_auth.py +0 -0
  64. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/checks.py +0 -0
  65. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/config.py +0 -0
  66. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/engine.py +0 -0
  67. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/security/findings.py +0 -0
  68. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/training/__init__.py +0 -0
  69. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/training/data_collector.py +0 -0
  70. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/training/dataset_builder.py +0 -0
  71. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest/training/trainer.py +0 -0
  72. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/dependency_links.txt +0 -0
  73. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/entry_points.txt +0 -0
  74. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/not-zip-safe +0 -0
  75. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/requires.txt +0 -0
  76. {fusiontest-0.2.48 → fusiontest-0.2.53}/fusiontest.egg-info/top_level.txt +0 -0
  77. {fusiontest-0.2.48 → fusiontest-0.2.53}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fusiontest
3
- Version: 0.2.48
3
+ Version: 0.2.53
4
4
  Summary: AI-powered UI testing for mobile and desktop — by FusionLeap.io
5
5
  Author-email: FusionLeap <hello@fusionleap.io>
6
6
  License: MIT
@@ -108,6 +108,7 @@ what passes as regression goals. See [docs/coding-agents.md](docs/coding-agents.
108
108
  | Multi-provider LLMs | Groq, Claude, Gemini, OpenAI or local Ollama, with automatic fallback |
109
109
  | Safe secrets | `{{PASSWORD}}` placeholders — the AI never sees values, which are only typed on allowed sites |
110
110
  | Guardrails | Invalid-action checks, loop detection, backtracking, no-progress detection |
111
+ | Run evidence | Web & Electron: a video of the run, a Playwright trace per failed goal, and console and network errors, in the report and the dashboard |
111
112
  | Reporting | JSON reports, dashboard uploads, failure screenshots, Slack, GitHub Actions annotations, webhooks |
112
113
  | Platforms | Web (Playwright), Electron, Android & iOS (Appium), Windows, macOS |
113
114
 
@@ -27,6 +27,7 @@ what passes as regression goals. See [docs/coding-agents.md](docs/coding-agents.
27
27
  | Multi-provider LLMs | Groq, Claude, Gemini, OpenAI or local Ollama, with automatic fallback |
28
28
  | Safe secrets | `{{PASSWORD}}` placeholders — the AI never sees values, which are only typed on allowed sites |
29
29
  | Guardrails | Invalid-action checks, loop detection, backtracking, no-progress detection |
30
+ | Run evidence | Web & Electron: a video of the run, a Playwright trace per failed goal, and console and network errors, in the report and the dashboard |
30
31
  | Reporting | JSON reports, dashboard uploads, failure screenshots, Slack, GitHub Actions annotations, webhooks |
31
32
  | Platforms | Web (Playwright), Electron, Android & iOS (Appium), Windows, macOS |
32
33
 
@@ -13,6 +13,7 @@ Commands:
13
13
  from __future__ import annotations
14
14
 
15
15
  import json
16
+ import shutil
16
17
  import sys
17
18
  import time
18
19
  from pathlib import Path
@@ -26,6 +27,7 @@ from rich.progress import Progress, SpinnerColumn, TextColumn
26
27
  from rich.table import Table
27
28
 
28
29
  from fusiontest import __version__
30
+ from fusiontest.core import evidence as _evidence
29
31
 
30
32
  console = Console()
31
33
 
@@ -33,6 +35,7 @@ console = Console()
33
35
  # safe to commit or cache in CI so later runs can replay.
34
36
  DEFAULT_TRACE_DIR = ".fusiontest/traces"
35
37
  DEFAULT_SCREENSHOT_DIR = ".fusiontest/screenshots"
38
+ DEFAULT_EVIDENCE_DIR = ".fusiontest/evidence"
36
39
 
37
40
 
38
41
  @click.group()
@@ -86,8 +89,11 @@ def _judge_note(backend: str, judge: str) -> str:
86
89
  @click.option("--judge", type=click.Choice(["gpt4o", "claude", "gemini", "groq", "ollama"]),
87
90
  default=None, help="Model that judges pass/fail (default: FUSIONTEST_JUDGE, else "
88
91
  "Claude or OpenAI when its key is set, else --backend)")
92
+ @click.option("--evidence", "evidence_mode", type=click.Choice(["failures", "all", "off"]), default=None,
93
+ help="Web and Electron: record a video of the run, a trace per goal, and console and "
94
+ "network errors. 'failures' (default) keeps the video and traces only for what failed")
89
95
  def run(goal, goal_file, platform, app, url, locale, backend, headless, output, config_file,
90
- replay, trace_dir, reverify_every, deploy, judge):
96
+ replay, trace_dir, reverify_every, deploy, judge, evidence_mode):
91
97
  """Run a FusionTest test — provide goals via --goal or --file."""
92
98
 
93
99
  _load_env()
@@ -142,8 +148,20 @@ def run(goal, goal_file, platform, app, url, locale, backend, headless, output,
142
148
  + _judge_note(backend, judge) + f" · Locale: [cyan]{locale}[/cyan]",
143
149
  border_style="blue",
144
150
  ))
151
+ # Run evidence (video, traces, console and network errors): web and Electron.
152
+ evidence_cfg = cfg.get("evidence") or {}
153
+ evidence_mode = evidence_mode or evidence_cfg.get("mode") or _evidence.DEFAULT_MODE
154
+ if evidence_mode not in _evidence.MODES:
155
+ console.print(f"[red]evidence.mode must be one of: {', '.join(_evidence.MODES)}[/red]")
156
+ sys.exit(1)
157
+ evidence_dir = None
158
+ if evidence_mode != "off" and platform in ("playwright", "electron"):
159
+ from datetime import datetime, timezone
160
+ evidence_dir = (Path(evidence_cfg.get("dir", DEFAULT_EVIDENCE_DIR))
161
+ / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ"))
162
+
145
163
  # Build adapter
146
- adapter = _build_adapter(platform, app, url, headless)
164
+ adapter = _build_adapter(platform, app, url, headless, evidence_dir=evidence_dir)
147
165
 
148
166
  # Build runner — enable step logging when an API key is present so every
149
167
  # (goal, screen, action, outcome) tuple is captured for training-data.
@@ -198,6 +216,7 @@ def run(goal, goal_file, platform, app, url, locale, backend, headless, output,
198
216
  # retried in a fresh browser before it's reported as a regression.
199
217
  deploy=deploy or _deploy_from_env(),
200
218
  fresh_adapter=(lambda: _build_adapter(platform, app, url, True)) if platform == "playwright" else None,
219
+ evidence_mode=evidence_mode,
201
220
  )
202
221
  runner = FusionTestRunner(adapter, runner_cfg)
203
222
 
@@ -249,6 +268,8 @@ def run(goal, goal_file, platform, app, url, locale, backend, headless, output,
249
268
  finally:
250
269
  progress.stop()
251
270
 
271
+ _finish_evidence(adapter, result, evidence_mode, evidence_dir)
272
+
252
273
  # Failure screenshots: saved next to the project, shown in the results.
253
274
  shot_dir = Path(cfg.get("screenshots", {}).get("dir", DEFAULT_SCREENSHOT_DIR))
254
275
  shots = _save_screenshots(result, shot_dir)
@@ -256,6 +277,7 @@ def run(goal, goal_file, platform, app, url, locale, backend, headless, output,
256
277
 
257
278
  # Print results table, then Slack / GitHub annotations if configured
258
279
  _print_results(result, shots, bug_shots)
280
+ _print_evidence(result, evidence_dir)
259
281
  _notify(result)
260
282
 
261
283
  # Save JSON report locally
@@ -270,6 +292,8 @@ def run(goal, goal_file, platform, app, url, locale, backend, headless, output,
270
292
  _upload_screenshots(uploaded_run_id, shots)
271
293
  if bug_shots:
272
294
  _upload_screenshots(uploaded_run_id, bug_shots, kind="bug")
295
+ if uploaded_run_id and result.video and evidence_cfg.get("upload", True):
296
+ _upload_video(uploaded_run_id, Path(result.video))
273
297
 
274
298
  # Upload step telemetry (best-effort, non-blocking)
275
299
  if _api_key and _step_log_tmp:
@@ -842,6 +866,92 @@ def _upload_screenshots(run_id: str, shots: dict[int, Path], kind: str = "goal")
842
866
  console.print(f"[dim]{stored} {what} screenshot(s) attached to the run (kept 30 days).[/dim]")
843
867
 
844
868
 
869
+ def _finish_evidence(adapter, result, mode: str, evidence_dir: Path | None) -> None:
870
+ """Close the browser so the video is written, then keep or delete it."""
871
+ finish = getattr(adapter, "finish_evidence", None)
872
+ if finish is None or evidence_dir is None:
873
+ return
874
+ try:
875
+ video = finish()
876
+ except Exception as e: # noqa: BLE001 — never fail a run over evidence
877
+ console.print(f"[yellow]Warning:[/yellow] Could not save the run's video: {e}")
878
+ return
879
+ if video is None:
880
+ return
881
+ if _evidence.keeps_video(mode, result.success):
882
+ target = evidence_dir / "run.webm"
883
+ try:
884
+ video.replace(target)
885
+ except OSError:
886
+ target = video
887
+ result.video = str(target)
888
+ else:
889
+ video.unlink(missing_ok=True)
890
+ shutil.rmtree(evidence_dir / "video", ignore_errors=True)
891
+ if evidence_dir.exists() and not any(evidence_dir.iterdir()):
892
+ evidence_dir.rmdir()
893
+
894
+
895
+ def _print_evidence(result, evidence_dir: Path | None) -> None:
896
+ traces = [(i, s.evidence.trace) for i, s in enumerate(result.steps) if s.evidence and s.evidence.trace]
897
+ problems = sum(len(s.evidence.console) + len(s.evidence.network)
898
+ for s in result.steps if s.evidence and not s.success)
899
+ if not traces and not result.video and not problems:
900
+ return
901
+ console.print("\n[bold]Evidence[/bold]")
902
+ if result.video:
903
+ console.print(f" video: {escape(result.video)}", soft_wrap=True)
904
+ for i, trace in traces:
905
+ console.print(f" {i + 1}. trace: {escape(trace)}", soft_wrap=True)
906
+ if traces:
907
+ console.print(" [dim]Open a trace with: playwright show-trace <file>[/dim]")
908
+ for i, step in enumerate(result.steps):
909
+ if step.success or step.evidence is None:
910
+ continue
911
+ for e in step.evidence.console[:5]:
912
+ console.print(f" {i + 1}. [dim]console {e.level}:[/dim] {escape(e.text)}", soft_wrap=True)
913
+ for e in step.evidence.network[:5]:
914
+ what = str(e.status) if e.status else e.failure
915
+ console.print(f" {i + 1}. [dim]network:[/dim] {escape(e.method)} {escape(e.url)} → {escape(what)}",
916
+ soft_wrap=True)
917
+
918
+
919
+ def _without_trace(step: dict) -> dict:
920
+ ev = step.get("evidence")
921
+ if not ev or "trace" not in ev:
922
+ return step
923
+ return {**step, "evidence": {k: v for k, v in ev.items() if k != "trace"}}
924
+
925
+
926
+ def _upload_video(run_id: str, path: Path) -> None:
927
+ """Attach the run's video to the uploaded run (best effort; kept 30 days,
928
+ and the org's screenshot setting covers it too)."""
929
+ import os
930
+
931
+ import httpx
932
+
933
+ size = path.stat().st_size if path.exists() else 0
934
+ if not size:
935
+ return
936
+ if size > _VIDEO_MAX_BYTES:
937
+ console.print(f"[dim]Video not uploaded: {size // (1024 * 1024)} MB is over the "
938
+ f"{_VIDEO_MAX_BYTES // (1024 * 1024)} MB limit (it's kept locally).[/dim]")
939
+ return
940
+ api_url = os.getenv("FUSIONTEST_API_URL", "https://api.fusiontest.fusionleap.io")
941
+ headers = {"Authorization": f"Bearer {os.getenv('FUSIONTEST_API_KEY', '')}", "Content-Type": "video/webm"}
942
+ try:
943
+ resp = httpx.post(f"{api_url}/api/runs/{run_id}/video", content=path.read_bytes(),
944
+ headers=headers, timeout=120)
945
+ resp.raise_for_status()
946
+ if resp.json().get("stored"):
947
+ console.print("[dim]Video attached to the run (kept 30 days).[/dim]")
948
+ except Exception as e: # noqa: BLE001 — never fail a run over a video
949
+ console.print(f"[yellow]Warning:[/yellow] Could not upload the video: {e}")
950
+
951
+
952
+ _VIDEO_MAX_BYTES = 50 * 1024 * 1024
953
+
954
+
845
955
  def _load_env() -> None:
846
956
  """Load .env from the directory the command runs in (or a parent).
847
957
 
@@ -1339,6 +1449,17 @@ def bench(suites, backends, repeat, headless, out_dir, min_accuracy, max_cost, m
1339
1449
  Path(summary_md).write_text(
1340
1450
  _bench_markdown(summaries, runs, spend_line, bug_summaries, bug_runs), encoding="utf-8")
1341
1451
 
1452
+ # A suite × backend where every case errored measured nothing (a rejected API
1453
+ # key, no credits, an outage). Results are still written and uploaded so the
1454
+ # dashboard shows the gap, but the run fails so it doesn't go unnoticed.
1455
+ unmeasured = ([f"{sm.suite} × {sm.backend}" for sm in summaries if sm.cases and not sm.evaluated]
1456
+ + [f"{sm.suite} × {sm.backend}" for sm in bug_summaries
1457
+ if sm.errors and not sm.variants])
1458
+ if unmeasured:
1459
+ console.print(f"[red]✗ Nothing measured for {', '.join(unmeasured)}: every case errored. "
1460
+ "Check the errors above (API key, credits, provider outage).[/red]")
1461
+ sys.exit(1)
1462
+
1342
1463
  if min_accuracy is not None:
1343
1464
  below = [sm for sm in summaries if sm.accuracy < min_accuracy or sm.false_pass]
1344
1465
  if below:
@@ -1778,10 +1899,11 @@ def _is_ollama_running() -> bool:
1778
1899
  return False
1779
1900
 
1780
1901
 
1781
- def _build_adapter(platform: str, app: str | None, url: str | None, headless: bool):
1902
+ def _build_adapter(platform: str, app: str | None, url: str | None, headless: bool,
1903
+ evidence_dir: Path | None = None):
1782
1904
  if platform == "playwright":
1783
1905
  from fusiontest.desktop.playwright_adapter import PlaywrightAdapter
1784
- adapter = PlaywrightAdapter(browser_type="chromium", headless=headless)
1906
+ adapter = PlaywrightAdapter(browser_type="chromium", headless=headless, evidence_dir=evidence_dir)
1785
1907
  adapter.start(url=url)
1786
1908
  return adapter
1787
1909
 
@@ -1790,7 +1912,7 @@ def _build_adapter(platform: str, app: str | None, url: str | None, headless: bo
1790
1912
  console.print("[red]--app is required for electron platform[/red]")
1791
1913
  sys.exit(1)
1792
1914
  from fusiontest.desktop.playwright_adapter import PlaywrightAdapter
1793
- adapter = PlaywrightAdapter(electron_app_path=app, headless=headless)
1915
+ adapter = PlaywrightAdapter(electron_app_path=app, headless=headless, evidence_dir=evidence_dir)
1794
1916
  adapter.start()
1795
1917
  return adapter
1796
1918
 
@@ -1958,6 +2080,7 @@ def _save_report(result, path: str) -> None:
1958
2080
  "total_duration_seconds": result.total_duration_seconds,
1959
2081
  "steps": [s.to_dict() for s in result.steps],
1960
2082
  "bugs_detected": [b.to_dict() for b in result.bugs_detected],
2083
+ **({"video": result.video} if result.video else {}),
1961
2084
  }
1962
2085
  with open(path, "w") as f:
1963
2086
  json.dump(data, f, indent=2)
@@ -1989,7 +2112,9 @@ def _upload_report(result) -> str | None:
1989
2112
  "status": result.status,
1990
2113
  "stability_score": result.stability_score,
1991
2114
  "total_duration_seconds": result.total_duration_seconds,
1992
- "steps": [s.to_dict() for s in result.steps],
2115
+ # Traces stay on this machine (they hold cookies and headers), and so
2116
+ # do local paths.
2117
+ "steps": [_without_trace(s.to_dict()) for s in result.steps],
1993
2118
  "bugs_detected": [b.to_dict() for b in result.bugs_detected],
1994
2119
  }
1995
2120
 
@@ -700,7 +700,10 @@ class LLMCaller:
700
700
  from google.genai import types as genai_types
701
701
  client = genai.Client(
702
702
  api_key=api_key,
703
- http_options=genai_types.HttpOptions(timeout=LLM_REQUEST_TIMEOUT_SECONDS * 1000), # ms
703
+ # v1beta: google-genai 3.x defaults to v1, where some models
704
+ # (gemini-2.5-flash) reject system instructions.
705
+ http_options=genai_types.HttpOptions(
706
+ api_version="v1beta", timeout=LLM_REQUEST_TIMEOUT_SECONDS * 1000), # ms
704
707
  )
705
708
 
706
709
  else:
@@ -0,0 +1,164 @@
1
+ """
2
+ fusiontest.core.evidence — what happened during a goal, kept so a person can
3
+ check the verdict themselves.
4
+
5
+ Adapters that can record (Playwright: web and Electron) capture, per goal:
6
+
7
+ console the page's console errors and warnings
8
+ network requests that failed or got a 4xx/5xx answer
9
+ trace a Playwright trace of the goal (open with `playwright show-trace`)
10
+
11
+ and one video of the whole run, with the second each goal started at so a
12
+ viewer can jump to it.
13
+
14
+ Unlike app_errors (near-certain bugs, ADR-009), these are raw observations:
15
+ a 404 for a missing avatar or a console warning is evidence, not a bug.
16
+
17
+ Secrets: console text and network URLs are redacted, and URLs lose their
18
+ query string and fragment (tokens often live there). Trace files are scrubbed
19
+ of secret values too, but they still hold cookies, request headers and
20
+ screenshots, so they stay on the machine that ran the test and are never
21
+ uploaded. The video shows the screen as a user would see it (password fields
22
+ masked), the same as failure screenshots.
23
+
24
+ Modes (`--evidence`, config `evidence.mode`):
25
+ failures keep traces of failed goals, and the video only if a goal failed
26
+ all keep everything
27
+ off record nothing
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import logging
33
+ import os
34
+ import re
35
+ import zipfile
36
+ from dataclasses import dataclass, field
37
+ from pathlib import Path
38
+ from urllib.parse import urlsplit
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ MODES = ("failures", "all", "off")
43
+ DEFAULT_MODE = "failures"
44
+
45
+ # Per goal, so a page that logs in a loop can't bloat the report.
46
+ MAX_ENTRIES = 50
47
+ MAX_TEXT = 500
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ConsoleEntry:
52
+ level: str # error | warning
53
+ text: str
54
+ page: str # path of the page it was logged on
55
+
56
+ def to_dict(self) -> dict:
57
+ return {"level": self.level, "text": self.text, "page": self.page}
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class NetworkEntry:
62
+ method: str
63
+ url: str # scheme://host/path — no query or fragment
64
+ status: int # 0 when the request failed without an answer
65
+ failure: str # e.g. "net::ERR_CONNECTION_REFUSED"; "" when it got an answer
66
+ resource: str # document | xhr | fetch | script | image | …
67
+
68
+ def to_dict(self) -> dict:
69
+ return {"method": self.method, "url": self.url, "status": self.status,
70
+ "failure": self.failure, "resource": self.resource}
71
+
72
+
73
+ @dataclass
74
+ class GoalEvidence:
75
+ console: list[ConsoleEntry] = field(default_factory=list)
76
+ network: list[NetworkEntry] = field(default_factory=list)
77
+ dropped: int = 0 # entries over MAX_ENTRIES, not kept
78
+ trace: str = "" # local path of the goal's trace zip, if kept
79
+ video_start: float | None = None # seconds into the run's video
80
+
81
+ def to_dict(self) -> dict:
82
+ data: dict = {
83
+ "console": [e.to_dict() for e in self.console],
84
+ "network": [e.to_dict() for e in self.network],
85
+ }
86
+ if self.dropped:
87
+ data["dropped"] = self.dropped
88
+ if self.trace:
89
+ data["trace"] = self.trace
90
+ if self.video_start is not None:
91
+ data["video_start"] = round(self.video_start, 1)
92
+ return data
93
+
94
+
95
+ def clean_url(url: str) -> str:
96
+ """The URL without query string, fragment or credentials. Never raises."""
97
+ try:
98
+ parts = urlsplit(url)
99
+ host, port = parts.hostname, parts.port
100
+ except ValueError: # bad port, unclosed "[", …
101
+ return _clean_malformed(url)
102
+ if not parts.scheme or not host:
103
+ return parts.path or _clean_malformed(url)
104
+ host = f"[{host}]" if ":" in host else host
105
+ return f"{parts.scheme}://{host}{f':{port}' if port else ''}{parts.path or '/'}"
106
+
107
+
108
+ def _clean_malformed(url: str) -> str:
109
+ """clean_url for what urlsplit can't take apart, by text alone."""
110
+ head, sep, rest = url.partition("//")
111
+ if not sep:
112
+ head, rest = "", url
113
+ authority = re.match(r"[^/?#]*", rest).group()
114
+ tail = rest[len(authority):]
115
+ if "@" in tail: # maybe credentials holding "/" or "?": can't tell where they end
116
+ return f"{head}{sep}***"
117
+ return head + sep + authority.rpartition("@")[2] + re.split(r"[?#]", tail, maxsplit=1)[0]
118
+
119
+
120
+ def clip(text: str) -> str:
121
+ text = " ".join(text.split())
122
+ return text if len(text) <= MAX_TEXT else text[: MAX_TEXT - 1] + "…"
123
+
124
+
125
+ def keeps_trace(mode: str, passed: bool) -> bool:
126
+ return mode == "all" or (mode == "failures" and not passed)
127
+
128
+
129
+ def keeps_video(mode: str, run_passed: bool) -> bool:
130
+ return mode == "all" or (mode == "failures" and not run_passed)
131
+
132
+
133
+ def scrub_trace(path: Path, secrets: list[str]) -> None:
134
+ """Replace secret values in the text files of a trace zip, in place.
135
+
136
+ Playwright traces log typed values ("fill" parameters) and DOM snapshots
137
+ with field values. Screenshots inside the trace can't be scrubbed — one
138
+ more reason traces stay local.
139
+ """
140
+ values = sorted({s for s in secrets if s}, key=len, reverse=True)
141
+ if not values or not path.exists():
142
+ return
143
+ needles: list[tuple[bytes, bytes]] = []
144
+ for value in values:
145
+ for form in {value, value.replace("\\", "\\\\").replace('"', '\\"')}:
146
+ needles.append((form.encode(), b"***"))
147
+ tmp = path.with_suffix(".scrub.zip")
148
+ try:
149
+ with zipfile.ZipFile(path) as src, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as dst:
150
+ for info in src.infolist():
151
+ data = src.read(info)
152
+ if not _is_image(info.filename):
153
+ for needle, repl in needles:
154
+ data = data.replace(needle, repl)
155
+ dst.writestr(info, data)
156
+ os.replace(tmp, path)
157
+ except Exception as exc: # noqa: BLE001 — a bad trace must not fail a run
158
+ logger.warning("Could not scrub trace %s, deleting it: %s", path, exc)
159
+ tmp.unlink(missing_ok=True)
160
+ path.unlink(missing_ok=True)
161
+
162
+
163
+ def _is_image(name: str) -> bool:
164
+ return name.lower().endswith((".jpeg", ".jpg", ".png", ".webp"))
@@ -28,6 +28,7 @@ class LogEntry:
28
28
  url: str = ""
29
29
  action: RecordedAction | None = None
30
30
  text: str = "" # in plain words, secrets masked: a step to reproduce
31
+ goal: str = "" # the goal (as written) it was part of: whose secrets it may type
31
32
 
32
33
 
33
34
  @dataclass
@@ -22,6 +22,7 @@ from typing import Protocol, runtime_checkable
22
22
  from urllib.parse import urlsplit
23
23
 
24
24
  from fusiontest.core import bugs
25
+ from fusiontest.core import evidence as run_evidence
25
26
  from fusiontest.core.action_model import (
26
27
  VISION_BACKENDS,
27
28
  Action,
@@ -111,6 +112,9 @@ class StepResult:
111
112
  # The judge's last reason for its verdict on this goal (ADR-010), for
112
113
  # reports that explain a pass as well as a failure.
113
114
  judge_reason: str = ""
115
+ # Console and network problems, the trace and where the goal starts in the
116
+ # run's video (fusiontest.core.evidence), from adapters that record them.
117
+ evidence: run_evidence.GoalEvidence | None = None
114
118
 
115
119
  def to_dict(self) -> dict:
116
120
  """JSON-safe form for reports and the API (screenshots excluded)."""
@@ -128,6 +132,7 @@ class StepResult:
128
132
  "verifier": self.verifier_tokens.to_dict(),
129
133
  },
130
134
  "mode": self.mode,
135
+ **({"evidence": self.evidence.to_dict()} if self.evidence is not None else {}),
131
136
  }
132
137
 
133
138
 
@@ -150,6 +155,8 @@ class RunResult:
150
155
  # LLM answers per "backend:model" (action model + verifier) — which
151
156
  # providers actually did the work after fallbacks.
152
157
  llm_calls: dict[str, int] = field(default_factory=dict)
158
+ # Local path of the run's video (fusiontest.core.evidence), once kept.
159
+ video: str = ""
153
160
 
154
161
  @property
155
162
  def errored(self) -> bool:
@@ -225,6 +232,7 @@ class RunnerConfig:
225
232
  # Keys are variable names, values are secret strings.
226
233
  # Env vars are also searched when a key is missing here, unless
227
234
  # secrets_allow_env is False (required for multi-tenant server runs).
235
+ # Either way, a goal can only type the ones its own text references.
228
236
  secrets: dict[str, str] = field(default_factory=dict)
229
237
  secrets_allow_env: bool = True
230
238
  # The model only ever sees {{VAR}} placeholders; real values are filled
@@ -257,6 +265,9 @@ class RunnerConfig:
257
265
  # (fresh_adapter) and reported as a regression only if it fails again.
258
266
  deploy: str = ""
259
267
  retry_regressions: bool = True
268
+ # Which goal traces to keep, from adapters that record evidence:
269
+ # "failures" (default), "all" or "off" (fusiontest.core.evidence).
270
+ evidence_mode: str = run_evidence.DEFAULT_MODE
260
271
 
261
272
 
262
273
  # ── Runner ─────────────────────────────────────────────────────────────────────
@@ -418,6 +429,7 @@ class FusionTestRunner:
418
429
  watchdog.start()
419
430
 
420
431
  app_closed = False
432
+ self._begin_evidence()
421
433
  try:
422
434
  step_result = self._execute_goal(goal, safe_goal, goal_url, resolver)
423
435
  except AdapterClosed as exc:
@@ -450,6 +462,7 @@ class FusionTestRunner:
450
462
  step_result.error = (
451
463
  f"goal_timeout: exceeded {self.config.max_goal_seconds}s wall-clock limit"
452
464
  )
465
+ step_result.evidence = self._end_evidence(i - 1, step_result, resolver)
453
466
  result.steps.append(step_result)
454
467
 
455
468
  if not step_result.success:
@@ -718,7 +731,7 @@ class FusionTestRunner:
718
731
  logger.info(f" Backtracking (step {step_num})")
719
732
  self._backtrack(history)
720
733
  recorded.append(RecordedAction(action_type="back"))
721
- self._log.append(LogEntry(kind="action", action=recorded[-1], text="Go back"))
734
+ self._log.append(LogEntry(kind="action", action=recorded[-1], text="Go back", goal=_safe))
722
735
  break
723
736
 
724
737
  if gr.should_skip:
@@ -726,7 +739,7 @@ class FusionTestRunner:
726
739
  continue
727
740
 
728
741
  # 5. Execute the action, filling in any secrets
729
- exec_action, blocked = self._bind_secrets(gr.action, resolver)
742
+ exec_action, blocked = self._bind_secrets(gr.action, resolver, _safe)
730
743
  if blocked:
731
744
  logger.warning(f" {blocked}")
732
745
  step.success = False
@@ -748,7 +761,7 @@ class FusionTestRunner:
748
761
  safe_action_str = _redact(action_str)
749
762
  step.actions.append(safe_action_str) # stored — secrets masked
750
763
  action_text = _redact(_action_text(gr.action, elements))
751
- self._log.append(LogEntry(kind="action", action=recorded[-1],
764
+ self._log.append(LogEntry(kind="action", action=recorded[-1], goal=_safe,
752
765
  text=step_text("action", action=action_text)))
753
766
  pending = (action_text, screen_text, len(self._log))
754
767
  self.guardrails.record_action(gr.action)
@@ -810,6 +823,27 @@ class FusionTestRunner:
810
823
 
811
824
  # ── Record & replay (ADR-007 Phase 2) ──────────────────────────────────────
812
825
 
826
+ def _begin_evidence(self) -> None:
827
+ begin = getattr(self.adapter, "begin_goal_evidence", None)
828
+ if begin is None or self.config.evidence_mode == "off":
829
+ return
830
+ try:
831
+ begin()
832
+ except Exception as exc: # noqa: BLE001 — evidence must never fail a run
833
+ logger.debug("Could not start collecting evidence: %s", exc)
834
+
835
+ def _end_evidence(self, index: int, step: StepResult,
836
+ resolver: SecretResolver) -> run_evidence.GoalEvidence | None:
837
+ end = getattr(self.adapter, "end_goal_evidence", None)
838
+ if end is None or self.config.evidence_mode == "off":
839
+ return None
840
+ try:
841
+ return end(index, run_evidence.keeps_trace(self.config.evidence_mode, step.success),
842
+ redact=resolver.redact, secrets=resolver.sensitive_values)
843
+ except Exception as exc: # noqa: BLE001 — evidence must never fail a run
844
+ logger.debug("Could not collect evidence: %s", exc)
845
+ return None
846
+
813
847
  def _execute_goal(
814
848
  self, goal: str, safe_goal: str, goal_url: str, resolver: SecretResolver
815
849
  ) -> StepResult:
@@ -933,7 +967,7 @@ class FusionTestRunner:
933
967
  action = resolve_action(entry.action, elements)
934
968
  if action is None:
935
969
  return False
936
- exec_action, blocked = self._bind_secrets(action, resolver)
970
+ exec_action, blocked = self._bind_secrets(action, resolver, entry.goal)
937
971
  if blocked or not self.adapter.execute(exec_action, elements):
938
972
  return False
939
973
  return True
@@ -1080,7 +1114,7 @@ class FusionTestRunner:
1080
1114
  logger.info(" Reproduction stopped: %s %r is gone",
1081
1115
  entry.action.element_type, entry.action.element_label)
1082
1116
  break
1083
- exec_action, blocked = self._bind_secrets(action, resolver)
1117
+ exec_action, blocked = self._bind_secrets(action, resolver, entry.goal)
1084
1118
  if blocked or not adapter.execute(exec_action, elements):
1085
1119
  logger.info(" Reproduction stopped: %s failed", entry.action.action_type)
1086
1120
  break
@@ -1130,11 +1164,12 @@ class FusionTestRunner:
1130
1164
  if action is None:
1131
1165
  logger.info(f" Replay: element gone — {recorded.element_type} {recorded.element_label!r}")
1132
1166
  return None
1133
- exec_action, blocked = self._bind_secrets(action, resolver)
1167
+ # The trace may be old, edited or shared: this goal decides what it may type.
1168
+ exec_action, blocked = self._bind_secrets(action, resolver, safe_goal)
1134
1169
  if blocked or not self.adapter.execute(exec_action, elements):
1135
- logger.info(f" Replay: action failed — {action}")
1170
+ logger.info(f" Replay: {blocked or f'action failed — {action}'}")
1136
1171
  return None
1137
- self._log.append(LogEntry(kind="action", action=recorded, text=step_text(
1172
+ self._log.append(LogEntry(kind="action", action=recorded, goal=safe_goal, text=step_text(
1138
1173
  "action", action=resolver.redact(_action_text(action, elements)))))
1139
1174
  actions.append(resolver.redact(str(action)))
1140
1175
  if trace.actions:
@@ -1185,12 +1220,16 @@ class FusionTestRunner:
1185
1220
  logger.warning(f" Navigation failed: {e}")
1186
1221
 
1187
1222
  def _bind_secrets(
1188
- self, action: Action, resolver: SecretResolver | None
1223
+ self, action: Action, resolver: SecretResolver | None, goal: str
1189
1224
  ) -> tuple[Action, str | None]:
1190
1225
  """
1191
- Substitute {{VAR}} placeholders in a "type" action's value — when
1192
- secret_hosts is set, only if the current page's host is allowed for
1193
- every referenced secret.
1226
+ Substitute {{VAR}} placeholders in a "type" action's value — only ones
1227
+ *goal* (as its author wrote it) contains, and when secret_hosts is set,
1228
+ only if the current page's host is allowed for every referenced secret.
1229
+
1230
+ The action's text is the model's, and a page can talk the model into
1231
+ typing {{ANY_ENV_VAR}}: what a goal doesn't reference is never typed.
1232
+ Pass the goal as written, not the model's copy (its hint says {{NAME}}).
1194
1233
 
1195
1234
  Returns (action_to_execute, None), or (action, error) when blocked.
1196
1235
  Other action types are returned unchanged — placeholders stay literal.
@@ -1198,6 +1237,13 @@ class FusionTestRunner:
1198
1237
  names = SecretResolver.template_names(action.value or "")
1199
1238
  if not names or action.action_type != "type" or resolver is None:
1200
1239
  return action, None
1240
+ own = set(SecretResolver.placeholders(goal))
1241
+ for placeholder in SecretResolver.placeholders(action.value):
1242
+ if placeholder not in own:
1243
+ return action, (
1244
+ f"secret_not_in_goal: {placeholder} was not typed: this goal doesn't "
1245
+ f"reference it (a goal can only type the {{{{VAR}}}} placeholders in its own text)"
1246
+ )
1201
1247
  if self.config.secret_hosts is None:
1202
1248
  return replace(action, value=resolver.resolve(action.value)), None
1203
1249
 
@@ -99,10 +99,22 @@ class SecretResolver:
99
99
  result = result.replace(secret, "***")
100
100
  return result
101
101
 
102
+ @property
103
+ def sensitive_values(self) -> list[str]:
104
+ """The secret values resolved so far, for scrubbing files that can't
105
+ go through redact() line by line (e.g. trace archives)."""
106
+ return list(self._sensitive)
107
+
102
108
  def has_templates(self, text: str) -> bool:
103
109
  """True if *text* contains any {{VAR}} placeholders."""
104
110
  return bool(_TEMPLATE_RE.search(text))
105
111
 
112
+ @staticmethod
113
+ def placeholders(text: str) -> list[str]:
114
+ """The placeholders in *text* as written, minus spaces ("{{EMAIL}}"), in
115
+ order of appearance. The runner types only those the goal contains too."""
116
+ return ["".join(m.group(0).split()) for m in _TEMPLATE_RE.finditer(text)]
117
+
106
118
  @staticmethod
107
119
  def template_names(text: str) -> list[str]:
108
120
  """Variable names referenced as {{VAR}} in *text*, in order of appearance."""