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/shadow/runtime.py ADDED
@@ -0,0 +1,233 @@
1
+ """Shadow Runtime entry point.
2
+
3
+ Instantiating the runtime has no side effects, and all collaborating components
4
+ are optional so a minimal runtime can be created and driven without wiring any
5
+ real components yet.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import shlex
11
+ import socket
12
+ import subprocess
13
+ import urllib.request
14
+ from pathlib import Path
15
+ from typing import cast
16
+
17
+ import structlog
18
+ from playwright.sync_api import sync_playwright
19
+
20
+ from app.config import settings
21
+ from app.sandbox import assert_command_allowed, assert_read_allowed, assert_write_allowed
22
+ from app.shadow.config import ShadowConfig
23
+ from app.shadow.context import ShadowContext
24
+ from app.shadow.injector import MockInjector
25
+ from app.shadow.interfaces import IMockInjector, IShadowRuntime, IShadowWorkspace, ISnapshotStore
26
+ from app.shadow.schemas import CapturedRequest, ShadowRunResult
27
+ from app.shadow.snapshot_store import SnapshotStore
28
+ from app.shadow.workspace import ShadowWorkspace
29
+
30
+ logger = structlog.get_logger(__name__)
31
+
32
+ SHADOW_PLACEHOLDER_MESSAGE = (
33
+ "Shadow Testing runtime is under development — no shadow logic runs yet."
34
+ )
35
+
36
+
37
+ def _get_free_port() -> int:
38
+ """Return an available TCP port by binding to port 0 and releasing it."""
39
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
40
+ s.bind(("", 0))
41
+ return cast(int, s.getsockname()[1])
42
+
43
+
44
+ def _fetch_ws_endpoint(port: int, timeout: float = 10.0) -> str:
45
+ """Fetch the Chrome DevTools websocket endpoint from a running Chromium debug port."""
46
+ url = f"http://localhost:{port}/json/version"
47
+ with urllib.request.urlopen(url, timeout=timeout) as resp: # noqa: S310
48
+ data = json.loads(resp.read().decode("utf-8"))
49
+ return cast(str, data["webSocketDebuggerUrl"])
50
+
51
+
52
+ class ShadowRuntime(IShadowRuntime):
53
+ """Minimal Shadow Runtime that manages a lifecycle and a :class:`ShadowContext`.
54
+
55
+ Collaborators are injected optionally so the runtime can be instantiated on
56
+ its own. :meth:`initialize` creates and activates a context; :meth:`shutdown`
57
+ deactivates and releases it. Both methods are idempotent.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ workspace: IShadowWorkspace | None = None,
63
+ snapshot_store: ISnapshotStore | None = None,
64
+ injector: IMockInjector | None = None,
65
+ ) -> None:
66
+ self.workspace = workspace
67
+ self.snapshot_store = snapshot_store
68
+ self.injector = injector
69
+ self._context: ShadowContext | None = None
70
+
71
+ @property
72
+ def context(self) -> ShadowContext | None:
73
+ """The active :class:`ShadowContext`, or ``None`` before initialization."""
74
+ return self._context
75
+
76
+ @property
77
+ def is_active(self) -> bool:
78
+ """Whether the runtime currently holds an active context."""
79
+ return self._context is not None and self._context.is_active
80
+
81
+ def initialize(self) -> None:
82
+ """Create and activate the shadow context.
83
+
84
+ Idempotent: calling it again while already active leaves the existing
85
+ context in place. Access the context via :attr:`context`.
86
+ """
87
+ if self.is_active:
88
+ logger.info("shadow_runtime_already_initialized")
89
+ return
90
+
91
+ self._context = ShadowContext(
92
+ workspace=self.workspace,
93
+ snapshot_store=self.snapshot_store,
94
+ injector=self.injector,
95
+ )
96
+ self._context.activate()
97
+ logger.info("shadow_runtime_initialized")
98
+
99
+ def shutdown(self) -> None:
100
+ """Deactivate and release the shadow context.
101
+
102
+ Idempotent: a no-op if the runtime was never initialized or is already
103
+ shut down.
104
+ """
105
+ if self._context is None:
106
+ logger.info("shadow_runtime_already_shutdown")
107
+ return
108
+
109
+ self._context.deactivate()
110
+ self._context = None
111
+ logger.info("shadow_runtime_shutdown")
112
+
113
+
114
+ def run_shadow(
115
+ test_path: str | Path | None = None,
116
+ snapshot_id: str | None = None,
117
+ config: ShadowConfig | None = None,
118
+ ) -> ShadowRunResult | str:
119
+ """Dedicated entry point for ``e2e-healer --shadow``.
120
+
121
+ When called without arguments (placeholder mode), exercises the minimal
122
+ runtime lifecycle (initialize → shutdown) and returns a human-readable
123
+ status message for the CLI to surface.
124
+
125
+ When called with a *test_path* and *snapshot_id*, orchestrates a full
126
+ Shadow Replay run:
127
+
128
+ 1. Load the saved :class:`ShadowSnapshot` from the :class:`SnapshotStore`.
129
+ 2. Launch a headless Chromium process with a remote-debugging port.
130
+ 3. Attach a Python :class:`MockInjector` that intercepts all network
131
+ requests and fulfils them from the snapshot data.
132
+ 4. Write a temporary Playwright config that connects Node.js tests to the
133
+ Python-controlled browser via ``connectOptions.wsEndpoint``.
134
+ 5. Run ``npx playwright test <test_path> --config <tmp_config>`` as a
135
+ subprocess.
136
+ 6. Collect matched / missed request counts and return a :class:`ShadowRunResult`.
137
+ """
138
+ if test_path is None or snapshot_id is None:
139
+ runtime = ShadowRuntime()
140
+ runtime.initialize()
141
+ runtime.shutdown()
142
+ return SHADOW_PLACEHOLDER_MESSAGE
143
+
144
+ test_path = Path(test_path)
145
+ assert_read_allowed(test_path)
146
+
147
+ cfg = config or ShadowConfig()
148
+ workspace = ShadowWorkspace(cfg)
149
+ store = SnapshotStore(workspace)
150
+ snapshot = store.get_snapshot(snapshot_id)
151
+
152
+ debug_port = _get_free_port()
153
+ is_success = False
154
+ config_path: Path | None = None
155
+
156
+ with sync_playwright() as p:
157
+ # Launch headless Chromium with a remote-debugging port so the
158
+ # Node.js Playwright process can connect to it via CDP/WS.
159
+ browser = p.chromium.launch(
160
+ headless=True,
161
+ args=[f"--remote-debugging-port={debug_port}"],
162
+ )
163
+ try:
164
+ # Obtain the WebSocket debugger URL from the CDP /json/version endpoint.
165
+ ws_endpoint = _fetch_ws_endpoint(debug_port)
166
+
167
+ # Attach a MockInjector to a fresh browser context so that every
168
+ # network request made by the test is intercepted and fulfilled from
169
+ # the snapshot data.
170
+ injector = MockInjector()
171
+ context = browser.new_context()
172
+ try:
173
+ injector.inject_mock(context, snapshot.network_snapshots)
174
+
175
+ # Write a temporary Playwright config that redirects Node.js to the
176
+ # Python-controlled browser via connectOptions.
177
+ config_file_name = "shadow_playwright.config.js"
178
+ config_content = f"""module.exports = {{
179
+ use: {{
180
+ connectOptions: {{
181
+ wsEndpoint: "{ws_endpoint}",
182
+ }}
183
+ }}
184
+ }};
185
+ """
186
+
187
+ config_path = workspace.tmp_path(config_file_name)
188
+ assert_write_allowed(config_path, reason="shadow_playwright_config")
189
+ config_path.write_text(config_content, encoding="utf-8")
190
+
191
+ # Build the subprocess command.
192
+ cmd_parts = shlex.split(settings.playwright_cmd)
193
+ cmd = [*cmd_parts, str(test_path), "--config", str(config_path)]
194
+ # On Windows, `npx` is a .cmd wrapper that must be invoked explicitly.
195
+ if os.name == "nt" and cmd and cmd[0] == "npx":
196
+ cmd[0] = "npx.cmd"
197
+ assert_command_allowed(cmd, reason="shadow_playwright_test")
198
+
199
+ env = os.environ.copy()
200
+ env["PLAYWRIGHT_WS_ENDPOINT"] = ws_endpoint
201
+
202
+ logger.info("shadow_playwright_run_started", cmd=cmd)
203
+ proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
204
+ is_success = proc.returncode == 0
205
+ logger.info(
206
+ "shadow_playwright_run_finished",
207
+ passed=is_success,
208
+ returncode=proc.returncode,
209
+ )
210
+ finally:
211
+ context.close()
212
+ finally:
213
+ browser.close()
214
+ if config_path is not None:
215
+ config_path.unlink(missing_ok=True)
216
+ workspace.cleanup(is_success=is_success)
217
+
218
+ # Compute replay result summary.
219
+ matched_count = len(injector.matched_requests)
220
+ missed_requests: list[CapturedRequest] = list(injector.unmatched_requests)
221
+ missed_count = len(missed_requests)
222
+ total_requests = matched_count + missed_count
223
+ avg_score = 0.0
224
+ if total_requests > 0:
225
+ avg_score = sum(s for _, s in injector.matched_requests) / total_requests
226
+
227
+ return ShadowRunResult(
228
+ is_success=is_success,
229
+ matched_count=matched_count,
230
+ missed_count=missed_count,
231
+ missed_requests=missed_requests,
232
+ score=avg_score,
233
+ )
app/shadow/schemas.py ADDED
@@ -0,0 +1,62 @@
1
+ """Pydantic schemas for the Shadow Runtime network mock capturing and replay."""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class CapturedRequest(BaseModel):
9
+ """Schema representing an intercepted outgoing request."""
10
+
11
+ method: str
12
+ url: str
13
+ headers: dict[str, str] = Field(default_factory=dict)
14
+ body: str | None = None
15
+
16
+
17
+ class CapturedResponse(BaseModel):
18
+ """Schema representing the captured HTTP response to replay."""
19
+
20
+ status: int
21
+ headers: dict[str, str] = Field(default_factory=dict)
22
+ body: str | None = None
23
+ is_base64: bool = False
24
+
25
+
26
+ class NetworkSnapshot(BaseModel):
27
+ """A pair of captured request and response representing a single network interaction."""
28
+
29
+ request: CapturedRequest
30
+ response: CapturedResponse
31
+ sequence: int | None = None # ordering index within the trace
32
+ started_at: float | None = None # request start, epoch seconds
33
+ duration_ms: float | None = None # request→response duration in ms
34
+
35
+
36
+ class SnapshotMetadata(BaseModel):
37
+ """Optional typed view of ShadowSnapshot.metadata; the field itself stays a
38
+ permissive dict, so arbitrary keys still round-trip untouched."""
39
+
40
+ model_config = {"extra": "allow"}
41
+
42
+ source_url: str | None = None # page URL the trace was captured from
43
+ captured_at: float | None = None # capture time, epoch seconds
44
+ event_count: int | None = None # number of network events in the trace
45
+
46
+
47
+ class ShadowSnapshot(BaseModel):
48
+ """Container representing a fully serialized/persisted application state for replay."""
49
+
50
+ snapshot_id: str
51
+ metadata: dict[str, Any] = Field(default_factory=dict)
52
+ network_snapshots: list[NetworkSnapshot] = Field(default_factory=list)
53
+
54
+
55
+ class ShadowRunResult(BaseModel):
56
+ """Result of a Shadow Replay execution run."""
57
+
58
+ is_success: bool
59
+ matched_count: int = 0
60
+ missed_count: int = 0
61
+ missed_requests: list[CapturedRequest] = Field(default_factory=list)
62
+ score: float = 0.0
app/shadow/scoring.py ADDED
@@ -0,0 +1,114 @@
1
+ """Scoring engine to compute similarity between incoming and captured network requests."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from app.shadow.normalizer import RequestNormalizer
7
+ from app.shadow.schemas import CapturedRequest
8
+
9
+
10
+ @dataclass
11
+ class ScoringWeights:
12
+ """Weights configuration for request similarity scoring."""
13
+
14
+ exact_url_bonus: float = 150.0
15
+ base_url_match: float = 100.0
16
+ query_max: float = 30.0
17
+ headers_max: float = 20.0
18
+ body_max: float = 50.0
19
+
20
+
21
+ class MatchScorer:
22
+ """Calculates a similarity score between two captured requests.
23
+
24
+ Higher scores indicate a better match. A score of -1.0 means incompatible.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ normalizer: RequestNormalizer | None = None,
30
+ weights: ScoringWeights | None = None,
31
+ ):
32
+ self.normalizer = normalizer or RequestNormalizer()
33
+ self.weights = weights or ScoringWeights()
34
+
35
+ def calculate_score(self, req1: CapturedRequest, req2: CapturedRequest) -> float:
36
+ """Calculates a similarity score.
37
+
38
+ Returns -1.0 if the requests are incompatible (different method or non-matching paths).
39
+ """
40
+ # 1. HTTP Method must match exactly (case-insensitive)
41
+ if req1.method.upper() != req2.method.upper():
42
+ return -1.0
43
+
44
+ # Normalize path and query
45
+ path1, query1 = self.normalizer.normalize_url(req1.url)
46
+ path2, query2 = self.normalizer.normalize_url(req2.url)
47
+
48
+ # 2. Path Match check
49
+ if path1 != path2:
50
+ return -1.0
51
+
52
+ score = 0.0
53
+
54
+ # High bonus for exact URL match (including all query parameters)
55
+ if req1.url == req2.url:
56
+ score += self.weights.exact_url_bonus
57
+ else:
58
+ score += self.weights.base_url_match
59
+
60
+ # 3. Query Parameters Match (up to query_max points)
61
+ if not query1 and not query2:
62
+ score += self.weights.query_max
63
+ elif query1 and query2:
64
+ all_keys = set(query1.keys()).union(query2.keys())
65
+ matching_keys = set(query1.keys()).intersection(query2.keys())
66
+ match_count = 0
67
+ for k in matching_keys:
68
+ if sorted(query1[k]) == sorted(query2[k]):
69
+ match_count += 1
70
+ if all_keys:
71
+ score += (match_count / len(all_keys)) * self.weights.query_max
72
+
73
+ # 4. Headers Match (up to headers_max points)
74
+ headers1 = self.normalizer.normalize_headers(req1.headers)
75
+ headers2 = self.normalizer.normalize_headers(req2.headers)
76
+
77
+ if not headers1 and not headers2:
78
+ score += self.weights.headers_max
79
+ elif headers1 and headers2:
80
+ all_keys = set(headers1.keys()).union(headers2.keys())
81
+ matching_keys = set(headers1.keys()).intersection(headers2.keys())
82
+ match_count = 0
83
+ for k in matching_keys:
84
+ if headers1[k] == headers2[k]:
85
+ match_count += 1
86
+ if all_keys:
87
+ score += (match_count / len(all_keys)) * self.weights.headers_max
88
+
89
+ # 5. Request Body Match (up to body_max points)
90
+ body1_norm = self.normalizer.normalize_body(req1.body)
91
+ body2_norm = self.normalizer.normalize_body(req2.body)
92
+
93
+ if not body1_norm and not body2_norm:
94
+ score += self.weights.body_max
95
+ elif body1_norm and body2_norm:
96
+ if body1_norm == body2_norm:
97
+ score += self.weights.body_max
98
+ elif isinstance(body1_norm, dict) and isinstance(body2_norm, dict):
99
+ dict_score = self._compare_normalized_dicts(body1_norm, body2_norm)
100
+ score += dict_score * self.weights.body_max
101
+
102
+ return score
103
+
104
+ def _compare_normalized_dicts(self, d1: dict[str, Any], d2: dict[str, Any]) -> float:
105
+ """Returns a similarity ratio between 0.0 and 1.0 for two normalized dictionaries."""
106
+ all_keys = set(d1.keys()).union(d2.keys())
107
+ if not all_keys:
108
+ return 1.0
109
+ matching_keys = set(d1.keys()).intersection(d2.keys())
110
+ match_count = 0
111
+ for k in matching_keys:
112
+ if d1[k] == d2[k]:
113
+ match_count += 1
114
+ return match_count / len(all_keys)
@@ -0,0 +1,106 @@
1
+ """Persistent storage layer for Shadow Runtime snapshots."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import structlog
8
+
9
+ from app.shadow.interfaces import ISnapshotStore
10
+ from app.shadow.schemas import ShadowSnapshot
11
+ from app.shadow.workspace import ShadowWorkspace
12
+
13
+ logger = structlog.get_logger(__name__)
14
+
15
+
16
+ class SnapshotStoreError(Exception):
17
+ """Base exception for SnapshotStore errors."""
18
+
19
+ pass
20
+
21
+
22
+ class SnapshotNotFoundError(SnapshotStoreError):
23
+ """Raised when a snapshot is not found on disk."""
24
+
25
+ pass
26
+
27
+
28
+ class SnapshotCorruptionError(SnapshotStoreError):
29
+ """Raised when a snapshot file is corrupted or invalid."""
30
+
31
+ pass
32
+
33
+
34
+ class SnapshotStore(ISnapshotStore):
35
+ """Persistent storage layer for Shadow Runtime snapshots.
36
+
37
+ Serializes and deserializes ShadowSnapshot objects to/from JSON files
38
+ inside a workspace's snapshots directory.
39
+ """
40
+
41
+ def __init__(self, workspace: ShadowWorkspace):
42
+ self.workspace = workspace
43
+ # Ensure snapshots directory exists
44
+ self.workspace.snapshots_dir.mkdir(parents=True, exist_ok=True)
45
+
46
+ def _get_snapshot_path(self, snapshot_id: str) -> Path:
47
+ """Returns the absolute file path for a given snapshot ID."""
48
+ # Clean snapshot_id to prevent directory traversal
49
+ safe_id = Path(snapshot_id).name
50
+ return self.workspace.snapshots_dir / f"{safe_id}.json"
51
+
52
+ def save_snapshot(self, snapshot_id: str, data: Any) -> None:
53
+ """Persists a ShadowSnapshot object (or dict) to a JSON file on disk."""
54
+ path = self._get_snapshot_path(snapshot_id)
55
+
56
+ # If it's a ShadowSnapshot object, convert to dict/JSON
57
+ if isinstance(data, ShadowSnapshot):
58
+ snapshot_dict = data.model_dump()
59
+ elif isinstance(data, dict):
60
+ # Try to validate/parse to ensure correctness before saving
61
+ try:
62
+ ShadowSnapshot(**data)
63
+ except Exception as e:
64
+ raise SnapshotStoreError(f"Invalid snapshot dict structure: {e}")
65
+ snapshot_dict = data
66
+ else:
67
+ raise SnapshotStoreError("Unsupported data type; expected ShadowSnapshot or dict")
68
+
69
+ try:
70
+ # Deterministic serialization: sort keys, indent for readability
71
+ serialized = json.dumps(snapshot_dict, sort_keys=True, indent=2)
72
+ path.write_text(serialized, encoding="utf-8")
73
+ logger.info("snapshot_saved", snapshot_id=snapshot_id, path=str(path))
74
+ except Exception as e:
75
+ raise SnapshotStoreError(f"Failed to write snapshot to disk: {e}")
76
+
77
+ def get_snapshot(self, snapshot_id: str) -> ShadowSnapshot:
78
+ """Loads and deserializes a ShadowSnapshot from disk."""
79
+ path = self._get_snapshot_path(snapshot_id)
80
+
81
+ if not path.exists():
82
+ logger.warning("snapshot_not_found", snapshot_id=snapshot_id, path=str(path))
83
+ raise SnapshotNotFoundError(f"Snapshot '{snapshot_id}' does not exist at {path}")
84
+
85
+ try:
86
+ content = path.read_text(encoding="utf-8")
87
+ except Exception as e:
88
+ raise SnapshotStoreError(f"Failed to read snapshot file: {e}")
89
+
90
+ try:
91
+ snapshot_dict = json.loads(content)
92
+ except json.JSONDecodeError as e:
93
+ logger.error(
94
+ "snapshot_file_corrupted", snapshot_id=snapshot_id, path=str(path), error=str(e)
95
+ )
96
+ raise SnapshotCorruptionError(f"Snapshot file is not valid JSON: {e}")
97
+
98
+ try:
99
+ return ShadowSnapshot(**snapshot_dict)
100
+ except Exception as e:
101
+ logger.error(
102
+ "snapshot_data_invalid", snapshot_id=snapshot_id, path=str(path), error=str(e)
103
+ )
104
+ raise SnapshotCorruptionError(
105
+ f"Snapshot data does not conform to ShadowSnapshot schema: {e}"
106
+ )