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
@@ -0,0 +1,266 @@
1
+ """Concrete Playwright ``trace.zip`` parser for the Shadow Runtime.
2
+
3
+ The archive holds JSONL trace streams (``*.trace`` / ``*.network``) plus a
4
+ ``resources/`` folder of SHA-1 addressed response bodies. Network activity lives
5
+ in ``resource-snapshot`` events, each a HAR entry already pairing a request with
6
+ its response. We map those entries onto the existing schema models
7
+ (:class:`CapturedRequest`, :class:`CapturedResponse`, :class:`NetworkSnapshot`);
8
+ snapshot assembly, persistence and replay are later stages.
9
+ """
10
+
11
+ import base64
12
+ import json
13
+ import zipfile
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+
17
+ import structlog
18
+
19
+ from app.shadow.interfaces import ITraceParser
20
+ from app.shadow.schemas import CapturedRequest, CapturedResponse, NetworkSnapshot
21
+
22
+ logger = structlog.get_logger(__name__)
23
+
24
+ # Newer Playwright writes resources to ``*.network``, older embeds them in
25
+ # ``*.trace``; preferring ``*.network`` avoids double-counting across streams.
26
+ _NETWORK_SUFFIX = ".network"
27
+ _TRACE_SUFFIX = ".trace"
28
+ _RESOURCE_SNAPSHOT = "resource-snapshot" # trace event holding a HAR entry
29
+ _RESOURCES_PREFIX = "resources/"
30
+
31
+
32
+ class TraceParseError(Exception):
33
+ """Base exception for trace parsing failures."""
34
+
35
+
36
+ class InvalidTraceArchiveError(TraceParseError):
37
+ """Raised when a trace archive is missing, unreadable, or not a Playwright trace."""
38
+
39
+
40
+ class PlaywrightTraceParser(ITraceParser):
41
+ """Reads a Playwright ``trace.zip`` and extracts its network interactions.
42
+
43
+ :meth:`parse` returns request/response pairs as chronologically ordered
44
+ :class:`NetworkSnapshot`. Non-network events are ignored; malformed lines and
45
+ incomplete interactions are skipped with a warning rather than aborting.
46
+ """
47
+
48
+ def parse(self, trace_path: Path) -> list[NetworkSnapshot]:
49
+ """Parse ``trace_path`` into its captured network interactions.
50
+
51
+ Raises :class:`InvalidTraceArchiveError` when the path is missing, is not
52
+ a readable zip, or has no trace streams. No network activity yields ``[]``.
53
+ """
54
+ path = Path(trace_path)
55
+ if not path.exists():
56
+ raise InvalidTraceArchiveError(f"Trace archive does not exist: {path}")
57
+ if not path.is_file():
58
+ raise InvalidTraceArchiveError(f"Trace path is not a file: {path}")
59
+
60
+ logger.info("trace_parse_started", path=str(path))
61
+
62
+ try:
63
+ with zipfile.ZipFile(path) as archive:
64
+ if archive.testzip() is not None:
65
+ raise InvalidTraceArchiveError(f"Trace archive is corrupted: {path}")
66
+
67
+ stream_names = self._select_trace_streams(archive.namelist())
68
+ if not stream_names:
69
+ raise InvalidTraceArchiveError(
70
+ f"No Playwright trace streams found in archive: {path}"
71
+ )
72
+
73
+ entries = self._collect_har_entries(archive, stream_names)
74
+ snapshots = self._build_snapshots(archive, entries)
75
+ except zipfile.BadZipFile as exc:
76
+ logger.exception("trace_archive_invalid", path=str(path))
77
+ raise InvalidTraceArchiveError(f"Not a valid zip archive: {path}") from exc
78
+ except OSError as exc:
79
+ logger.exception("trace_archive_unreadable", path=str(path))
80
+ raise InvalidTraceArchiveError(f"Failed to read trace archive: {path}") from exc
81
+
82
+ logger.info("trace_parse_finished", path=str(path), event_count=len(snapshots))
83
+ return snapshots
84
+
85
+ @staticmethod
86
+ def _select_trace_streams(names: list[str]) -> list[str]:
87
+ """Pick the JSONL streams to read, preferring ``*.network`` over ``*.trace``."""
88
+ network = [name for name in names if name.endswith(_NETWORK_SUFFIX)]
89
+ if network:
90
+ return network
91
+ return [name for name in names if name.endswith(_TRACE_SUFFIX)]
92
+
93
+ def _collect_har_entries(self, archive: zipfile.ZipFile, stream_names: list[str]) -> list[dict]:
94
+ """Read the selected streams and return the HAR entries of network events."""
95
+ entries: list[dict] = []
96
+ for name in stream_names:
97
+ raw = archive.read(name).decode("utf-8", errors="replace")
98
+ for line_no, line in enumerate(raw.splitlines(), start=1):
99
+ line = line.strip()
100
+ if not line:
101
+ continue
102
+ try:
103
+ event = json.loads(line)
104
+ except json.JSONDecodeError:
105
+ logger.warning("trace_line_skipped", stream=name, line=line_no)
106
+ continue
107
+ if not isinstance(event, dict) or event.get("type") != _RESOURCE_SNAPSHOT:
108
+ continue # ignore non-network trace events
109
+ snapshot = event.get("snapshot")
110
+ if isinstance(snapshot, dict):
111
+ entries.append(snapshot)
112
+ return entries
113
+
114
+ def _build_snapshots(
115
+ self, archive: zipfile.ZipFile, entries: list[dict]
116
+ ) -> list[NetworkSnapshot]:
117
+ """Map HAR entries onto ordered :class:`NetworkSnapshot` models."""
118
+ # Order by monotonic time; entries lacking it keep order (stable sort).
119
+ ordered = sorted(entries, key=lambda entry: self._monotonic_time(entry))
120
+
121
+ snapshots: list[NetworkSnapshot] = []
122
+ sequence = 0
123
+ for entry in ordered:
124
+ snapshot = self._to_network_snapshot(archive, entry, sequence)
125
+ if snapshot is None:
126
+ continue
127
+ snapshots.append(snapshot)
128
+ sequence += 1
129
+ return snapshots
130
+
131
+ def _to_network_snapshot(
132
+ self, archive: zipfile.ZipFile, entry: dict, sequence: int
133
+ ) -> NetworkSnapshot | None:
134
+ """Build a single :class:`NetworkSnapshot`, or ``None`` if incomplete."""
135
+ request = self._to_request(entry.get("request"))
136
+ if request is None:
137
+ logger.warning("network_event_skipped", reason="missing_request")
138
+ return None
139
+
140
+ response = self._to_response(archive, entry.get("response"))
141
+ if response is None:
142
+ # Pending/failed request; NetworkSnapshot needs both halves, so drop.
143
+ logger.warning("network_event_skipped", reason="missing_response", url=request.url)
144
+ return None
145
+
146
+ return NetworkSnapshot(
147
+ request=request,
148
+ response=response,
149
+ sequence=sequence,
150
+ started_at=self._started_at(entry),
151
+ duration_ms=self._duration_ms(entry),
152
+ )
153
+
154
+ def _to_request(self, request: dict | None) -> CapturedRequest | None:
155
+ """Map a HAR request object onto :class:`CapturedRequest`."""
156
+ if not isinstance(request, dict):
157
+ return None
158
+ method = request.get("method")
159
+ url = request.get("url")
160
+ if not isinstance(method, str) or not isinstance(url, str) or not method or not url:
161
+ return None
162
+
163
+ post_data = request.get("postData")
164
+ body = post_data.get("text") if isinstance(post_data, dict) else None
165
+ return CapturedRequest(
166
+ method=method,
167
+ url=url,
168
+ headers=self._headers_to_dict(request.get("headers")),
169
+ body=body if isinstance(body, str) else None,
170
+ )
171
+
172
+ def _to_response(
173
+ self, archive: zipfile.ZipFile, response: dict | None
174
+ ) -> CapturedResponse | None:
175
+ """Map a HAR response object onto :class:`CapturedResponse`."""
176
+ if not isinstance(response, dict):
177
+ return None
178
+ status = response.get("status")
179
+ # Playwright records 0/-1 when no response ever arrived.
180
+ if not isinstance(status, int) or status <= 0:
181
+ return None
182
+
183
+ body, is_base64 = self._resolve_response_body(archive, response.get("content"))
184
+ return CapturedResponse(
185
+ status=status,
186
+ headers=self._headers_to_dict(response.get("headers")),
187
+ body=body,
188
+ is_base64=is_base64,
189
+ )
190
+
191
+ def _resolve_response_body(
192
+ self, archive: zipfile.ZipFile, content: dict | None
193
+ ) -> tuple[str | None, bool]:
194
+ """Resolve a HAR ``content`` into ``(body, is_base64)``.
195
+
196
+ Body is inline (``text``) or a SHA-1 resource (``_sha1``); binary payloads
197
+ are base64-encoded with the flag set.
198
+ """
199
+ if not isinstance(content, dict):
200
+ return None, False
201
+
202
+ text = content.get("text")
203
+ if isinstance(text, str):
204
+ return text, content.get("encoding") == "base64"
205
+
206
+ sha1 = content.get("_sha1")
207
+ if not isinstance(sha1, str) or not sha1:
208
+ return None, False
209
+
210
+ raw = self._read_resource(archive, sha1)
211
+ if raw is None:
212
+ return None, False
213
+
214
+ try:
215
+ return raw.decode("utf-8"), False
216
+ except UnicodeDecodeError:
217
+ return base64.b64encode(raw).decode("ascii"), True
218
+
219
+ @staticmethod
220
+ def _read_resource(archive: zipfile.ZipFile, sha1: str) -> bytes | None:
221
+ """Read a response body from the archive's ``resources/`` folder by SHA-1."""
222
+ name = f"{_RESOURCES_PREFIX}{sha1}"
223
+ try:
224
+ return archive.read(name)
225
+ except KeyError:
226
+ logger.warning("trace_resource_missing", sha1=sha1)
227
+ return None
228
+
229
+ @staticmethod
230
+ def _headers_to_dict(headers: object) -> dict[str, str]:
231
+ """Convert HAR ``[{"name", "value"}]`` header lists into a plain dict."""
232
+ result: dict[str, str] = {}
233
+ if not isinstance(headers, list):
234
+ return result
235
+ for header in headers:
236
+ if not isinstance(header, dict):
237
+ continue
238
+ name = header.get("name")
239
+ if not isinstance(name, str) or not name:
240
+ continue
241
+ value = header.get("value")
242
+ result[name] = value if isinstance(value, str) else ""
243
+ return result
244
+
245
+ @staticmethod
246
+ def _monotonic_time(entry: dict) -> float:
247
+ """Return the entry's monotonic time for ordering; missing sorts first."""
248
+ value = entry.get("_monotonicTime")
249
+ return float(value) if isinstance(value, (int, float)) else float("-inf")
250
+
251
+ @staticmethod
252
+ def _started_at(entry: dict) -> float | None:
253
+ """Parse the HAR ``startedDateTime`` (ISO 8601) into epoch seconds."""
254
+ started = entry.get("startedDateTime")
255
+ if not isinstance(started, str) or not started:
256
+ return None
257
+ try:
258
+ return datetime.fromisoformat(started.replace("Z", "+00:00")).timestamp()
259
+ except ValueError:
260
+ return None
261
+
262
+ @staticmethod
263
+ def _duration_ms(entry: dict) -> float | None:
264
+ """Return the HAR ``time`` (total duration in ms) when numeric."""
265
+ value = entry.get("time")
266
+ return float(value) if isinstance(value, (int, float)) else None
@@ -0,0 +1,104 @@
1
+ """Filesystem workspace for the Shadow Runtime.
2
+
3
+ Owns the on-disk directory layout (cache, snapshots, tmp) and its lifecycle
4
+ (creation and policy-aware cleanup). All directory names are derived from the
5
+ shared :class:`ShadowConfig` so they live in exactly one place.
6
+ """
7
+
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ import structlog
12
+
13
+ from app.shadow.config import CleanupPolicy, ShadowConfig
14
+ from app.shadow.interfaces import IShadowWorkspace
15
+
16
+ logger = structlog.get_logger(__name__)
17
+
18
+
19
+ class ShadowWorkspace(IShadowWorkspace):
20
+ """
21
+ Manages temporary runtime resources, cached artifacts, and snapshots for the
22
+ Shadow Runtime, conforming to the IShadowWorkspace interface.
23
+
24
+ Every path is resolved from the shared :class:`ShadowConfig`, so the workspace
25
+ layout is defined in a single place rather than hardcoded here.
26
+ """
27
+
28
+ def __init__(self, config: ShadowConfig | None = None):
29
+ self.config = config or ShadowConfig()
30
+
31
+ # Resolve the workspace root and subdirectories from the shared config.
32
+ self.base_dir = Path(self.config.workspace_dir).resolve()
33
+ self.cache_dir = self.base_dir / self.config.cache_dir
34
+ self.snapshots_dir = self.base_dir / self.config.snapshots_dir
35
+ self.tmp_dir = self.base_dir / self.config.tmp_dir
36
+
37
+ # Automatically build the folders when initialized
38
+ self.setup_dirs()
39
+
40
+ def setup_dirs(self) -> None:
41
+ """Creates the directory structure safely."""
42
+
43
+ for directory in [self.base_dir, self.cache_dir, self.snapshots_dir, self.tmp_dir]:
44
+ directory.mkdir(parents=True, exist_ok=True)
45
+
46
+ def resolve_path(self, relative_path: str | Path) -> Path:
47
+ """Safely resolves paths relative to the workspace base."""
48
+
49
+ return (self.base_dir / relative_path).resolve()
50
+
51
+ def cache_path(self, name: str | Path) -> Path:
52
+ """Returns a path inside the workspace cache directory."""
53
+
54
+ return self._resolve_under(self.cache_dir, name)
55
+
56
+ def snapshot_path(self, name: str | Path) -> Path:
57
+ """Returns a path inside the workspace snapshots directory."""
58
+
59
+ return self._resolve_under(self.snapshots_dir, name)
60
+
61
+ def tmp_path(self, name: str | Path) -> Path:
62
+ """Returns a path inside the workspace temporary directory."""
63
+
64
+ return self._resolve_under(self.tmp_dir, name)
65
+
66
+ def cleanup(self, is_success: bool = False) -> None:
67
+ """Removes the workspace directory according to the configured cleanup policy.
68
+
69
+ - ``NEVER``: always keep artifacts.
70
+ - ``ON_SUCCESS``: remove only when the shadow run succeeded.
71
+ - ``ALWAYS``: remove regardless of outcome.
72
+ """
73
+
74
+ policy = self.config.cleanup_policy
75
+
76
+ if policy is CleanupPolicy.NEVER:
77
+ logger.info("workspace_cleanup_skipped", policy=policy.value, path=str(self.base_dir))
78
+ return
79
+
80
+ if policy is CleanupPolicy.ON_SUCCESS and not is_success:
81
+ logger.info(
82
+ "workspace_cleanup_skipped",
83
+ policy=policy.value,
84
+ is_success=is_success,
85
+ path=str(self.base_dir),
86
+ )
87
+ return
88
+
89
+ if not self.base_dir.exists():
90
+ return
91
+
92
+ shutil.rmtree(self.base_dir)
93
+ logger.info(
94
+ "workspace_cleaned",
95
+ policy=policy.value,
96
+ is_success=is_success,
97
+ path=str(self.base_dir),
98
+ )
99
+
100
+ @staticmethod
101
+ def _resolve_under(root: Path, name: str | Path) -> Path:
102
+ path = (root / name).resolve()
103
+ path.relative_to(root)
104
+ return path
app/state.py ADDED
@@ -0,0 +1,23 @@
1
+ """Shared LangGraph state for the repair loop.
2
+
3
+ The state is a plain ``TypedDict`` so it stays immutable/traceable across nodes:
4
+ each node reads from it and returns a partial update dict.
5
+ """
6
+
7
+ from typing import NotRequired, TypedDict
8
+
9
+
10
+ class AgentState(TypedDict):
11
+ test_script_path: str # path to the test file under repair
12
+ original_code: str # the original test script
13
+ current_code: str # test script as modified in the current loop
14
+ error_log: str # latest Playwright error log (abstracted)
15
+ dom_diff_context: list[dict] # DOM changes from AST parsing
16
+ dom_snapshot: str # ARIA snapshot of the failing page (from error-context.md)
17
+ analysis_report: str # Diagnoser's failure-cause report
18
+ patch_instructions: dict # Patch Generator's fix guide (line, code)
19
+ verification_report: dict # Selector Verifier's live-DOM match result
20
+ shadow_report: NotRequired[dict] # Shadow Verifier's network replay result
21
+ review_report: NotRequired[dict] # Reviewer's source-level suggestions (review mode only)
22
+ loop_count: int # infinite-loop guard (max: settings.max_loops)
23
+ is_success: bool # whether the test passed
app/utils/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Shared utilities."""
app/utils/files.py ADDED
@@ -0,0 +1,24 @@
1
+ """Filesystem helpers."""
2
+
3
+ import os
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ from app.sandbox import assert_write_allowed
8
+
9
+
10
+ def atomic_write(path: Path, content: str) -> None:
11
+ """Write ``content`` to ``path`` atomically.
12
+
13
+ Writes to a temp file in the same directory then ``os.replace`` so a crash mid-write
14
+ never leaves a half-patched test file on disk.
15
+ """
16
+ assert_write_allowed(path, reason="atomic_write")
17
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-", suffix=path.suffix)
18
+ try:
19
+ with os.fdopen(fd, "w") as handle:
20
+ handle.write(content)
21
+ os.replace(tmp, path)
22
+ except BaseException:
23
+ Path(tmp).unlink(missing_ok=True)
24
+ raise
app/verify/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Live-DOM selector verification (grounding for LLM-produced patches)."""
@@ -0,0 +1,92 @@
1
+ """Verify candidate selectors against the live DOM via a Node/Playwright helper.
2
+
3
+ The helper is generated as a temporary ``.mjs`` and run with ``node`` as a subprocess —
4
+ the same "shell out to the installed Playwright" pattern the Test Runner uses, so no new
5
+ Python browser dependency is introduced. It loads the app URL and reports how many elements
6
+ each candidate selector resolves to; the caller treats "exactly one" as verified.
7
+ """
8
+
9
+ import json
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ import structlog
14
+ from tenacity import retry, stop_after_attempt, wait_exponential
15
+
16
+ from app.config import settings
17
+ from app.sandbox import assert_command_allowed, assert_write_allowed
18
+
19
+ logger = structlog.get_logger(__name__)
20
+
21
+ # Node ESM helper: argv = [url, selectorsJson]; prints {selector: count} to stdout.
22
+ # count is -1 when the selector string is invalid for the Playwright engine.
23
+ _HELPER_SCRIPT = """
24
+ import { chromium } from '@playwright/test';
25
+
26
+ const url = process.argv[2];
27
+ const selectors = JSON.parse(process.argv[3]);
28
+
29
+ const browser = await chromium.launch();
30
+ try {
31
+ const page = await browser.newPage();
32
+ await page.goto(url, { waitUntil: 'domcontentloaded' });
33
+ const counts = {};
34
+ for (const selector of selectors) {
35
+ try {
36
+ counts[selector] = await page.locator(selector).count();
37
+ } catch (err) {
38
+ counts[selector] = -1;
39
+ }
40
+ }
41
+ process.stdout.write(JSON.stringify(counts));
42
+ } finally {
43
+ await browser.close();
44
+ }
45
+ """
46
+
47
+ _HELPER_FILENAME = ".e2e-healer-verify.mjs"
48
+
49
+
50
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=8))
51
+ def _run_helper(url: str, selectors: list[str]) -> dict[str, int]:
52
+ """Run the Node helper once and parse its JSON output. Retries on transient failure."""
53
+ script_path = Path.cwd() / _HELPER_FILENAME # in cwd so node resolves @playwright/test
54
+ assert_write_allowed(script_path, reason="selector_verifier_helper")
55
+ script_path.write_text(_HELPER_SCRIPT)
56
+ try:
57
+ cmd = [settings.node_cmd, str(script_path), url, json.dumps(selectors)]
58
+ assert_command_allowed(cmd, reason="selector_verifier")
59
+ result = subprocess.run(
60
+ cmd,
61
+ capture_output=True,
62
+ text=True,
63
+ timeout=90,
64
+ )
65
+ finally:
66
+ script_path.unlink(missing_ok=True)
67
+
68
+ if result.returncode != 0:
69
+ logger.warning(
70
+ "selector_helper_nonzero", returncode=result.returncode, stderr=result.stderr[:500]
71
+ )
72
+ raise RuntimeError("selector_helper_failed")
73
+ return json.loads(result.stdout)
74
+
75
+
76
+ def check_selectors(url: str, selectors: list[str]) -> dict[str, int] | None:
77
+ """Return ``{selector: match_count}`` for each candidate, or ``None`` if it can't run.
78
+
79
+ ``None`` signals a graceful skip (Node/Playwright missing, page unreachable, bad JSON):
80
+ verification degrades to "unverified" so the repair loop is never blocked by tooling.
81
+ """
82
+ if not selectors:
83
+ return {}
84
+
85
+ try:
86
+ counts = _run_helper(url, selectors)
87
+ except Exception:
88
+ logger.exception("selector_check_skipped")
89
+ return None
90
+
91
+ logger.info("selector_check_finished", counts=counts)
92
+ return counts