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/llm.py ADDED
@@ -0,0 +1,246 @@
1
+ """Provider-agnostic LLM client built on LangChain chat models.
2
+
3
+ Hides per-provider differences (endpoints, credentials, Structured Outputs mechanics)
4
+ behind one interface with two operations: free-text completion and schema-validated
5
+ structured completion (Pydantic schema in -> validated model out). A factory selects the
6
+ concrete chat model from ``settings.llm_provider`` so users can plug in OpenAI, Anthropic,
7
+ Ollama, or any OpenAI-compatible endpoint (NVIDIA NIM) without touching node code.
8
+
9
+ The default model (``openai/gpt-oss-120b`` on NVIDIA NIM) is a reasoning model, so
10
+ completions are given explicit token headroom (``settings.llm_max_tokens``) to leave room
11
+ for its reasoning content.
12
+ """
13
+
14
+ import os
15
+ from functools import lru_cache
16
+ from typing import Any, Protocol, TypeVar
17
+
18
+ import structlog
19
+ from langchain_core.language_models import BaseChatModel
20
+ from langchain_core.messages import BaseMessage
21
+ from langchain_openai import ChatOpenAI
22
+ from pydantic import BaseModel
23
+ from tenacity import retry, stop_after_attempt, wait_exponential
24
+
25
+ from app.config import LLMProvider, settings
26
+ from app.schemas import PatchOutput, ReviewOutput
27
+
28
+ # Anthropic and Ollama are optional dependencies: users who don't use them shouldn't have to
29
+ # install langchain-anthropic / langchain-ollama. The guarded imports stay at module top per
30
+ # the imports-at-top rule; the matching provider branch checks availability at build time.
31
+ try:
32
+ from langchain_anthropic import ChatAnthropic
33
+ except ImportError: # pragma: no cover - exercised only without the extra installed
34
+ ChatAnthropic = None
35
+
36
+ try:
37
+ from langchain_ollama import ChatOllama
38
+ except ImportError: # pragma: no cover - exercised only without the extra installed
39
+ ChatOllama = None
40
+
41
+ logger = structlog.get_logger(__name__)
42
+
43
+ SchemaT = TypeVar("SchemaT", bound=BaseModel)
44
+
45
+ # Ollama runs models locally with no credential; the native endpoint (no OpenAI /v1 path).
46
+ _OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"
47
+
48
+ # OpenAI's native Structured Outputs: strict json_schema guarantees the response matches
49
+ # PatchOutput/ReviewOutput exactly (the same mechanism the original beta.parse used). Applied
50
+ # to the OpenAI-SDK-driven providers; other backends fall back to their default method.
51
+ _STRICT_JSON_SCHEMA: dict[str, Any] = {"method": "json_schema", "strict": True}
52
+ _STRICT_SCHEMA_PROVIDERS: frozenset[str] = frozenset({"openai", "nvidia"})
53
+
54
+
55
+ class LLMClient(Protocol):
56
+ """Provider-agnostic surface the nodes call: free-text and structured completion.
57
+
58
+ Implementations must ``raise`` on an empty/unparsed response (never return ``None``)
59
+ so the tenacity retry and the Patch Generator feedback loop keep working.
60
+ """
61
+
62
+ def complete(self, system_prompt: str, user_prompt: str) -> str: ...
63
+
64
+ def structured(
65
+ self, system_prompt: str, user_prompt: str, schema: type[SchemaT]
66
+ ) -> SchemaT: ...
67
+
68
+
69
+ def _extract_text(message: BaseMessage) -> str:
70
+ """Flatten an LLM message's content to plain text (providers may return content blocks)."""
71
+ content = message.content
72
+ if isinstance(content, str):
73
+ return content
74
+ parts = [block if isinstance(block, str) else str(block.get("text", "")) for block in content]
75
+ return "".join(parts)
76
+
77
+
78
+ class LangChainClient:
79
+ """Adapts a LangChain ``BaseChatModel`` to the ``LLMClient`` interface.
80
+
81
+ ``with_structured_output`` normalizes each provider's Structured Outputs mechanism
82
+ (OpenAI json-schema/tool-calling, Anthropic tool use) into one call that returns a
83
+ validated Pydantic model, so the schema enforcement (PatchOutput/ReviewOutput) holds
84
+ regardless of backend.
85
+ """
86
+
87
+ def __init__(
88
+ self, model: BaseChatModel, structured_kwargs: dict[str, Any] | None = None
89
+ ) -> None:
90
+ self._model = model
91
+ # Per-provider Structured Outputs tuning (e.g. OpenAI/NVIDIA use strict json_schema,
92
+ # which is OpenAI's native Structured Outputs). Empty = the model's default method.
93
+ self._structured_kwargs = structured_kwargs or {}
94
+
95
+ def complete(self, system_prompt: str, user_prompt: str) -> str:
96
+ messages = [("system", system_prompt), ("human", user_prompt)]
97
+ response = self._model.invoke(messages)
98
+ content = _extract_text(response)
99
+ if not content:
100
+ logger.warning("llm_returned_empty_completion")
101
+ raise ValueError("llm_returned_empty_completion")
102
+ return content
103
+
104
+ def structured(self, system_prompt: str, user_prompt: str, schema: type[SchemaT]) -> SchemaT:
105
+ messages = [("system", system_prompt), ("human", user_prompt)]
106
+ runnable = self._model.with_structured_output(schema, **self._structured_kwargs)
107
+ parsed = runnable.invoke(messages)
108
+ if not isinstance(parsed, schema):
109
+ logger.warning("llm_returned_no_parsed_output", schema=schema.__name__)
110
+ raise ValueError("llm_returned_no_parsed_output")
111
+ return parsed
112
+
113
+
114
+ def _require_key() -> str:
115
+ """Return the configured API key, or raise so callers fail loudly (not silently)."""
116
+ if not settings.llm_api_key:
117
+ raise RuntimeError(
118
+ "E2E_HEALER_LLM_API_KEY is not set for provider=" + settings.llm_provider
119
+ )
120
+ return settings.llm_api_key
121
+
122
+
123
+ def _openai_api_key() -> str:
124
+ """OpenAI key: prefer the generic setting, else the standard ``OPENAI_API_KEY`` env var.
125
+
126
+ Lets a user with an existing ``OPENAI_API_KEY`` drop in without duplicating it under the
127
+ ``E2E_HEALER_`` prefix.
128
+ """
129
+ key = settings.llm_api_key or os.environ.get("OPENAI_API_KEY", "")
130
+ if not key:
131
+ raise RuntimeError(
132
+ "E2E_HEALER_LLM_API_KEY or OPENAI_API_KEY is not set for provider=openai"
133
+ )
134
+ return key
135
+
136
+
137
+ def _anthropic_api_key() -> str:
138
+ """Anthropic key: prefer the generic setting, else the standard ``ANTHROPIC_API_KEY`` env var.
139
+
140
+ Lets a user with an existing ``ANTHROPIC_API_KEY`` drop in without duplicating it under
141
+ the ``E2E_HEALER_`` prefix.
142
+ """
143
+ key = settings.llm_api_key or os.environ.get("ANTHROPIC_API_KEY", "")
144
+ if not key:
145
+ raise RuntimeError(
146
+ "E2E_HEALER_LLM_API_KEY or ANTHROPIC_API_KEY is not set for provider=anthropic"
147
+ )
148
+ return key
149
+
150
+
151
+ def _build_chat_model(provider: LLMProvider) -> BaseChatModel:
152
+ """Construct the LangChain chat model for ``provider`` from settings (the factory core).
153
+
154
+ Model kwargs are splatted from a dict because the chat-model classes expose ``model`` /
155
+ ``max_tokens`` as pydantic aliases the type checker can't see on the constructor.
156
+ """
157
+ if provider == "anthropic":
158
+ if ChatAnthropic is None:
159
+ raise RuntimeError(
160
+ "provider=anthropic requires the optional 'anthropic' extra: "
161
+ 'install it with pip install "ai-driven-e2e[anthropic]"'
162
+ )
163
+ # Anthropic has no OpenAI-style response_format; with_structured_output maps
164
+ # PatchOutput/ReviewOutput onto Claude tool-use (the default method), so the schema
165
+ # is still enforced. That's why anthropic is absent from _STRICT_SCHEMA_PROVIDERS.
166
+ params: dict[str, Any] = {
167
+ "model": settings.llm_model,
168
+ "api_key": _anthropic_api_key(),
169
+ "max_tokens": settings.llm_max_tokens,
170
+ }
171
+ return ChatAnthropic(**params)
172
+ if provider == "ollama":
173
+ if ChatOllama is None:
174
+ raise RuntimeError(
175
+ "provider=ollama requires the optional 'ollama' extra: "
176
+ 'install it with pip install "ai-driven-e2e[ollama]"'
177
+ )
178
+ # Fully local, no API key. Ollama's native structured output (format=<json schema>,
179
+ # the default with_structured_output method) validates against PatchOutput/ReviewOutput;
180
+ # a parse/validation failure raises out of structured() so tenacity retries and, on
181
+ # exhaustion, the Patch Generator feedback loop kicks in (local models are less reliable
182
+ # at strict JSON). num_predict is Ollama's token-cap name.
183
+ params = {
184
+ "model": settings.llm_model,
185
+ "base_url": settings.llm_base_url or _OLLAMA_DEFAULT_BASE_URL,
186
+ "num_predict": settings.llm_max_tokens,
187
+ }
188
+ return ChatOllama(**params)
189
+ if provider == "openai":
190
+ # Native OpenAI. base_url stays empty for api.openai.com, or points at an
191
+ # Azure / OpenAI-compatible endpoint via E2E_HEALER_LLM_BASE_URL.
192
+ params = {
193
+ "model": settings.llm_model,
194
+ "api_key": _openai_api_key(),
195
+ "base_url": settings.llm_base_url or None,
196
+ "max_tokens": settings.llm_max_tokens,
197
+ }
198
+ return ChatOpenAI(**params)
199
+ # nvidia: OpenAI-compatible NIM endpoint driven by the OpenAI SDK; needs an explicit
200
+ # base_url (folded in from the legacy nvidia_* settings by the config layer).
201
+ params = {
202
+ "model": settings.llm_model,
203
+ "api_key": _require_key(),
204
+ "base_url": settings.llm_base_url or None,
205
+ "max_tokens": settings.llm_max_tokens,
206
+ }
207
+ return ChatOpenAI(**params)
208
+
209
+
210
+ @lru_cache(maxsize=1)
211
+ def _get_client() -> LLMClient:
212
+ """Build the provider client lazily so importing never needs credentials.
213
+
214
+ Instantiating at import time would require an API key just to collect tests or run
215
+ ``--help``; deferring it here keeps import side-effect-free and fails only when the
216
+ LLM is actually called without a key configured.
217
+ """
218
+ provider = settings.llm_provider
219
+ structured_kwargs = _STRICT_JSON_SCHEMA if provider in _STRICT_SCHEMA_PROVIDERS else {}
220
+ return LangChainClient(_build_chat_model(provider), structured_kwargs)
221
+
222
+
223
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
224
+ def generate_diagnosis(system_prompt: str, user_prompt: str) -> str:
225
+ """Call the LLM for a free-text failure diagnosis (the Diagnoser node)."""
226
+ return _get_client().complete(system_prompt, user_prompt)
227
+
228
+
229
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
230
+ def generate_patch(system_prompt: str, user_prompt: str) -> PatchOutput:
231
+ """Call the LLM with an enforced PatchOutput schema and return the parsed result.
232
+
233
+ Raises on a missing/malformed parse so tenacity retries; the Patch Generator node
234
+ is responsible for the feedback loop when retries are exhausted.
235
+ """
236
+ return _get_client().structured(system_prompt, user_prompt, PatchOutput)
237
+
238
+
239
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
240
+ def generate_review(system_prompt: str, user_prompt: str) -> ReviewOutput:
241
+ """Call the LLM with an enforced ReviewOutput schema for source-level suggestions.
242
+
243
+ Mirrors ``generate_patch``: Structured Outputs keep the Reviewer to advisory findings
244
+ (never free-form rewrites). Raises on a missing parse so tenacity retries.
245
+ """
246
+ return _get_client().structured(system_prompt, user_prompt, ReviewOutput)
app/logging.py ADDED
@@ -0,0 +1,22 @@
1
+ """structlog configuration for the whole application."""
2
+
3
+ import logging
4
+
5
+ import structlog
6
+
7
+
8
+ def configure_logging(level: str = "INFO") -> None:
9
+ """Configure structlog once at process start."""
10
+ logging.basicConfig(format="%(message)s", level=level)
11
+ structlog.configure(
12
+ processors=[
13
+ structlog.contextvars.merge_contextvars,
14
+ structlog.processors.add_log_level,
15
+ structlog.processors.TimeStamper(fmt="iso"),
16
+ structlog.processors.StackInfoRenderer(),
17
+ structlog.processors.format_exc_info,
18
+ structlog.dev.ConsoleRenderer(),
19
+ ],
20
+ wrapper_class=structlog.make_filtering_bound_logger(logging.getLevelNamesMapping()[level]),
21
+ cache_logger_on_first_use=True,
22
+ )
app/nodes/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """LangGraph nodes: Diagnoser, Patch Generator, Test Runner."""
app/nodes/diagnoser.py ADDED
@@ -0,0 +1,28 @@
1
+ """Diagnoser node: infer why the test broke."""
2
+
3
+ import json
4
+
5
+ import structlog
6
+
7
+ from app.llm import generate_diagnosis
8
+ from app.preprocess.aria_snapshot import abstract_snapshot
9
+ from app.prompts.diagnoser import SYSTEM_PROMPT
10
+ from app.state import AgentState
11
+
12
+ logger = structlog.get_logger(__name__)
13
+
14
+
15
+ def diagnoser(state: AgentState) -> dict:
16
+ """Map the failing selector to the DOM change and produce an ``analysis_report``."""
17
+ logger.info("diagnoser_started", loop_count=state["loop_count"])
18
+ user_prompt = (
19
+ f"Error log:\n{state['error_log']}\n\n"
20
+ f"DOM changes (from git diff):\n{json.dumps(state['dom_diff_context'], indent=2)}\n\n"
21
+ )
22
+ snapshot = abstract_snapshot(state.get("dom_snapshot", ""))
23
+ if snapshot:
24
+ user_prompt += f"ARIA page snapshot (at failure):\n{snapshot}\n\n"
25
+ user_prompt += f"Current test code:\n{state['current_code']}"
26
+ report = generate_diagnosis(SYSTEM_PROMPT, user_prompt)
27
+ logger.info("diagnoser_finished")
28
+ return {"analysis_report": report}
@@ -0,0 +1,43 @@
1
+ """Patch Generator node: produce a narrow, schema-constrained fix."""
2
+
3
+ import structlog
4
+
5
+ from app.llm import generate_patch
6
+ from app.prompts.patch_generator import SYSTEM_PROMPT
7
+ from app.schemas import PatchInstruction
8
+ from app.state import AgentState
9
+
10
+ logger = structlog.get_logger(__name__)
11
+
12
+
13
+ def _apply(code: str, instructions: list[PatchInstruction]) -> str:
14
+ """Apply line-targeted replacements to ``code`` (1-based line numbers)."""
15
+ lines = code.splitlines(keepends=True)
16
+ for instruction in instructions:
17
+ index = instruction.line - 1
18
+ if 0 <= index < len(lines):
19
+ newline = "\n" if lines[index].endswith("\n") else ""
20
+ lines[index] = instruction.replacement + newline
21
+ return "".join(lines)
22
+
23
+
24
+ def patch_generator(state: AgentState) -> dict:
25
+ """Generate a targeted patch via Structured Outputs and apply it to ``current_code``.
26
+
27
+ On LLM/parse failure, log and return the code unchanged rather than crashing the
28
+ graph — the Test Runner will fail again and the Router loops until the cap.
29
+ """
30
+ logger.info("patch_generator_started", loop_count=state["loop_count"])
31
+ user_prompt = (
32
+ f"Failure diagnosis:\n{state['analysis_report']}\n\n"
33
+ f"Current test code:\n{state['current_code']}"
34
+ )
35
+ try:
36
+ output = generate_patch(SYSTEM_PROMPT, user_prompt)
37
+ except Exception:
38
+ logger.exception("patch_generation_failed")
39
+ return {"current_code": state["current_code"], "patch_instructions": {}}
40
+
41
+ patched = _apply(state["current_code"], output.instructions)
42
+ logger.info("patch_generator_finished", instruction_count=len(output.instructions))
43
+ return {"current_code": patched, "patch_instructions": output.model_dump()}
app/nodes/reviewer.py ADDED
@@ -0,0 +1,34 @@
1
+ """Reviewer node (review mode): advise a source-level fix instead of patching the test."""
2
+
3
+ import json
4
+
5
+ import structlog
6
+
7
+ from app.llm import generate_review
8
+ from app.prompts.reviewer import SYSTEM_PROMPT
9
+ from app.state import AgentState
10
+
11
+ logger = structlog.get_logger(__name__)
12
+
13
+
14
+ def reviewer(state: AgentState) -> dict:
15
+ """Turn the diagnosis + DOM changes into source-level suggestions (never edits the test).
16
+
17
+ On any LLM/parse failure, log and return an empty report rather than crashing the graph
18
+ (Rule 10) — the CLI then reports "no findings" instead of failing the run.
19
+ """
20
+ logger.info("reviewer_started")
21
+ user_prompt = (
22
+ f"Failure diagnosis:\n{state['analysis_report']}\n\n"
23
+ f"DOM changes (from git diff, with new-file lines):\n"
24
+ f"{json.dumps(state['dom_diff_context'], indent=2)}\n\n"
25
+ f"Current test code:\n{state['current_code']}"
26
+ )
27
+ try:
28
+ output = generate_review(SYSTEM_PROMPT, user_prompt)
29
+ except Exception:
30
+ logger.exception("review_generation_failed")
31
+ return {"review_report": {"findings": []}}
32
+
33
+ logger.info("reviewer_finished", finding_count=len(output.findings))
34
+ return {"review_report": output.model_dump()}
@@ -0,0 +1,75 @@
1
+ """Selector Verifier node: ground LLM-produced selectors against the live DOM.
2
+
3
+ Sits between the Patch Generator and the Test Runner. Before spending a full Playwright
4
+ run, it checks that each patched selector resolves to exactly one element on the real page.
5
+ A hallucinated (0 matches) or ambiguous (>1 matches) selector is rejected: the just-applied
6
+ patch is reverted and the loop re-patches with feedback, saving a wasted test run.
7
+
8
+ Graceful by design — if verification is disabled, no app URL is set, there are no selector
9
+ edits, or the Node helper can't run, it passes through and lets the Test Runner arbitrate.
10
+ """
11
+
12
+ import structlog
13
+
14
+ from app.config import settings
15
+ from app.schemas import PatchInstruction
16
+ from app.state import AgentState
17
+ from app.verify.selector_check import check_selectors
18
+
19
+ logger = structlog.get_logger(__name__)
20
+
21
+ _SKIPPED: dict = {"skipped": True, "ok": True}
22
+
23
+
24
+ def _revert(code: str, instructions: list[PatchInstruction]) -> str:
25
+ """Undo an applied patch by restoring each instruction's original line (1-based)."""
26
+ lines = code.splitlines(keepends=True)
27
+ for instruction in instructions:
28
+ index = instruction.line - 1
29
+ if 0 <= index < len(lines):
30
+ newline = "\n" if lines[index].endswith("\n") else ""
31
+ lines[index] = instruction.original + newline
32
+ return "".join(lines)
33
+
34
+
35
+ def _feedback(bad: dict[str, int]) -> str:
36
+ """Build a diagnosis addendum naming the rejected selectors for the next patch attempt."""
37
+ detail = "; ".join(f"'{sel}' matched {count} element(s)" for sel, count in bad.items())
38
+ return (
39
+ "\n\n[VERIFICATION FEEDBACK] The previous patch was rejected against the live DOM: "
40
+ f"{detail}. Each selector must resolve to exactly one element — choose a different, "
41
+ "more specific selector and do not reuse the rejected one."
42
+ )
43
+
44
+
45
+ def selector_verifier(state: AgentState) -> dict:
46
+ """Verify patched selectors against the live DOM; revert and loop back if any is invalid."""
47
+ if not settings.verify_selectors or not settings.app_url:
48
+ return {"verification_report": _SKIPPED}
49
+
50
+ instructions = [
51
+ PatchInstruction(**i) for i in state["patch_instructions"].get("instructions", [])
52
+ ]
53
+ selectors = [i.selector for i in instructions if i.selector]
54
+ if not selectors:
55
+ return {"verification_report": _SKIPPED}
56
+
57
+ logger.info("selector_verify_started", selector_count=len(selectors), url=settings.app_url)
58
+ counts = check_selectors(settings.app_url, selectors)
59
+ if counts is None:
60
+ logger.info("selector_verify_unavailable") # tooling missing -> defer to Test Runner
61
+ return {"verification_report": _SKIPPED}
62
+
63
+ bad = {sel: count for sel, count in counts.items() if count != 1}
64
+ if not bad:
65
+ logger.info("selector_verify_passed", counts=counts)
66
+ return {"verification_report": {"ok": True, "counts": counts}}
67
+
68
+ next_count = state["loop_count"] + 1
69
+ logger.info("selector_verify_failed", bad=bad, loop_count=next_count)
70
+ return {
71
+ "current_code": _revert(state["current_code"], instructions),
72
+ "analysis_report": state["analysis_report"] + _feedback(bad),
73
+ "loop_count": next_count,
74
+ "verification_report": {"ok": False, "counts": counts},
75
+ }
@@ -0,0 +1,106 @@
1
+ """Shadow Verifier node: run the patched test in the Shadow Runtime.
2
+
3
+ Serves as a fast, offline gate before invoking the live, slow, and potentially
4
+ flaky selector verifier and test runner. If the shadow replay fails, the loop
5
+ re-patches with feedback, saving a wasted test run.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import structlog
11
+
12
+ from app.shadow.config import ShadowConfig
13
+ from app.shadow.runtime import run_shadow
14
+ from app.shadow.schemas import ShadowRunResult
15
+ from app.shadow.snapshot_store import SnapshotNotFoundError, SnapshotStore
16
+ from app.shadow.workspace import ShadowWorkspace
17
+ from app.state import AgentState
18
+ from app.utils.files import atomic_write
19
+
20
+ logger = structlog.get_logger(__name__)
21
+
22
+
23
+ def _shadow_feedback(result: ShadowRunResult) -> str:
24
+ """Build a diagnosis addendum naming the shadow replay failure details."""
25
+ detail = (
26
+ f"matched={result.matched_count}, missed={result.missed_count}, score={result.score:.2f}"
27
+ )
28
+ return (
29
+ "\n\n[SHADOW VERIFICATION FEEDBACK] The previous patch was rejected because the shadow replay failed: "
30
+ f"{detail}. Make sure to adjust selectors or wait conditions to match expected network interactions."
31
+ )
32
+
33
+
34
+ def shadow_verifier(state: AgentState) -> dict:
35
+ """Verify the patched test script using the Shadow Runtime replay.
36
+
37
+ Temporarily writes the patched code to disk, executes the shadow replay,
38
+ and reverts the changes on disk/state if the replay fails.
39
+
40
+ If no snapshot exists for the test, skips shadow verification gracefully.
41
+ """
42
+ test_path = Path(state["test_script_path"])
43
+ snapshot_id = test_path.stem
44
+
45
+ logger.info("shadow_verify_started", test_script_path=str(test_path), snapshot_id=snapshot_id)
46
+
47
+ # Check if the snapshot exists before running to skip gracefully if absent
48
+ cfg = ShadowConfig()
49
+ workspace = ShadowWorkspace(cfg)
50
+ store = SnapshotStore(workspace)
51
+ try:
52
+ store.get_snapshot(snapshot_id)
53
+ except SnapshotNotFoundError:
54
+ logger.info("shadow_verify_skipped_no_snapshot", snapshot_id=snapshot_id)
55
+ return {"shadow_report": {"ok": True, "skipped": True}}
56
+
57
+ # Memoize the pre-change code (for rollback atomicity) and the candidate code
58
+ pre_change_code = test_path.read_text(encoding="utf-8")
59
+ candidate_code = state["current_code"]
60
+
61
+ # Write the current candidate code to disk so run_shadow can execute it
62
+ atomic_write(test_path, candidate_code)
63
+
64
+ try:
65
+ result = run_shadow(test_path=test_path, snapshot_id=snapshot_id, config=cfg)
66
+
67
+ if not isinstance(result, ShadowRunResult):
68
+ # Fallback if run_shadow returned placeholder string
69
+ logger.info("shadow_verify_skipped_placeholder")
70
+ atomic_write(test_path, pre_change_code)
71
+ return {"shadow_report": {"ok": True, "skipped": True}}
72
+
73
+ if result.is_success:
74
+ logger.info("shadow_verify_passed", score=result.score)
75
+ return {
76
+ "current_code": candidate_code,
77
+ "shadow_report": {"ok": True, "score": result.score},
78
+ }
79
+
80
+ # Replay failed: rollback both disk and state to pre_change_code
81
+ logger.info("shadow_verify_failed", score=result.score)
82
+ atomic_write(test_path, pre_change_code)
83
+
84
+ next_count = state["loop_count"] + 1
85
+ return {
86
+ "current_code": pre_change_code,
87
+ "analysis_report": state["analysis_report"] + _shadow_feedback(result),
88
+ "loop_count": next_count,
89
+ "shadow_report": {"ok": False, "score": result.score},
90
+ }
91
+
92
+ except Exception as e:
93
+ logger.exception("shadow_verify_exception")
94
+ # In case of any exception, revert changes to disk
95
+ atomic_write(test_path, pre_change_code)
96
+
97
+ next_count = state["loop_count"] + 1
98
+ return {
99
+ "current_code": pre_change_code,
100
+ "analysis_report": (
101
+ state["analysis_report"]
102
+ + f"\n\n[SHADOW VERIFICATION ERROR] Exception occurred during shadow verification: {e}"
103
+ ),
104
+ "loop_count": next_count,
105
+ "shadow_report": {"ok": False, "error": str(e)},
106
+ }
@@ -0,0 +1,36 @@
1
+ """Test Runner node: write the patched test and run Playwright."""
2
+
3
+ from pathlib import Path
4
+
5
+ import structlog
6
+
7
+ from app.preprocess.error_log_parser import parse_error_log
8
+ from app.runner import run_playwright
9
+ from app.state import AgentState
10
+ from app.utils.files import atomic_write
11
+
12
+ logger = structlog.get_logger(__name__)
13
+
14
+
15
+ def test_runner(state: AgentState) -> dict:
16
+ """Write ``current_code`` to disk and run Playwright via the shared runner.
17
+
18
+ On pass returns ``{"is_success": True}``; on fail returns the re-parsed error log
19
+ and an incremented ``loop_count``.
20
+ """
21
+ path = state["test_script_path"]
22
+ logger.info("test_runner_started", test_script_path=path)
23
+ atomic_write(Path(path), state["current_code"])
24
+
25
+ passed, log = run_playwright(path)
26
+ if passed:
27
+ logger.info("test_runner_passed", loop_count=state["loop_count"])
28
+ return {"is_success": True}
29
+
30
+ next_count = state["loop_count"] + 1
31
+ logger.info("test_runner_failed", loop_count=next_count)
32
+ return {
33
+ "is_success": False,
34
+ "error_log": parse_error_log(log),
35
+ "loop_count": next_count,
36
+ }
@@ -0,0 +1 @@
1
+ """Data preprocessing: abstract raw inputs before they reach the LLM."""
@@ -0,0 +1,70 @@
1
+ """Extract Playwright's failure-time page (ARIA) snapshot from ``error-context.md``.
2
+
3
+ On failure, recent Playwright writes ``test-results/<name>/error-context.md`` containing a
4
+ ``# Page snapshot`` section — a YAML accessibility tree of the page **at the moment of
5
+ failure** (after navigation/interaction). This is a hallucination-resistant, deep-state
6
+ view of the page, captured with no test modification and no trace parsing.
7
+ """
8
+
9
+ import re
10
+ from pathlib import Path
11
+
12
+ import structlog
13
+
14
+ from app.sandbox import SandboxViolation, assert_read_allowed
15
+
16
+ logger = structlog.get_logger(__name__)
17
+
18
+ # Keep ARIA snapshots bounded for LLM context — raw trees can be very large.
19
+ DEFAULT_MAX_SNAPSHOT_CHARS = 2500
20
+
21
+ _SNAPSHOT_RE = re.compile(r"#\s*Page snapshot\s*```ya?ml\s*\n(.*?)\n```", re.DOTALL)
22
+
23
+
24
+ def abstract_snapshot(snapshot: str, max_chars: int = DEFAULT_MAX_SNAPSHOT_CHARS) -> str:
25
+ """Return a trimmed ARIA snapshot suitable for Diagnoser context, or '' if empty."""
26
+ text = snapshot.strip()
27
+ if not text:
28
+ return ""
29
+ if len(text) <= max_chars:
30
+ return text
31
+ return text[:max_chars] + f"\n... [truncated to {max_chars} chars]"
32
+
33
+
34
+ def extract_page_snapshot(error_context_md: str | None) -> str:
35
+ """Return the ARIA page-snapshot YAML from an error-context.md body, or '' if absent."""
36
+ if not error_context_md:
37
+ return ""
38
+ match = _SNAPSHOT_RE.search(error_context_md)
39
+ return match.group(1).strip() if match else ""
40
+
41
+
42
+ def read_failure_snapshot(results_dir: Path) -> str:
43
+ """Return the ARIA page snapshot from the newest error-context.md under ``results_dir``.
44
+
45
+ Returns '' when no results dir or snapshot exists, so callers degrade gracefully.
46
+ """
47
+ if not results_dir.exists():
48
+ return ""
49
+ try:
50
+ assert_read_allowed(results_dir)
51
+ except SandboxViolation as exc:
52
+ logger.warning("failure_snapshot_sandbox_denied", path=str(results_dir), error=str(exc))
53
+ return ""
54
+
55
+ contexts = []
56
+ for path in results_dir.rglob("*error-context*.md"):
57
+ try:
58
+ assert_read_allowed(path)
59
+ except SandboxViolation as exc:
60
+ logger.warning("failure_snapshot_file_sandbox_denied", path=str(path), error=str(exc))
61
+ continue
62
+ contexts.append(path)
63
+
64
+ contexts = sorted(contexts, key=lambda p: p.stat().st_mtime, reverse=True)
65
+ if not contexts:
66
+ return ""
67
+
68
+ snapshot = extract_page_snapshot(contexts[0].read_text())
69
+ logger.info("failure_snapshot_read", chars=len(snapshot), source=str(contexts[0]))
70
+ return snapshot