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,201 @@
1
+ """Diff-JSX AST Analyzer: turn a git diff into before/after DOM node trees.
2
+
3
+ Uses tree-sitter (tree-sitter-typescript) for robust JSX/TSX element and attribute
4
+ extraction, with a regex-based fallback if tree-sitter is unavailable.
5
+ """
6
+
7
+ import importlib.util
8
+ import re
9
+ import structlog
10
+ from app.schemas import DomDiff
11
+
12
+ logger = structlog.get_logger(__name__)
13
+
14
+ _FILE_RE = re.compile(r"^\+\+\+ b/(.+)$")
15
+ _JSX_TAG_RE = re.compile(
16
+ r"<([A-Za-z][\w.]*)((?:\s+[\w-]+=(?:\"[^\"]*\"|'[^']*'|\{[^}]*\}))*)\s*/?>"
17
+ )
18
+ _ATTR_RE = re.compile(r"([\w-]+)=(?:\"([^\"]*)\"|'([^']*)'|\{([^}]*)\})")
19
+ _JSX_SUFFIXES = (".tsx", ".jsx")
20
+
21
+ _HAS_TREE_SITTER = (
22
+ importlib.util.find_spec("tree_sitter") is not None
23
+ and importlib.util.find_spec("tree_sitter_typescript") is not None
24
+ )
25
+
26
+
27
+ def _parse_element_regex(line: str) -> dict | None:
28
+ tag_match = _JSX_TAG_RE.search(line)
29
+ if not tag_match:
30
+ return None
31
+ attrs: dict[str, str] = {}
32
+ for attr_match in _ATTR_RE.finditer(tag_match.group(2)):
33
+ name = attr_match.group(1)
34
+ value = attr_match.group(2) or attr_match.group(3) or attr_match.group(4) or ""
35
+ attrs[name] = value
36
+ return {"tag": tag_match.group(1), "attributes": attrs}
37
+
38
+
39
+ def _analyze_diff_regex(git_diff: str) -> list[DomDiff]:
40
+ diffs: list[DomDiff] = []
41
+ current_file = ""
42
+ removed: list[dict] = []
43
+ added: list[dict] = []
44
+
45
+ def flush(file: str) -> None:
46
+ for previous, current in zip(removed, added):
47
+ diffs.append(DomDiff(file=file, previous=previous, current=current))
48
+ removed.clear()
49
+ added.clear()
50
+
51
+ for line in git_diff.splitlines():
52
+ file_match = _FILE_RE.match(line)
53
+ if file_match:
54
+ flush(current_file)
55
+ current_file = file_match.group(1)
56
+ continue
57
+ if not current_file.endswith(_JSX_SUFFIXES):
58
+ continue
59
+ if line.startswith("-") and not line.startswith("---"):
60
+ element = _parse_element_regex(line[1:])
61
+ if element:
62
+ removed.append(element)
63
+ elif line.startswith("+") and not line.startswith("+++"):
64
+ element = _parse_element_regex(line[1:])
65
+ if element:
66
+ added.append(element)
67
+ flush(current_file)
68
+ return diffs
69
+
70
+
71
+ def _extract_jsx_elements_tree_sitter(code_bytes: bytes) -> list[dict]:
72
+ if not _HAS_TREE_SITTER:
73
+ return []
74
+
75
+ import tree_sitter_typescript as ts_typescript
76
+ from tree_sitter import Language, Parser
77
+
78
+ tsx_language = Language(ts_typescript.language_tsx())
79
+ parser = Parser(tsx_language)
80
+ tree = parser.parse(code_bytes)
81
+ elements = []
82
+
83
+ def walk(node):
84
+ if node.type in ("jsx_opening_element", "jsx_self_closing_element"):
85
+ tag = ""
86
+ for child in node.children:
87
+ if child.type in (
88
+ "identifier",
89
+ "member_expression",
90
+ "nested_identifier",
91
+ "jsx_namespace_name",
92
+ "jsx_identifier",
93
+ "jsx_member_expression",
94
+ ):
95
+ tag = code_bytes[child.start_byte : child.end_byte].decode(
96
+ "utf-8", errors="ignore"
97
+ )
98
+ break
99
+
100
+ attrs = {}
101
+ for child in node.children:
102
+ if child.type == "jsx_attribute":
103
+ name = ""
104
+ value = ""
105
+ for attr_child in child.children:
106
+ if attr_child.type in ("property_identifier", "jsx_namespace_name"):
107
+ name = code_bytes[attr_child.start_byte : attr_child.end_byte].decode(
108
+ "utf-8", errors="ignore"
109
+ )
110
+ elif attr_child.type == "string":
111
+ val_text = code_bytes[
112
+ attr_child.start_byte : attr_child.end_byte
113
+ ].decode("utf-8", errors="ignore")
114
+ if val_text.startswith(('"', "'")) and val_text.endswith(('"', "'")):
115
+ value = val_text[1:-1]
116
+ else:
117
+ value = val_text
118
+ elif attr_child.type == "jsx_expression":
119
+ val_text = code_bytes[
120
+ attr_child.start_byte : attr_child.end_byte
121
+ ].decode("utf-8", errors="ignore")
122
+ if val_text.startswith("{") and val_text.endswith("}"):
123
+ value = val_text[1:-1]
124
+ else:
125
+ value = val_text
126
+ if name:
127
+ attrs[name] = value
128
+
129
+ elements.append({"tag": tag, "attributes": attrs})
130
+ for child in node.children:
131
+ walk(child)
132
+
133
+ walk(tree.root_node)
134
+ return elements
135
+
136
+
137
+ def _analyze_diff_tree_sitter(git_diff: str) -> list[DomDiff]:
138
+ diffs: list[DomDiff] = []
139
+ current_file = ""
140
+ hunks = []
141
+
142
+ current_removed = []
143
+ current_added = []
144
+
145
+ def flush_hunk(file: str) -> None:
146
+ if current_removed or current_added:
147
+ rem_str = "\n".join(current_removed)
148
+ add_str = "\n".join(current_added)
149
+ hunks.append((rem_str, add_str))
150
+ current_removed.clear()
151
+ current_added.clear()
152
+
153
+ def process_file_hunks(file: str) -> None:
154
+ flush_hunk(file)
155
+ for rem_str, add_str in hunks:
156
+ rem_elements = _extract_jsx_elements_tree_sitter(rem_str.encode("utf-8"))
157
+ add_elements = _extract_jsx_elements_tree_sitter(add_str.encode("utf-8"))
158
+ for prev, curr in zip(rem_elements, add_elements):
159
+ diffs.append(DomDiff(file=file, previous=prev, current=curr))
160
+ hunks.clear()
161
+
162
+ for line in git_diff.splitlines():
163
+ file_match = _FILE_RE.match(line)
164
+ if file_match:
165
+ process_file_hunks(current_file)
166
+ current_file = file_match.group(1)
167
+ continue
168
+
169
+ if not current_file.endswith(_JSX_SUFFIXES):
170
+ continue
171
+
172
+ if line.startswith("-") and not line.startswith("---"):
173
+ current_removed.append(line[1:])
174
+ elif line.startswith("+") and not line.startswith("+++"):
175
+ current_added.append(line[1:])
176
+ elif line.startswith(" "):
177
+ flush_hunk(current_file)
178
+ elif line.startswith("@@"):
179
+ flush_hunk(current_file)
180
+
181
+ process_file_hunks(current_file)
182
+ return diffs
183
+
184
+
185
+ def analyze_diff(git_diff: str) -> list[DomDiff]:
186
+ """Parse the JSX/TSX regions of a git diff into lightweight DOM diffs.
187
+
188
+ Uses Tree-sitter if available to pair changed elements, and falls back to
189
+ regex line pairing on import or parsing failures.
190
+ """
191
+ if _HAS_TREE_SITTER:
192
+ try:
193
+ diffs = _analyze_diff_tree_sitter(git_diff)
194
+ logger.debug("diff_analyzed_tree_sitter", dom_changes=len(diffs))
195
+ return diffs
196
+ except Exception as exc:
197
+ logger.warning("tree_sitter_diff_analysis_failed_falling_back", error=str(exc))
198
+
199
+ diffs = _analyze_diff_regex(git_diff)
200
+ logger.debug("diff_analyzed_regex", dom_changes=len(diffs))
201
+ return diffs
@@ -0,0 +1,52 @@
1
+ """Error Log Parser: distill a full Playwright log into the core failure reason."""
2
+
3
+ import re
4
+
5
+ import structlog
6
+
7
+ logger = structlog.get_logger(__name__)
8
+
9
+ # The `Error:` line carrying the core reason (e.g. `Error: locator.click: Timeout ...`).
10
+ _ERROR_RE = re.compile(r"^\s*(Error:.*)$", re.MULTILINE)
11
+ # A test-file source location, e.g. `tests/example.spec.ts:12:34`.
12
+ _LOCATION_RE = re.compile(r"([\w./-]+\.(?:spec|test)\.[jt]sx?):(\d+):(\d+)")
13
+ # The stack-trace failing line, e.g. `at tests/example.spec.ts:12:9` — the line to patch,
14
+ # preferred over the test-header location that appears earlier in the log.
15
+ _AT_LOCATION_RE = re.compile(r"\bat\s+([\w./-]+\.(?:spec|test)\.[jt]sx?):(\d+):(\d+)")
16
+ # Playwright call-log lines, e.g. `- waiting for locator('#submit-btn')`.
17
+ _WAITING_RE = re.compile(r"waiting for (.+)")
18
+
19
+
20
+ def parse_error_log(raw_log: str | None) -> str:
21
+ """Extract only the essentials from a raw Playwright failure log.
22
+
23
+ Keeps the ``Error:`` reason, the failing source location, and up to three call-log
24
+ ``waiting for ...`` lines. Falls back to the trimmed tail of the log if nothing
25
+ matches, so the Diagnoser always gets *something* to work with.
26
+ """
27
+ if not raw_log:
28
+ return ""
29
+
30
+ parts: list[str] = []
31
+
32
+ error_match = _ERROR_RE.search(raw_log)
33
+ if error_match:
34
+ parts.append(error_match.group(1).strip())
35
+
36
+ # Prefer the stack-trace `at ...` line (the actual failing line) over the earlier
37
+ # test-header location, so the Diagnoser points the patch at the right line.
38
+ loc_match = _AT_LOCATION_RE.search(raw_log) or _LOCATION_RE.search(raw_log)
39
+ if loc_match:
40
+ parts.append(f"at {loc_match.group(1)}:{loc_match.group(2)}")
41
+
42
+ waiting = [w.strip() for w in _WAITING_RE.findall(raw_log)]
43
+ if waiting:
44
+ parts.append("call log: " + "; ".join(waiting[:3]))
45
+
46
+ result = "\n".join(parts)
47
+ if not result:
48
+ logger.warning("error_log_parse_fell_back_to_tail")
49
+ result = raw_log.strip()[-1000:]
50
+
51
+ logger.debug("error_log_parsed", chars=len(result))
52
+ return result
@@ -0,0 +1,32 @@
1
+ """Scan a whole-suite Playwright log for the distinct test files that failed.
2
+
3
+ Playwright's reporter lists each failure as a numbered entry, optionally prefixed with a
4
+ project tag, e.g.::
5
+
6
+ 1) [chromium] › tests/login.spec.ts:12:3 › user can log in
7
+ 2) example.spec.ts:7:5 › submits the form
8
+
9
+ We extract the failing test-file paths (deduplicated, in first-seen order) so the suite
10
+ healer can repair each one.
11
+ """
12
+
13
+ import re
14
+
15
+ import structlog
16
+
17
+ logger = structlog.get_logger(__name__)
18
+
19
+ # A numbered failure entry; capture the first test-file path on the line.
20
+ _FAILURE_RE = re.compile(
21
+ r"^\s*\d+\)\s+.*?((?:[a-zA-Z]:)?[\w./\\-]+\.(?:spec|test)\.[jt]sx?):\d+", re.MULTILINE
22
+ )
23
+
24
+
25
+ def scan_failing_tests(raw_log: str) -> list[str]:
26
+ """Return distinct failing test-file paths from a whole-suite Playwright log."""
27
+ seen: dict[str, None] = {} # dict preserves first-seen order while deduping
28
+ for match in _FAILURE_RE.finditer(raw_log):
29
+ seen.setdefault(match.group(1), None)
30
+ paths = list(seen)
31
+ logger.info("failing_tests_scanned", count=len(paths))
32
+ return paths
@@ -0,0 +1 @@
1
+ """System prompts for the agent nodes."""
@@ -0,0 +1,11 @@
1
+ """System prompt for the Diagnoser node."""
2
+
3
+ SYSTEM_PROMPT = (
4
+ "You are an expert Playwright E2E test debugger. You are given a failure log, the "
5
+ "DOM changes from a git diff (before/after tag + attributes), an optional ARIA page "
6
+ "snapshot captured at failure time, and the current test code. Explain concisely WHY "
7
+ "the test broke: identify which selector/locator failed and which DOM attribute change "
8
+ "(id, className, data-testid, role, name) caused it. Use the ARIA snapshot to correlate "
9
+ "the failing selector with what was actually on the page. Output a short diagnosis only "
10
+ "— do NOT write code."
11
+ )
@@ -0,0 +1,14 @@
1
+ """System prompt for the Patch Generator node (carries the code-integrity guardrail)."""
2
+
3
+ SYSTEM_PROMPT = (
4
+ "You repair Playwright E2E tests. You may ONLY fix failing locators (selectors) and "
5
+ "optimize wait conditions. You must NEVER change assertions, test flow, or business "
6
+ "logic. For each edit, return the 1-based line number, the exact original line, the "
7
+ "replacement line, and a short reason. When the edit changes a locator, also return "
8
+ "'selector' as a Playwright selector-engine string usable by page.locator() (e.g. "
9
+ "'#submit', 'role=button[name=\"Submit\"]', 'text=Submit') matching the new locator, so "
10
+ "it can be verified against the live DOM; leave 'selector' empty for non-locator edits "
11
+ "such as wait tweaks. If a prior attempt is reported as rejected in the diagnosis, do NOT "
12
+ "reuse the rejected selector — pick a different, more specific one. Return edits strictly "
13
+ "via the provided schema; if no selector/wait fix is warranted, return an empty list."
14
+ )
@@ -0,0 +1,18 @@
1
+ """System prompt for the Reviewer node (review mode — advisory, source-level fixes)."""
2
+
3
+ SYSTEM_PROMPT = (
4
+ "You are a senior code reviewer for Playwright E2E tests. You are given a failure "
5
+ "diagnosis, the DOM changes from a git diff (before/after tag + attributes, with the "
6
+ "new-file line number of each change), and the current test code. Your job is NOT to "
7
+ "rewrite the test — it is to advise how to fix the ROOT CAUSE in the source so the UI "
8
+ "and its tests stay robust. For each broken locator, produce one finding: the source "
9
+ "'file' and 'line' that changed (from the DOM changes), the 'broken_selector' from the "
10
+ "test, the 'root_cause' (which attribute change — id, className, data-testid, role, name "
11
+ "— broke it), and a 'suggestion' that prefers a STABLE, accessible contract over a "
12
+ "brittle one: add or keep a semantic role/accessible name, add a stable 'data-testid', "
13
+ "and avoid coupling tests to volatile classNames or auto-generated ids. In "
14
+ "'recommended_selector', give the accessibility-first Playwright locator the test should "
15
+ "use (e.g. getByRole('button', { name: 'Submit' }) or getByTestId('submit')). Set "
16
+ "'severity' to 'warning' when the change silently breaks a test, else 'info'. Return "
17
+ "findings strictly via the provided schema; if nothing is actionable, return an empty list."
18
+ )
app/runner.py ADDED
@@ -0,0 +1,31 @@
1
+ """Shared Playwright execution helper.
2
+
3
+ Used both by the CLI's initial failure capture and by the Test Runner node, so the
4
+ subprocess invocation lives in exactly one place.
5
+ """
6
+
7
+ import shlex
8
+ import subprocess
9
+
10
+ import structlog
11
+
12
+ from app.config import settings
13
+ from app.sandbox import assert_command_allowed
14
+
15
+ logger = structlog.get_logger(__name__)
16
+
17
+
18
+ def run_playwright(test_path: str = "") -> tuple[bool, str]:
19
+ """Run Playwright against a single test file, or the whole suite if ``test_path`` is empty.
20
+
21
+ Returns ``(passed, combined_log)`` where stdout and stderr are merged so the
22
+ Error Log Parser sees the full failure output.
23
+ """
24
+ cmd = [*shlex.split(settings.playwright_cmd), *([test_path] if test_path else [])]
25
+ assert_command_allowed(cmd, reason="playwright")
26
+ logger.info("playwright_run_started", cmd=cmd)
27
+ result = subprocess.run(cmd, capture_output=True, text=True)
28
+ passed = result.returncode == 0
29
+ log = result.stdout + result.stderr
30
+ logger.info("playwright_run_finished", passed=passed, returncode=result.returncode)
31
+ return passed, log
app/sandbox.py ADDED
@@ -0,0 +1,130 @@
1
+ """Sandbox policy for filesystem and subprocess access."""
2
+
3
+ from fnmatch import fnmatchcase
4
+ from pathlib import Path
5
+
6
+ from app.config import settings
7
+
8
+ _MODES = {"strict", "relaxed", "off"}
9
+ _SHELL_TOKENS = {"&&", "||", ";", "|", ">", ">>", "<", "$(", "`"}
10
+ _SHELL_TOKEN_FRAGMENTS = ("$(", "`")
11
+ _TEMP_HELPER = ".e2e-healer-verify.mjs"
12
+
13
+
14
+ class SandboxViolation(PermissionError):
15
+ """Raised when a path or command falls outside the configured sandbox."""
16
+
17
+
18
+ def sandbox_mode() -> str:
19
+ """Return the normalized sandbox mode, failing closed on invalid config."""
20
+ mode = settings.sandbox_mode.strip().lower()
21
+ if mode not in _MODES:
22
+ raise SandboxViolation(f"invalid sandbox mode: {settings.sandbox_mode}")
23
+ return mode
24
+
25
+
26
+ def workspace_root() -> Path:
27
+ """Return the resolved workspace root for strict sandbox checks."""
28
+ return Path(settings.workspace_root).expanduser().resolve()
29
+
30
+
31
+ def assert_read_allowed(path: Path) -> None:
32
+ """Allow reads unless strict root checks or deny globs reject the path."""
33
+ if sandbox_mode() == "off":
34
+ return
35
+
36
+ resolved = _resolve(path)
37
+ _assert_not_denied(resolved)
38
+ if sandbox_mode() == "strict":
39
+ _assert_inside_workspace(resolved)
40
+
41
+
42
+ def assert_write_allowed(path: Path, reason: str = "write") -> None:
43
+ """Allow writes only inside the configured policy."""
44
+ if sandbox_mode() == "off":
45
+ return
46
+
47
+ resolved = _resolve(path)
48
+ _assert_not_denied(resolved)
49
+
50
+ mode = sandbox_mode()
51
+ if mode == "strict":
52
+ _assert_inside_workspace(resolved)
53
+ if _is_allowed_temp_helper(resolved):
54
+ return
55
+ if not _matches_any(_write_match_value(resolved), _patterns(settings.write_globs)):
56
+ raise SandboxViolation(f"write denied by sandbox globs: {path}")
57
+
58
+ if reason == "selector_verifier_helper" and not _is_allowed_temp_helper(resolved):
59
+ raise SandboxViolation(f"unexpected helper write target: {path}")
60
+
61
+
62
+ def assert_command_allowed(argv: list[str], reason: str = "subprocess") -> None:
63
+ """Reject command arguments that look like shell control syntax."""
64
+ if sandbox_mode() == "off":
65
+ return
66
+ if not argv:
67
+ raise SandboxViolation(f"empty command denied: {reason}")
68
+ for arg in argv:
69
+ if (
70
+ arg in _SHELL_TOKENS
71
+ or arg.endswith(";")
72
+ or any(token in arg for token in _SHELL_TOKEN_FRAGMENTS)
73
+ ):
74
+ raise SandboxViolation(f"shell-like command token denied: {arg}")
75
+
76
+
77
+ def _resolve(path: Path) -> Path:
78
+ return path.expanduser().resolve()
79
+
80
+
81
+ def _assert_inside_workspace(path: Path) -> None:
82
+ root = workspace_root()
83
+ try:
84
+ path.relative_to(root)
85
+ except ValueError as exc:
86
+ raise SandboxViolation(f"path outside workspace: {path}") from exc
87
+
88
+
89
+ def _relative_to_workspace(path: Path) -> str:
90
+ return path.relative_to(workspace_root()).as_posix()
91
+
92
+
93
+ def _write_match_value(path: Path) -> str:
94
+ try:
95
+ return _relative_to_workspace(path)
96
+ except ValueError:
97
+ return path.name
98
+
99
+
100
+ def _assert_not_denied(path: Path) -> None:
101
+ rel = _relative_or_name(path)
102
+ if _matches_any(rel, _patterns(settings.deny_globs)):
103
+ raise SandboxViolation(f"path denied by sandbox: {path}")
104
+ denied_dirs = {".git", ".github", ".venv", "node_modules"}
105
+ if denied_dirs.intersection(path.parts):
106
+ raise SandboxViolation(f"path denied by sandbox: {path}")
107
+
108
+
109
+ def _relative_or_name(path: Path) -> str:
110
+ try:
111
+ return path.relative_to(workspace_root()).as_posix()
112
+ except ValueError:
113
+ return path.name
114
+
115
+
116
+ def _patterns(raw: str) -> list[str]:
117
+ return [pattern.strip() for pattern in raw.split(",") if pattern.strip()]
118
+
119
+
120
+ def _matches_any(value: str, patterns: list[str]) -> bool:
121
+ for pattern in patterns:
122
+ if fnmatchcase(value, pattern):
123
+ return True
124
+ if pattern.startswith("**/") and fnmatchcase(value, pattern[3:]):
125
+ return True
126
+ return False
127
+
128
+
129
+ def _is_allowed_temp_helper(path: Path) -> bool:
130
+ return settings.allow_temp_helper and path.name == _TEMP_HELPER
app/schemas.py ADDED
@@ -0,0 +1,99 @@
1
+ """Pydantic models: structured LLM output and machine-readable CI results."""
2
+
3
+ from typing import Literal
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class DomDiff(BaseModel):
9
+ """A single before/after DOM node change parsed from a git diff."""
10
+
11
+ file: str
12
+ line: int = Field(
13
+ default=0,
14
+ description="1-based line in the new file where the changed element sits (0 if unknown)",
15
+ )
16
+ previous: dict = Field(default_factory=dict, description="DOM node before the change")
17
+ current: dict = Field(default_factory=dict, description="DOM node after the change")
18
+
19
+
20
+ class PatchInstruction(BaseModel):
21
+ """A single targeted edit produced by the Patch Generator.
22
+
23
+ Scope is intentionally narrow: only failing locators and wait conditions.
24
+ """
25
+
26
+ line: int = Field(..., description="1-based line number to replace")
27
+ original: str = Field(..., description="the exact line being replaced")
28
+ replacement: str = Field(..., description="the new line content")
29
+ reason: str = Field(..., description="why this selector/wait was changed")
30
+ selector: str = Field(
31
+ default="",
32
+ description=(
33
+ "the new locator as a Playwright selector-engine string usable by page.locator() "
34
+ "(e.g. '#submit', 'role=button[name=\"Submit\"]', 'text=Submit'), for live-DOM "
35
+ "verification. Empty if this edit is not a selector change (e.g. a wait tweak)."
36
+ ),
37
+ )
38
+
39
+
40
+ class PatchOutput(BaseModel):
41
+ """Structured Output schema the LLM is forced to return (no free-form rewrites)."""
42
+
43
+ instructions: list[PatchInstruction]
44
+
45
+
46
+ class RepairSummary(BaseModel):
47
+ """Machine-readable result emitted for the CI wrapper to consume."""
48
+
49
+ test_script_path: str
50
+ is_success: bool
51
+ loop_count: int
52
+ instructions: list[PatchInstruction] = Field(default_factory=list)
53
+
54
+
55
+ class SuiteSummary(BaseModel):
56
+ """Aggregate result when healing a whole suite (multiple failing tests)."""
57
+
58
+ total_failed: int
59
+ healed: int
60
+ is_success: bool # every failing test was healed
61
+ results: list[RepairSummary] = Field(default_factory=list)
62
+
63
+
64
+ class ReviewFinding(BaseModel):
65
+ """A single source-level suggestion produced by the Reviewer (review mode).
66
+
67
+ Advisory only: the review mode never edits the test. A finding anchors to the changed
68
+ *source* file/line so the CI wrapper can post it as an inline PR comment.
69
+ """
70
+
71
+ file: str = Field(..., description="source file that changed (e.g. components/CTAButton.tsx)")
72
+ line: int = Field(..., description="1-based line in the new source file to comment on")
73
+ broken_selector: str = Field(..., description="the test locator that no longer matches")
74
+ root_cause: str = Field(..., description="which DOM attribute change broke the selector")
75
+ suggestion: str = Field(
76
+ ...,
77
+ description="source-level fix (e.g. add a stable data-testid or an accessible role/name)",
78
+ )
79
+ recommended_selector: str = Field(
80
+ default="",
81
+ description="accessibility-first test selector to prefer (e.g. getByRole('button', ...))",
82
+ )
83
+ severity: Literal["info", "warning"] = Field(
84
+ default="warning", description="advisory severity for the PR comment"
85
+ )
86
+
87
+
88
+ class ReviewOutput(BaseModel):
89
+ """Structured Output schema the Reviewer LLM is forced to return (no free-form prose)."""
90
+
91
+ findings: list[ReviewFinding]
92
+
93
+
94
+ class ReviewReport(BaseModel):
95
+ """Machine-readable review result emitted for the CI wrapper to post as PR comments."""
96
+
97
+ test_script_path: str
98
+ findings: list[ReviewFinding] = Field(default_factory=list)
99
+ has_findings: bool = False
app/shadow/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """Shadow Runtime module for E2E-Self-Heal.
2
+
3
+ Provides workspaces, snapshots, matching, and playwright mock injection.
4
+ """
5
+
6
+ from app.shadow.config import CleanupPolicy, ShadowConfig
7
+ from app.shadow.injector import MockInjector
8
+ from app.shadow.in_memory_snapshot_store import InMemorySnapshotStore
9
+ from app.shadow.interfaces import (
10
+ IMockInjector,
11
+ IShadowRuntime,
12
+ IShadowWorkspace,
13
+ ISnapshotStore,
14
+ ITraceParser,
15
+ )
16
+ from app.shadow.matcher import NoMatchError, SnapshotMatcher
17
+ from app.shadow.normalizer import RequestNormalizer
18
+ from app.shadow.runtime import ShadowRuntime
19
+ from app.shadow.schemas import (
20
+ CapturedRequest,
21
+ CapturedResponse,
22
+ NetworkSnapshot,
23
+ ShadowRunResult,
24
+ ShadowSnapshot,
25
+ )
26
+ from app.shadow.scoring import MatchScorer, ScoringWeights
27
+ from app.shadow.snapshot_store import (
28
+ SnapshotCorruptionError,
29
+ SnapshotNotFoundError,
30
+ SnapshotStore,
31
+ SnapshotStoreError,
32
+ )
33
+ from app.shadow.trace_parser import (
34
+ InvalidTraceArchiveError,
35
+ PlaywrightTraceParser,
36
+ TraceParseError,
37
+ )
38
+ from app.shadow.workspace import ShadowWorkspace
39
+
40
+ __all__ = [
41
+ "IMockInjector",
42
+ "IShadowRuntime",
43
+ "IShadowWorkspace",
44
+ "ISnapshotStore",
45
+ "ITraceParser",
46
+ "CleanupPolicy",
47
+ "MockInjector",
48
+ "ShadowConfig",
49
+ "ShadowRuntime",
50
+ "SnapshotMatcher",
51
+ "NoMatchError",
52
+ "RequestNormalizer",
53
+ "MatchScorer",
54
+ "ScoringWeights",
55
+ "CapturedRequest",
56
+ "CapturedResponse",
57
+ "NetworkSnapshot",
58
+ "ShadowSnapshot",
59
+ "ShadowRunResult",
60
+ "SnapshotStore",
61
+ "SnapshotStoreError",
62
+ "SnapshotNotFoundError",
63
+ "SnapshotCorruptionError",
64
+ "PlaywrightTraceParser",
65
+ "TraceParseError",
66
+ "InvalidTraceArchiveError",
67
+ "ShadowWorkspace",
68
+ "InMemorySnapshotStore",
69
+ ]