diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 046f42ff46..c3a6bb033e 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -475,7 +475,7 @@ jobs: python - <<'PY' import xml.etree.ElementTree as ET cases = ET.parse("tests.xml").getroot().findall(".//testcase") - assert len(cases) == 168, f"expected 168 independent-store, surgical-heal, portal-readback, mcpify, and commit-firewall controls, got {len(cases)}" + assert len(cases) == 181, f"expected 181 independent-store, surgical-heal, portal-readback, mcpify, commit-firewall, and jit controls, got {len(cases)}" # The PostgreSQL and MySQL quickstart controls need the database # services of verify-clean-install, which runs them; nothing else skips. skipped = {c.get("name") for c in cases if c.find("skipped") is not None} diff --git a/packages/verify/src/openadapt_verify/__init__.py b/packages/verify/src/openadapt_verify/__init__.py index 0c9d71f40e..e631f62bd5 100644 --- a/packages/verify/src/openadapt_verify/__init__.py +++ b/packages/verify/src/openadapt_verify/__init__.py @@ -25,6 +25,7 @@ from openadapt_flow.write_receipt import Verification as PortableReceiptVerification from openadapt_flow.write_receipt import verify as verify_receipt +from openadapt_verify import jit from openadapt_verify.commit_firewall import ( CommitBlockedError, CommitResult, @@ -34,6 +35,14 @@ verify_commit, ) from openadapt_verify.guard import checked_write, verified +from openadapt_verify.jit import ( + CompiledPlan, + CompiledStep, + JitResult, + ParameterBinder, + format_scorecard, + jit_wrap, +) from openadapt_verify.mcpify import ( McpifyServer, ReadbackResult, @@ -42,6 +51,7 @@ WorkflowToolSpec, generate_mcp_client_config, issue_mcpify_receipt, + load_compiled_tools, load_workflow_spec, load_workflow_specs, verify_mcpify_receipt, @@ -61,13 +71,17 @@ "AlreadyWritten", "CommitBlockedError", "CommitResult", + "CompiledPlan", + "CompiledStep", "ConfirmationPdfOracle", "Contract", "FieldCheck", "FreshReloadSummaryOracle", + "JitResult", "LocalSealVerification", "McpifyServer", "Outcome", + "ParameterBinder", "PortalReadbackResult", "PortableReceiptVerification", "ReadbackResult", @@ -84,9 +98,13 @@ "async_verify_commit", "begin_write", "checked_write", + "format_scorecard", "generate_mcp_client_config", "issue_mcpify_receipt", "issue_write_receipt", + "jit", + "jit_wrap", + "load_compiled_tools", "load_workflow_spec", "load_workflow_specs", "recheck", diff --git a/packages/verify/src/openadapt_verify/jit.py b/packages/verify/src/openadapt_verify/jit.py new file mode 100644 index 0000000000..d5307d6131 --- /dev/null +++ b/packages/verify/src/openadapt_verify/jit.py @@ -0,0 +1,1684 @@ +"""Local JIT compiler for verified UI workflows (``openadapt_verify.jit``). + +Compiles the first verified run of an agent-driven UI function into a +parameterized, deterministic ``CompiledPlan`` cached under +``.openadapt/compiled/.json``. Subsequent runs skip the agent, replay +the compiled steps directly with new parameters, and verify persistence via +independent read-back. If a selector breaks, bounded step-level self-healing +recovers from the current page state and updates the cache only when final +read-back passes ``VERIFIED``. +""" + +from __future__ import annotations + +import functools +import inspect +import json +import os +import re +import tempfile +import time +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, Optional, Union + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from openadapt_verify.mcpify import ( + ReadbackResult, + SafetyPolicy, + SignedReceipt, + WorkflowToolSpec, + issue_mcpify_receipt, +) + +COMPILED_PLAN_SCHEMA = "openadapt.jit.plan/v1" +DEFAULT_CACHE_DIR = ".openadapt/compiled" + +JitMode = Literal["cold", "warm", "healed"] +JitStatus = Literal["VERIFIED", "UNCONFIRMED_WRITE", "STOPPED"] +StepAction = Literal["goto", "click", "fill", "select", "press"] + +_SECRET_NAME_TOKENS = ( + "password", + "passwd", + "secret", + "token", + "api_key", + "apikey", + "auth", + "credential", + "ssn", + "cvv", + "pin", +) +_TEMPLATE_VAR_RE = re.compile(r"\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}") +_SAFE_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,127}$") + + +class StepReplayError(RuntimeError): + """Raised when every fallback selector for a compiled step fails.""" + + def __init__(self, step_index: int, step: CompiledStep, detail: str) -> None: + self.step_index = step_index + self.step = step + self.detail = detail + super().__init__(f"Step {step_index} ({step.action}) failed: {detail}") + + +class ParameterBinder: + """Bind concrete runtime parameter values into ``{{param_name}}`` templates. + + Matches longer parameter values before shorter ones, refuses empty + parameter values, and protects secret-named parameters so raw secret values + are never persisted in compiled plans. + """ + + @staticmethod + def is_secret_param(name: str) -> bool: + lowered = name.strip().lower() + return any(token in lowered for token in _SECRET_NAME_TOKENS) + + @classmethod + def validate_params(cls, params: Mapping[str, Any]) -> dict[str, str]: + cleaned: dict[str, str] = {} + for key, raw_val in params.items(): + if not isinstance(key, str) or not key.strip(): + raise ValueError("Parameter names must be non-empty strings.") + if raw_val is None: + raise ValueError(f"Parameter {key!r} must not be None.") + val_str = str(raw_val) + if not val_str.strip(): + raise ValueError(f"Parameter {key!r} must not be empty.") + cleaned[key.strip()] = val_str + return cleaned + + @classmethod + def bind_value( + cls, + value: str, + params: Mapping[str, Any], + ) -> tuple[str, tuple[str, ...]]: + """Replace concrete parameter values in ``value`` with ``{{name}}``.""" + validated = cls.validate_params(params) + if not value: + return value, () + + # Single-pass regex alternation ordered by value length descending so + # longer values match before substrings and already-inserted {{name}} + # placeholders can never be re-matched by another parameter's value. + ordered = sorted( + validated.items(), + key=lambda kv: (-len(kv[1]), kv[0]), + ) + val_to_name: dict[str, str] = {} + for pname, pval in ordered: + val_to_name.setdefault(pval, pname) + if not val_to_name: + return value, () + + pattern = re.compile("|".join(re.escape(v) for v in val_to_name)) + bound_names: list[str] = [] + + def _replace(match: re.Match[str]) -> str: + pname = val_to_name[match.group(0)] + if pname not in bound_names: + bound_names.append(pname) + return f"{{{{{pname}}}}}" + + templated = pattern.sub(_replace, value) + return templated, tuple(bound_names) + + @classmethod + def bind_mapping( + cls, + mapping: Mapping[str, Any], + params: Mapping[str, Any], + ) -> dict[str, Any]: + """Recursively template string values inside a JSON-compatible mapping.""" + out: dict[str, Any] = {} + for key, val in mapping.items(): + if isinstance(val, str): + templated, _ = cls.bind_value(val, params) + out[str(key)] = templated + elif isinstance(val, Mapping): + out[str(key)] = cls.bind_mapping(val, params) + elif isinstance(val, list): + out[str(key)] = [ + cls.bind_value(item, params)[0] if isinstance(item, str) else item + for item in val + ] + else: + out[str(key)] = val + return out + + @classmethod + def substitute(cls, template: str, params: Mapping[str, Any]) -> str: + """Substitute ``{{param_name}}`` placeholders using concrete ``params``.""" + validated = cls.validate_params(params) + + def _replace(match: re.Match[str]) -> str: + name = match.group(1) + if name not in validated: + raise KeyError( + f"Missing required parameter {name!r} for template {template!r}" + ) + return validated[name] + + return _TEMPLATE_VAR_RE.sub(_replace, template) + + @classmethod + def substitute_mapping( + cls, + mapping: Mapping[str, Any], + params: Mapping[str, Any], + ) -> dict[str, Any]: + """Recursively substitute ``{{param_name}}`` placeholders in a mapping.""" + out: dict[str, Any] = {} + for key, val in mapping.items(): + if isinstance(val, str): + out[str(key)] = cls.substitute(val, params) + elif isinstance(val, Mapping): + out[str(key)] = cls.substitute_mapping(val, params) + elif isinstance(val, list): + out[str(key)] = [ + cls.substitute(item, params) if isinstance(item, str) else item + for item in val + ] + else: + out[str(key)] = val + return out + + @classmethod + def redact_secrets(cls, text: str, params: Mapping[str, Any]) -> str: + """Replace any secret-named parameter values in ``text`` with ````.""" + if not text: + return text + secret_vals = sorted( + { + str(raw_val) + for key, raw_val in params.items() + if cls.is_secret_param(key) and str(raw_val) + }, + key=len, + reverse=True, + ) + if not secret_vals: + return text + pattern = re.compile("|".join(re.escape(v) for v in secret_vals)) + return pattern.sub("", text) + + @classmethod + def assert_no_secrets_leaked( + cls, + serialized_plan: str, + params: Mapping[str, Any], + ) -> None: + """Raise ValueError if any secret-named parameter value appears in plaintext.""" + for key, raw_val in params.items(): + if not cls.is_secret_param(key): + continue + val_str = str(raw_val) + if val_str and val_str in serialized_plan: + raise ValueError( + f"Secret parameter {key!r} leaked into compiled plan; refusing to persist." + ) + + +@dataclass(frozen=True) +class CompiledStep: + """One deterministic browser step in a compiled plan.""" + + action: StepAction + selectors: tuple[str, ...] = () + value: Optional[str] = None + post_condition: Optional[str] = None + healed_count: int = 0 + + def to_dict(self) -> dict[str, Any]: + data: dict[str, Any] = { + "action": self.action, + "selectors": list(self.selectors), + "value": self.value, + "post_condition": self.post_condition, + "healed_count": self.healed_count, + } + return data + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> CompiledStep: + action = str(data["action"]) + if action not in ("goto", "click", "fill", "select", "press"): + raise ValueError(f"Unsupported compiled step action: {action!r}") + raw_selectors = data.get("selectors") or () + selectors = tuple(str(s) for s in raw_selectors) + val = data.get("value") + post = data.get("post_condition") + return cls( + action=action, # type: ignore[arg-type] + selectors=selectors, + value=str(val) if val is not None else None, + post_condition=str(post) if post is not None else None, + healed_count=int(data.get("healed_count", 0)), + ) + + +@dataclass(frozen=True) +class CompiledPlanStats: + """Cumulative execution and savings counters for a compiled plan.""" + + cold_runs: int = 0 + warm_runs: int = 0 + heals: int = 0 + total_ms_saved: float = 0.0 + total_usd_saved: float = 0.0 + last_cold_ms: float = 0.0 + last_cold_usd: float = 0.0 + + def to_dict(self) -> dict[str, Any]: + return { + "cold_runs": self.cold_runs, + "warm_runs": self.warm_runs, + "heals": self.heals, + "total_ms_saved": round(self.total_ms_saved, 3), + "total_usd_saved": round(self.total_usd_saved, 6), + "last_cold_ms": round(self.last_cold_ms, 3), + "last_cold_usd": round(self.last_cold_usd, 6), + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> CompiledPlanStats: + return cls( + cold_runs=int(data.get("cold_runs", 0)), + warm_runs=int(data.get("warm_runs", 0)), + heals=int(data.get("heals", 0)), + total_ms_saved=float(data.get("total_ms_saved", 0.0)), + total_usd_saved=float(data.get("total_usd_saved", 0.0)), + last_cold_ms=float(data.get("last_cold_ms", 0.0)), + last_cold_usd=float(data.get("last_cold_usd", 0.0)), + ) + + +@dataclass(frozen=True) +class CompiledPlan: + """JSON-serializable compiled workflow plan stored on disk.""" + + name: str + description: str + param_names: tuple[str, ...] + secret_params: tuple[str, ...] + steps: tuple[CompiledStep, ...] + readback_mode: str = "fresh_reload" + readback_expectations: dict[str, Any] = field(default_factory=dict) + stats: CompiledPlanStats = field(default_factory=CompiledPlanStats) + schema_version: str = COMPILED_PLAN_SCHEMA + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "name": self.name, + "description": self.description, + "param_names": list(self.param_names), + "secret_params": list(self.secret_params), + "steps": [step.to_dict() for step in self.steps], + "readback_mode": self.readback_mode, + "readback_expectations": dict(self.readback_expectations), + "stats": self.stats.to_dict(), + } + + def to_json(self, indent: int = 2) -> str: + return json.dumps(self.to_dict(), indent=indent) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> CompiledPlan: + schema = str(data.get("schema_version", "")) + if schema != COMPILED_PLAN_SCHEMA: + raise ValueError( + f"Expected schema_version {COMPILED_PLAN_SCHEMA!r}, got {schema!r}" + ) + name = str(data["name"]) + if not _SAFE_NAME_RE.match(name): + raise ValueError(f"Invalid compiled plan name: {name!r}") + raw_steps = data.get("steps") + if not isinstance(raw_steps, list) or not raw_steps: + raise ValueError("Compiled plan 'steps' must be a non-empty list.") + return cls( + name=name, + description=str(data.get("description") or f"Compiled JIT workflow {name}"), + param_names=tuple(str(p) for p in data.get("param_names", ())), + secret_params=tuple(str(p) for p in data.get("secret_params", ())), + steps=tuple(CompiledStep.from_dict(s) for s in raw_steps), + readback_mode=str(data.get("readback_mode", "fresh_reload")), + readback_expectations=dict(data.get("readback_expectations") or {}), + stats=CompiledPlanStats.from_dict(data.get("stats") or {}), + schema_version=schema, + ) + + def save( + self, + path: Union[str, Path], + *, + params_to_audit: Optional[Mapping[str, Any]] = None, + ) -> Path: + """Atomically persist this compiled plan to ``path``.""" + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + payload = self.to_json(indent=2) + "\n" + if params_to_audit: + ParameterBinder.assert_no_secrets_leaked(payload, params_to_audit) + fd, tmp_name = tempfile.mkstemp( + prefix=f".{target.name}.", + suffix=".tmp", + dir=str(target.parent), + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(payload) + os.replace(tmp_name, target) + except BaseException: + try: + os.unlink(tmp_name) + except OSError: + pass + raise + return target + + @classmethod + def load(cls, path: Union[str, Path]) -> CompiledPlan: + target = Path(path) + raw = json.loads(target.read_text(encoding="utf-8")) + if not isinstance(raw, Mapping): + raise ValueError(f"Compiled plan at {target} must be a JSON object.") + return cls.from_dict(raw) + + def to_workflow_tool_spec(self) -> WorkflowToolSpec: + """Expose this compiled plan as a verified ``mcpify.WorkflowToolSpec``.""" + properties: dict[str, Any] = {} + for pname in self.param_names: + desc = ( + f"Secret parameter '{pname}' (never persisted in compiled plan)." + if pname in self.secret_params + else f"Workflow parameter '{pname}'." + ) + properties[pname] = {"type": "string", "description": desc} + + input_schema: dict[str, Any] = { + "type": "object", + "properties": properties, + "required": list(self.param_names), + "additionalProperties": False, + } + mcp_steps = tuple( + { + "op": f"jit.{step.action}", + "selectors": list(step.selectors), + "value": step.value, + "post_condition": step.post_condition, + } + for step in self.steps + ) + readback_contract: dict[str, Any] = { + "kind": f"jit_{self.readback_mode}", + "expected": dict(self.readback_expectations), + } + return WorkflowToolSpec( + name=self.name, + description=self.description, + input_schema=input_schema, + steps=mcp_steps, + readback_contract=readback_contract, + safety_policy=SafetyPolicy(), + schema_version=COMPILED_PLAN_SCHEMA, + ) + + +@dataclass(frozen=True) +class JitResult: + """Structured result returned by a ``jit_wrap``-decorated workflow.""" + + mode: JitMode + status: JitStatus + latency_ms: float + estimated_usd: float + receipt: Optional[SignedReceipt] = None + healed_steps: tuple[int, ...] = () + plan_path: Optional[Path] = None + reason: str = "" + value: Any = None + stats: Optional[CompiledPlanStats] = None + + +def format_scorecard(result: JitResult) -> str: + """Format a compact terminal scorecard for a ``JitResult``.""" + receipt_label = ( + f"signed ({result.receipt.receipt_digest[:12]})" + if result.receipt is not None + else "unsigned" + ) + lines = [ + f"[openadapt-jit] mode={result.mode} status={result.status} " + f"latency={result.latency_ms:.1f}ms cost=${result.estimated_usd:.4f} " + f"receipt={receipt_label}" + ] + if result.healed_steps: + lines.append(f" healed_steps={list(result.healed_steps)}") + if result.stats is not None: + lines.append( + f" totals: cold={result.stats.cold_runs} warm={result.stats.warm_runs} " + f"heals={result.stats.heals} " + f"saved={result.stats.total_ms_saved:.1f}ms / ${result.stats.total_usd_saved:.4f}" + ) + if result.reason: + lines.append(f" reason: {result.reason}") + return "\n".join(lines) + + +@dataclass +class _RecordedAction: + action: StepAction + selectors: tuple[str, ...] = () + value: Optional[str] = None + post_condition: Optional[str] = None + + +class _RecordingLocatorProxy: + """Thin proxy over Playwright-style locators (``locator``, ``get_by_role``, etc.).""" + + def __init__( + self, + raw_locator: Any, + selectors: tuple[str, ...], + sink: list[_RecordedAction], + ) -> None: + self._raw = raw_locator + self._selectors = selectors + self._sink = sink + + def click(self, *args: Any, **kwargs: Any) -> Any: + self._sink.append(_RecordedAction(action="click", selectors=self._selectors)) + return self._raw.click(*args, **kwargs) + + def fill(self, value: str, *args: Any, **kwargs: Any) -> Any: + self._sink.append( + _RecordedAction(action="fill", selectors=self._selectors, value=str(value)) + ) + return self._raw.fill(value, *args, **kwargs) + + def select_option(self, value: str, *args: Any, **kwargs: Any) -> Any: + self._sink.append( + _RecordedAction( + action="select", selectors=self._selectors, value=str(value) + ) + ) + return self._raw.select_option(value, *args, **kwargs) + + def press(self, key: str, *args: Any, **kwargs: Any) -> Any: + self._sink.append( + _RecordedAction(action="press", selectors=self._selectors, value=str(key)) + ) + return self._raw.press(key, *args, **kwargs) + + def __getattr__(self, item: str) -> Any: + return getattr(self._raw, item) + + +class RecordingPageProxy: + """Thin page wrapper that records UI actions during Cold Run and Healing. + + Supports both sync and async page objects (Playwright ``Page`` or test + doubles) without importing Playwright. + """ + + def __init__(self, page: Any) -> None: + self._page = page + self.recorded: list[_RecordedAction] = [] + + def _selectors_for( + self, + primary: str, + *, + fallback_selectors: Optional[tuple[str, ...]] = None, + ) -> tuple[str, ...]: + chain: list[str] = [primary] + if fallback_selectors: + for item in fallback_selectors: + if item and item not in chain: + chain.append(item) + # Ask the page if it can report extra semantic fallback selectors (role/label/text). + hint_fn = getattr(self._page, "fallback_selectors_for", None) + if callable(hint_fn): + extra = hint_fn(primary) + if isinstance(extra, (list, tuple)): + for item in extra: + s = str(item) + if s and s not in chain: + chain.append(s) + return tuple(chain) + + def goto(self, url: str, *args: Any, **kwargs: Any) -> Any: + self.recorded.append(_RecordedAction(action="goto", value=str(url))) + return self._page.goto(url, *args, **kwargs) + + def click(self, selector: str, *args: Any, **kwargs: Any) -> Any: + self.recorded.append( + _RecordedAction(action="click", selectors=self._selectors_for(selector)) + ) + return self._page.click(selector, *args, **kwargs) + + def fill(self, selector: str, value: str, *args: Any, **kwargs: Any) -> Any: + self.recorded.append( + _RecordedAction( + action="fill", + selectors=self._selectors_for(selector), + value=str(value), + ) + ) + return self._page.fill(selector, value, *args, **kwargs) + + def select_option( + self, selector: str, value: str, *args: Any, **kwargs: Any + ) -> Any: + self.recorded.append( + _RecordedAction( + action="select", + selectors=self._selectors_for(selector), + value=str(value), + ) + ) + return self._page.select_option(selector, value, *args, **kwargs) + + def select(self, selector: str, value: str, *args: Any, **kwargs: Any) -> Any: + self.recorded.append( + _RecordedAction( + action="select", + selectors=self._selectors_for(selector), + value=str(value), + ) + ) + if hasattr(self._page, "select"): + return self._page.select(selector, value, *args, **kwargs) + return self._page.select_option(selector, value, *args, **kwargs) + + def press(self, selector: str, key: str, *args: Any, **kwargs: Any) -> Any: + self.recorded.append( + _RecordedAction( + action="press", + selectors=self._selectors_for(selector), + value=str(key), + ) + ) + return self._page.press(selector, key, *args, **kwargs) + + def locator( + self, selector: str, *args: Any, **kwargs: Any + ) -> _RecordingLocatorProxy: + return _RecordingLocatorProxy( + self._page.locator(selector, *args, **kwargs), + self._selectors_for(selector), + self.recorded, + ) + + def get_by_role( + self, role: str, *, name: Optional[str] = None, **kwargs: Any + ) -> _RecordingLocatorProxy: + sel = f"role={role}[name={name}]" if name else f"role={role}" + return _RecordingLocatorProxy( + self._page.get_by_role(role, name=name, **kwargs), + (sel,), + self.recorded, + ) + + def get_by_label(self, text: str, **kwargs: Any) -> _RecordingLocatorProxy: + return _RecordingLocatorProxy( + self._page.get_by_label(text, **kwargs), + (f"label={text}",), + self.recorded, + ) + + def get_by_text(self, text: str, **kwargs: Any) -> _RecordingLocatorProxy: + return _RecordingLocatorProxy( + self._page.get_by_text(text, **kwargs), + (f"text={text}",), + self.recorded, + ) + + def __getattr__(self, item: str) -> Any: + return getattr(self._page, item) + + +def _bind_recorded_actions( + recorded: list[_RecordedAction], + params: Mapping[str, Any], +) -> tuple[CompiledStep, ...]: + steps: list[CompiledStep] = [] + for item in recorded: + bound_selectors = tuple( + ParameterBinder.bind_value(sel, params)[0] for sel in item.selectors + ) + bound_val = ( + ParameterBinder.bind_value(item.value, params)[0] + if item.value is not None + else None + ) + bound_post = ( + ParameterBinder.bind_value(item.post_condition, params)[0] + if item.post_condition is not None + else None + ) + steps.append( + CompiledStep( + action=item.action, + selectors=bound_selectors, + value=bound_val, + post_condition=bound_post, + ) + ) + return tuple(steps) + + +def _dispatch_selector_sync( + page: Any, + action: StepAction, + selector: str, + value: Optional[str], +) -> None: + if selector.startswith("role="): + body = selector[len("role=") :] + if "[name=" in body and body.endswith("]"): + role, rest = body.split("[name=", 1) + target = page.get_by_role(role, name=rest[:-1]) + else: + target = page.get_by_role(body) + if action == "click": + target.click() + elif action == "fill": + target.fill(value or "") + elif action == "select": + target.select_option(value or "") + elif action == "press": + target.press(value or "") + return + + if selector.startswith("label="): + target = page.get_by_label(selector[len("label=") :]) + if action == "click": + target.click() + elif action == "fill": + target.fill(value or "") + elif action == "select": + target.select_option(value or "") + elif action == "press": + target.press(value or "") + return + + if selector.startswith("text="): + target = page.get_by_text(selector[len("text=") :]) + if action == "click": + target.click() + elif action == "fill": + target.fill(value or "") + elif action == "select": + target.select_option(value or "") + elif action == "press": + target.press(value or "") + return + + if action == "click": + page.click(selector) + elif action == "fill": + page.fill(selector, value or "") + elif action == "select": + if hasattr(page, "select_option"): + page.select_option(selector, value or "") + else: + page.select(selector, value or "") + elif action == "press": + page.press(selector, value or "") + + +async def _dispatch_selector_async( + page: Any, + action: StepAction, + selector: str, + value: Optional[str], +) -> None: + if selector.startswith("role="): + body = selector[len("role=") :] + if "[name=" in body and body.endswith("]"): + role, rest = body.split("[name=", 1) + target = page.get_by_role(role, name=rest[:-1]) + else: + target = page.get_by_role(body) + if action == "click": + await target.click() + elif action == "fill": + await target.fill(value or "") + elif action == "select": + await target.select_option(value or "") + elif action == "press": + await target.press(value or "") + return + + if selector.startswith("label="): + target = page.get_by_label(selector[len("label=") :]) + if action == "click": + await target.click() + elif action == "fill": + await target.fill(value or "") + elif action == "select": + await target.select_option(value or "") + elif action == "press": + await target.press(value or "") + return + + if selector.startswith("text="): + target = page.get_by_text(selector[len("text=") :]) + if action == "click": + await target.click() + elif action == "fill": + await target.fill(value or "") + elif action == "select": + await target.select_option(value or "") + elif action == "press": + await target.press(value or "") + return + + if action == "click": + await page.click(selector) + elif action == "fill": + await page.fill(selector, value or "") + elif action == "select": + if hasattr(page, "select_option"): + await page.select_option(selector, value or "") + else: + await page.select(selector, value or "") + elif action == "press": + await page.press(selector, value or "") + + +def replay_step_sync( + page: Any, + step_index: int, + step: CompiledStep, + params: Mapping[str, Any], +) -> None: + """Replay one compiled step synchronously using its fallback selector chain.""" + resolved_val = ( + ParameterBinder.substitute(step.value, params) + if step.value is not None + else None + ) + if step.action == "goto": + page.goto(resolved_val or "") + return + + if not step.selectors: + raise StepReplayError(step_index, step, "Step has no selectors.") + + last_err = "no selectors matched" + for raw_sel in step.selectors: + selector = ParameterBinder.substitute(raw_sel, params) + try: + _dispatch_selector_sync(page, step.action, selector, resolved_val) + return + except Exception as exc: # noqa: BLE001 - try next fallback selector + last_err = f"{selector!r}: {exc}" + raise StepReplayError(step_index, step, last_err) + + +async def replay_step_async( + page: Any, + step_index: int, + step: CompiledStep, + params: Mapping[str, Any], +) -> None: + """Replay one compiled step asynchronously using its fallback selector chain.""" + resolved_val = ( + ParameterBinder.substitute(step.value, params) + if step.value is not None + else None + ) + if step.action == "goto": + await page.goto(resolved_val or "") + return + + if not step.selectors: + raise StepReplayError(step_index, step, "Step has no selectors.") + + last_err = "no selectors matched" + for raw_sel in step.selectors: + selector = ParameterBinder.substitute(raw_sel, params) + try: + await _dispatch_selector_async(page, step.action, selector, resolved_val) + return + except Exception as exc: # noqa: BLE001 - try next fallback selector + last_err = f"{selector!r}: {exc}" + raise StepReplayError(step_index, step, last_err) + + +def _reject_secret_expectations( + expectations: Optional[Mapping[str, Any]], + params: Optional[Mapping[str, Any]] = None, +) -> None: + """Reject secret-named keys or secret-param references in readback_expectations.""" + if not expectations: + return + secret_names = ( + {k for k in params if ParameterBinder.is_secret_param(k)} if params else set() + ) + secret_vals = ( + { + str(v) + for k, v in params.items() + if ParameterBinder.is_secret_param(k) and str(v) + } + if params + else set() + ) + + def _walk(obj: Any, path: str) -> None: + if isinstance(obj, Mapping): + for key, val in obj.items(): + key_s = str(key) + if ParameterBinder.is_secret_param(key_s): + raise ValueError( + f"Secret-named key {key_s!r} is not allowed in readback_expectations." + ) + _walk(val, f"{path}.{key_s}") + elif isinstance(obj, (list, tuple)): + for idx, item in enumerate(obj): + _walk(item, f"{path}[{idx}]") + elif isinstance(obj, str): + for ref in _TEMPLATE_VAR_RE.findall(obj): + if ParameterBinder.is_secret_param(ref) or ref in secret_names: + raise ValueError( + f"Secret parameter reference {{{{{ref}}}}} is not allowed in readback_expectations ({path})." + ) + for sval in secret_vals: + if sval in obj: + raise ValueError( + f"Secret parameter value is not allowed in readback_expectations ({path})." + ) + + _walk(expectations, "readback_expectations") + + +def _default_fresh_reload_readback_sync( + page: Any, + params: Mapping[str, Any], + expectations: Mapping[str, Any], +) -> tuple[bool, str]: + """Reload the page and check that non-secret expected values appear in the reloaded DOM.""" + _reject_secret_expectations(expectations, params) + reload_fn = getattr(page, "reload", None) + if not callable(reload_fn): + return False, "Page does not expose reload() for fresh_reload read-back." + reload_fn() + content_fn = getattr(page, "content", None) + text_fn = getattr(page, "inner_text", None) + if callable(content_fn): + body = str(content_fn()) + elif callable(text_fn): + body = str(text_fn("body")) + else: + return False, "Page does not expose content() or inner_text() for read-back." + + expected_map = ( + ParameterBinder.substitute_mapping(expectations, params) + if expectations + else { + k: str(v) + for k, v in params.items() + if not ParameterBinder.is_secret_param(k) + } + ) + if not expected_map: + return False, "No verifiable read-back expectations were supplied." + + missing = [f"{k}={v!r}" for k, v in expected_map.items() if str(v) not in body] + if missing: + return False, f"Fresh reload missing expected value(s): {', '.join(missing)}" + return True, "Fresh reload confirmed expected values." + + +async def _default_fresh_reload_readback_async( + page: Any, + params: Mapping[str, Any], + expectations: Mapping[str, Any], +) -> tuple[bool, str]: + _reject_secret_expectations(expectations, params) + reload_fn = getattr(page, "reload", None) + if not callable(reload_fn): + return False, "Page does not expose reload() for fresh_reload read-back." + await reload_fn() + content_fn = getattr(page, "content", None) + text_fn = getattr(page, "inner_text", None) + if callable(content_fn): + body = str(await content_fn()) + elif callable(text_fn): + body = str(await text_fn("body")) + else: + return False, "Page does not expose content() or inner_text() for read-back." + + expected_map = ( + ParameterBinder.substitute_mapping(expectations, params) + if expectations + else { + k: str(v) + for k, v in params.items() + if not ParameterBinder.is_secret_param(k) + } + ) + if not expected_map: + return False, "No verifiable read-back expectations were supplied." + + missing = [f"{k}={v!r}" for k, v in expected_map.items() if str(v) not in body] + if missing: + return False, f"Fresh reload missing expected value(s): {', '.join(missing)}" + return True, "Fresh reload confirmed expected values." + + +def _run_readback_sync( + *, + page: Any, + params: Mapping[str, Any], + expectations: Mapping[str, Any], + readback_fn: Optional[Callable[..., Any]], +) -> tuple[bool, str]: + _reject_secret_expectations(expectations, params) + try: + ok, reason = ( + _interpret_readback_outcome(readback_fn(page, params)) + if readback_fn is not None + else _default_fresh_reload_readback_sync(page, params, expectations) + ) + except Exception as exc: # noqa: BLE001 - transport/reload error is UNCONFIRMED_WRITE + ok = False + reason = f"Read-back error ({type(exc).__name__}): {exc}" + return ok, ParameterBinder.redact_secrets(reason, params) + + +async def _run_readback_async( + *, + page: Any, + params: Mapping[str, Any], + expectations: Mapping[str, Any], + readback_fn: Optional[Callable[..., Any]], +) -> tuple[bool, str]: + _reject_secret_expectations(expectations, params) + try: + if readback_fn is not None: + rb_raw = readback_fn(page, params) + if inspect.isawaitable(rb_raw): + rb_raw = await rb_raw + ok, reason = _interpret_readback_outcome(rb_raw) + else: + ok, reason = await _default_fresh_reload_readback_async( + page, params, expectations + ) + except Exception as exc: # noqa: BLE001 - transport/reload error is UNCONFIRMED_WRITE + ok = False + reason = f"Read-back error ({type(exc).__name__}): {exc}" + return ok, ParameterBinder.redact_secrets(reason, params) + + +def _interpret_readback_outcome(outcome: Any) -> tuple[bool, str]: + if isinstance(outcome, bool): + return outcome, "readback confirmed" if outcome else "readback returned False" + if ( + isinstance(outcome, tuple) + and len(outcome) == 2 + and isinstance(outcome[0], bool) + ): + return outcome[0], str(outcome[1]) + status = getattr(outcome, "status", None) + if isinstance(status, str): + reason = str( + getattr(outcome, "reason", "") or getattr(outcome, "detail", "") or status + ) + return status.upper() == "VERIFIED", reason + verified = getattr(outcome, "verified", None) + if isinstance(verified, bool): + reason = str(getattr(outcome, "reason", "") or getattr(outcome, "detail", "")) + return verified, reason + return False, f"Unsupported read-back return type: {type(outcome).__name__}" + + +def _maybe_sign_receipt( + *, + plan: CompiledPlan, + params: Mapping[str, Any], + verified: bool, + reason: str, + signing_key: Optional[Ed25519PrivateKey], + llm_calls: int = 0, +) -> Optional[SignedReceipt]: + if signing_key is None or not verified: + return None + redacted_args = { + k: ("" if ParameterBinder.is_secret_param(k) else str(v)) + for k, v in params.items() + } + rb = ReadbackResult( + verdict="VERIFIED", + reason=reason, + expected={ + k: v + for k, v in plan.readback_expectations.items() + if k not in plan.secret_params + }, + observed={"mode": plan.readback_mode}, + ) + spec = plan.to_workflow_tool_spec() + return issue_mcpify_receipt( + tool_name=plan.name, + arguments=redacted_args, + steps=spec.steps, + readback=rb, + signing_key=signing_key, + llm_calls=llm_calls, + ) + + +def _build_plan_from_recording( + *, + name: str, + description: str, + params: Mapping[str, Any], + recorded: list[_RecordedAction], + readback_mode: str, + readback_expectations: Optional[Mapping[str, Any]], + cold_ms: float, + estimated_cold_usd: float, +) -> CompiledPlan: + validated = ParameterBinder.validate_params(params) + secret_params = tuple( + sorted(k for k in validated if ParameterBinder.is_secret_param(k)) + ) + param_names = tuple(sorted(validated.keys())) + steps = _bind_recorded_actions(recorded, validated) + if readback_expectations is not None: + _reject_secret_expectations(readback_expectations, validated) + templated_rb = ParameterBinder.bind_mapping(readback_expectations, validated) + else: + templated_rb = { + k: f"{{{{{k}}}}}" for k in param_names if k not in secret_params + } + return CompiledPlan( + name=name, + description=description or f"Compiled JIT workflow {name}", + param_names=param_names, + secret_params=secret_params, + steps=steps, + readback_mode=readback_mode, + readback_expectations=templated_rb, + stats=CompiledPlanStats( + cold_runs=1, + warm_runs=0, + heals=0, + total_ms_saved=0.0, + total_usd_saved=0.0, + last_cold_ms=cold_ms, + last_cold_usd=estimated_cold_usd, + ), + ) + + +def _invoke_healer_sync( + healer: Callable[..., Any], + proxy: RecordingPageProxy, + params: Mapping[str, Any], + *, + failed_index: int, + failed_step: CompiledStep, +) -> Any: + sig = inspect.signature(healer) + kwargs: dict[str, Any] = {} + if "failed_step_index" in sig.parameters: + kwargs["failed_step_index"] = failed_index + if "failed_step" in sig.parameters: + kwargs["failed_step"] = failed_step + return healer(proxy, dict(params), **kwargs) + + +async def _invoke_healer_async( + healer: Callable[..., Awaitable[Any]], + proxy: RecordingPageProxy, + params: Mapping[str, Any], + *, + failed_index: int, + failed_step: CompiledStep, +) -> Any: + sig = inspect.signature(healer) + kwargs: dict[str, Any] = {} + if "failed_step_index" in sig.parameters: + kwargs["failed_step_index"] = failed_index + if "failed_step" in sig.parameters: + kwargs["failed_step"] = failed_step + return await healer(proxy, dict(params), **kwargs) + + +def jit_wrap( + name: str, + *, + readback: str = "fresh_reload", + cache_dir: Union[str, Path] = DEFAULT_CACHE_DIR, + max_heal_steps: int = 5, + signing_key: Optional[Ed25519PrivateKey] = None, + readback_fn: Optional[Callable[..., Any]] = None, + healer_fn: Optional[Callable[..., Any]] = None, + estimated_cold_usd: float = 0.05, + description: str = "", + readback_expectations: Optional[Mapping[str, Any]] = None, +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """Decorate a sync or async ``fn(page, params)`` with local JIT compilation. + + - **Cold Run (#1):** records actions through ``RecordingPageProxy``, runs + independent read-back, and saves ``/.json`` only when + read-back returns ``VERIFIED``. + - **Warm Run (#2+):** skips ``fn``, replays the cached ``CompiledPlan`` with + substituted ``params``, and runs read-back against the new ``params``. + - **Bounded Self-Healing:** if a step fails during Warm Run, invokes + ``healer_fn`` (or ``fn``) capped at ``max_heal_steps`` and updates the + cached plan on disk only if final read-back passes ``VERIFIED``. + """ + if not _SAFE_NAME_RE.match(name): + raise ValueError(f"Invalid JIT workflow name: {name!r}") + if max_heal_steps < 0: + raise ValueError("max_heal_steps must be >= 0") + _reject_secret_expectations(readback_expectations) + + plan_path = Path(cache_dir) / f"{name}.json" + + def _decorator(fn: Callable[..., Any]) -> Callable[..., Any]: + is_async = inspect.iscoroutinefunction(fn) + + if not is_async: + + @functools.wraps(fn) + def _sync_wrapper(page: Any, params: Mapping[str, Any]) -> JitResult: + t0 = time.perf_counter() + validated = ParameterBinder.validate_params(params) + + # --- COLD RUN --- + if not plan_path.exists(): + proxy = RecordingPageProxy(page) + ret_val = fn(proxy, dict(validated)) + if not proxy.recorded: + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="cold", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + plan_path=None, + reason="Cold run recorded 0 actions; refusing to compile an empty plan.", + value=ret_val, + ) + rb_ok, rb_reason = _run_readback_sync( + page=page, + params=validated, + expectations=readback_expectations or {}, + readback_fn=readback_fn, + ) + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + if not rb_ok: + return JitResult( + mode="cold", + status="UNCONFIRMED_WRITE", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + plan_path=None, + reason=rb_reason, + value=ret_val, + ) + plan = _build_plan_from_recording( + name=name, + description=description, + params=validated, + recorded=proxy.recorded, + readback_mode=readback, + readback_expectations=readback_expectations, + cold_ms=elapsed_ms, + estimated_cold_usd=estimated_cold_usd, + ) + plan.save(plan_path, params_to_audit=validated) + receipt = _maybe_sign_receipt( + plan=plan, + params=validated, + verified=True, + reason=rb_reason, + signing_key=signing_key, + llm_calls=1, + ) + return JitResult( + mode="cold", + status="VERIFIED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + receipt=receipt, + plan_path=plan_path, + reason=rb_reason, + value=ret_val, + stats=plan.stats, + ) + + # --- WARM RUN (+ BOUNDED SELF-HEAL) --- + plan = CompiledPlan.load(plan_path) + candidate_steps = list(plan.steps) + healed_indices: list[int] = [] + heal_actions_used = 0 + idx = 0 + while idx < len(candidate_steps): + step = candidate_steps[idx] + try: + replay_step_sync(page, idx, step, validated) + idx += 1 + except StepReplayError as err: + if heal_actions_used >= max_heal_steps: + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=ParameterBinder.redact_secrets( + f"Exceeded max_heal_steps={max_heal_steps}: {err}", + validated, + ), + stats=plan.stats, + ) + heal_proxy = RecordingPageProxy(page) + active_healer = healer_fn if healer_fn is not None else fn + try: + _invoke_healer_sync( + active_healer, + heal_proxy, + validated, + failed_index=idx, + failed_step=step, + ) + except Exception as heal_exc: # noqa: BLE001 - stop without poisoning cache + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=ParameterBinder.redact_secrets( + f"Self-heal raised at step {idx}: {heal_exc}", + validated, + ), + stats=plan.stats, + ) + + healed_recorded = heal_proxy.recorded + if not healed_recorded or ( + heal_actions_used + len(healed_recorded) > max_heal_steps + ): + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=( + f"Self-heal recorded {len(healed_recorded)} actions " + f"(budget remaining: {max_heal_steps - heal_actions_used})." + ), + stats=plan.stats, + ) + + heal_actions_used += len(healed_recorded) + bound_healed = _bind_recorded_actions( + healed_recorded, validated + ) + healed_with_counts = [ + CompiledStep( + action=s.action, + selectors=s.selectors, + value=s.value, + post_condition=s.post_condition, + healed_count=step.healed_count + 1, + ) + for s in bound_healed + ] + healed_indices.append(idx) + if healer_fn is not None: + # Step-level healer replaced just step `idx`; continue remaining steps. + candidate_steps[idx : idx + 1] = healed_with_counts + idx += len(healed_with_counts) + else: + # Full wrapped agent re-ran the workflow from scratch; replace full plan. + candidate_steps = healed_with_counts + break + + rb_ok, rb_reason = _run_readback_sync( + page=page, + params=validated, + expectations=plan.readback_expectations, + readback_fn=readback_fn, + ) + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + mode: JitMode = "healed" if healed_indices else "warm" + est_usd = estimated_cold_usd if healed_indices else 0.0 + + if not rb_ok: + # Broken heal or failed warm read-back NEVER overwrites the cached plan. + return JitResult( + mode=mode, + status="UNCONFIRMED_WRITE", + latency_ms=elapsed_ms, + estimated_usd=est_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=rb_reason, + stats=plan.stats, + ) + + ms_saved = ( + max(0.0, plan.stats.last_cold_ms - elapsed_ms) + if not healed_indices + else 0.0 + ) + usd_saved = plan.stats.last_cold_usd if not healed_indices else 0.0 + new_stats = CompiledPlanStats( + cold_runs=plan.stats.cold_runs, + warm_runs=plan.stats.warm_runs + (0 if healed_indices else 1), + heals=plan.stats.heals + len(healed_indices), + total_ms_saved=plan.stats.total_ms_saved + ms_saved, + total_usd_saved=plan.stats.total_usd_saved + usd_saved, + last_cold_ms=plan.stats.last_cold_ms, + last_cold_usd=plan.stats.last_cold_usd, + ) + updated_plan = CompiledPlan( + name=plan.name, + description=plan.description, + param_names=plan.param_names, + secret_params=plan.secret_params, + steps=tuple(candidate_steps), + readback_mode=plan.readback_mode, + readback_expectations=plan.readback_expectations, + stats=new_stats, + schema_version=plan.schema_version, + ) + updated_plan.save(plan_path, params_to_audit=validated) + receipt = _maybe_sign_receipt( + plan=updated_plan, + params=validated, + verified=True, + reason=rb_reason, + signing_key=signing_key, + llm_calls=len(healed_indices), + ) + return JitResult( + mode=mode, + status="VERIFIED", + latency_ms=elapsed_ms, + estimated_usd=est_usd, + receipt=receipt, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=rb_reason, + stats=new_stats, + ) + + return _sync_wrapper + + @functools.wraps(fn) + async def _async_wrapper(page: Any, params: Mapping[str, Any]) -> JitResult: + t0 = time.perf_counter() + validated = ParameterBinder.validate_params(params) + + if not plan_path.exists(): + proxy = RecordingPageProxy(page) + ret_val = await fn(proxy, dict(validated)) + if not proxy.recorded: + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="cold", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + plan_path=None, + reason="Cold run recorded 0 actions; refusing to compile an empty plan.", + value=ret_val, + ) + rb_ok, rb_reason = await _run_readback_async( + page=page, + params=validated, + expectations=readback_expectations or {}, + readback_fn=readback_fn, + ) + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + if not rb_ok: + return JitResult( + mode="cold", + status="UNCONFIRMED_WRITE", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + plan_path=None, + reason=rb_reason, + value=ret_val, + ) + plan = _build_plan_from_recording( + name=name, + description=description, + params=validated, + recorded=proxy.recorded, + readback_mode=readback, + readback_expectations=readback_expectations, + cold_ms=elapsed_ms, + estimated_cold_usd=estimated_cold_usd, + ) + plan.save(plan_path, params_to_audit=validated) + receipt = _maybe_sign_receipt( + plan=plan, + params=validated, + verified=True, + reason=rb_reason, + signing_key=signing_key, + llm_calls=1, + ) + return JitResult( + mode="cold", + status="VERIFIED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + receipt=receipt, + plan_path=plan_path, + reason=rb_reason, + value=ret_val, + stats=plan.stats, + ) + + plan = CompiledPlan.load(plan_path) + candidate_steps = list(plan.steps) + healed_indices: list[int] = [] + heal_actions_used = 0 + idx = 0 + while idx < len(candidate_steps): + step = candidate_steps[idx] + try: + await replay_step_async(page, idx, step, validated) + idx += 1 + except StepReplayError as err: + if heal_actions_used >= max_heal_steps: + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=ParameterBinder.redact_secrets( + f"Exceeded max_heal_steps={max_heal_steps}: {err}", + validated, + ), + stats=plan.stats, + ) + heal_proxy = RecordingPageProxy(page) + active_healer = healer_fn if healer_fn is not None else fn + try: + await _invoke_healer_async( + active_healer, + heal_proxy, + validated, + failed_index=idx, + failed_step=step, + ) + except Exception as heal_exc: # noqa: BLE001 + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=ParameterBinder.redact_secrets( + f"Self-heal raised at step {idx}: {heal_exc}", + validated, + ), + stats=plan.stats, + ) + + healed_recorded = heal_proxy.recorded + if not healed_recorded or ( + heal_actions_used + len(healed_recorded) > max_heal_steps + ): + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + return JitResult( + mode="healed", + status="STOPPED", + latency_ms=elapsed_ms, + estimated_usd=estimated_cold_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=( + f"Self-heal recorded {len(healed_recorded)} actions " + f"(budget remaining: {max_heal_steps - heal_actions_used})." + ), + stats=plan.stats, + ) + + heal_actions_used += len(healed_recorded) + bound_healed = _bind_recorded_actions(healed_recorded, validated) + healed_with_counts = [ + CompiledStep( + action=s.action, + selectors=s.selectors, + value=s.value, + post_condition=s.post_condition, + healed_count=step.healed_count + 1, + ) + for s in bound_healed + ] + healed_indices.append(idx) + if healer_fn is not None: + candidate_steps[idx : idx + 1] = healed_with_counts + idx += len(healed_with_counts) + else: + candidate_steps = healed_with_counts + break + + rb_ok, rb_reason = await _run_readback_async( + page=page, + params=validated, + expectations=plan.readback_expectations, + readback_fn=readback_fn, + ) + elapsed_ms = (time.perf_counter() - t0) * 1000.0 + mode: JitMode = "healed" if healed_indices else "warm" + est_usd = estimated_cold_usd if healed_indices else 0.0 + + if not rb_ok: + return JitResult( + mode=mode, + status="UNCONFIRMED_WRITE", + latency_ms=elapsed_ms, + estimated_usd=est_usd, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=rb_reason, + stats=plan.stats, + ) + + ms_saved = ( + max(0.0, plan.stats.last_cold_ms - elapsed_ms) + if not healed_indices + else 0.0 + ) + usd_saved = plan.stats.last_cold_usd if not healed_indices else 0.0 + new_stats = CompiledPlanStats( + cold_runs=plan.stats.cold_runs, + warm_runs=plan.stats.warm_runs + (0 if healed_indices else 1), + heals=plan.stats.heals + len(healed_indices), + total_ms_saved=plan.stats.total_ms_saved + ms_saved, + total_usd_saved=plan.stats.total_usd_saved + usd_saved, + last_cold_ms=plan.stats.last_cold_ms, + last_cold_usd=plan.stats.last_cold_usd, + ) + updated_plan = CompiledPlan( + name=plan.name, + description=plan.description, + param_names=plan.param_names, + secret_params=plan.secret_params, + steps=tuple(candidate_steps), + readback_mode=plan.readback_mode, + readback_expectations=plan.readback_expectations, + stats=new_stats, + schema_version=plan.schema_version, + ) + updated_plan.save(plan_path, params_to_audit=validated) + receipt = _maybe_sign_receipt( + plan=updated_plan, + params=validated, + verified=True, + reason=rb_reason, + signing_key=signing_key, + llm_calls=len(healed_indices), + ) + return JitResult( + mode=mode, + status="VERIFIED", + latency_ms=elapsed_ms, + estimated_usd=est_usd, + receipt=receipt, + healed_steps=tuple(healed_indices), + plan_path=plan_path, + reason=rb_reason, + stats=new_stats, + ) + + return _async_wrapper + + return _decorator + + +__all__ = [ + "COMPILED_PLAN_SCHEMA", + "CompiledPlan", + "CompiledPlanStats", + "CompiledStep", + "DEFAULT_CACHE_DIR", + "JitMode", + "JitResult", + "JitStatus", + "ParameterBinder", + "RecordingPageProxy", + "StepAction", + "StepReplayError", + "format_scorecard", + "jit_wrap", + "replay_step_async", + "replay_step_sync", +] diff --git a/packages/verify/src/openadapt_verify/mcpify.py b/packages/verify/src/openadapt_verify/mcpify.py index 3474ab5bdb..d503383cc3 100644 --- a/packages/verify/src/openadapt_verify/mcpify.py +++ b/packages/verify/src/openadapt_verify/mcpify.py @@ -262,6 +262,44 @@ def load_workflow_specs(path: Union[str, Path]) -> tuple[WorkflowToolSpec, ...]: return specs +def load_compiled_tools(cache_dir: Union[str, Path]) -> tuple[WorkflowToolSpec, ...]: + """Load all JIT ``CompiledPlan`` JSON files from ``cache_dir`` as MCP tools.""" + from openadapt_verify.jit import COMPILED_PLAN_SCHEMA, CompiledPlan + + root = Path(cache_dir).expanduser() + if not root.is_dir(): + raise FileNotFoundError(f"Compiled plan directory not found: {root}") + resolved_root = root.resolve() + + specs: list[WorkflowToolSpec] = [] + seen: set[str] = set() + for path in sorted(root.glob("*.json")): + resolved_path = path.resolve() + if not resolved_path.is_relative_to(resolved_root): + raise ValueError( + f"Refusing compiled plan symlink escaping cache directory: {path}" + ) + try: + raw = json.loads(resolved_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + raise ValueError(f"Invalid JSON in compiled plan {path}: {exc}") from exc + if ( + not isinstance(raw, Mapping) + or raw.get("schema_version") != COMPILED_PLAN_SCHEMA + ): + continue + plan = CompiledPlan.from_dict(raw) + spec = plan.to_workflow_tool_spec() + if spec.name in seen: + raise ValueError(f"Duplicate compiled tool name in {root}: {spec.name}") + seen.add(spec.name) + specs.append(spec) + + if not specs: + raise ValueError(f"No compiled JIT plans found in {root}") + return tuple(specs) + + @dataclass(frozen=True) class ReadbackResult: """Outcome from the independent system-of-record read-back oracle.""" @@ -1292,11 +1330,17 @@ def _build_parser() -> argparse.ArgumentParser: sub = parser.add_subparsers(dest="command", required=True) serve_cmd = sub.add_parser("serve", help="Run the live stdio MCP server.") - serve_cmd.add_argument( + serve_source = serve_cmd.add_mutually_exclusive_group(required=True) + serve_source.add_argument( "--spec", - required=True, + default=None, help="Path to the compiled workflow pack JSON (.oapack.json).", ) + serve_source.add_argument( + "--from-compiled", + default=None, + help="Directory of JIT CompiledPlan JSON files (.openadapt/compiled) to expose as MCP tools.", + ) serve_cmd.add_argument( "--server-name", default=None, @@ -1312,11 +1356,17 @@ def _build_parser() -> argparse.ArgumentParser: "config", help="Print a copy-paste mcpServers JSON snippet for an MCP client.", ) - config_cmd.add_argument( + config_source = config_cmd.add_mutually_exclusive_group(required=True) + config_source.add_argument( "--spec", - required=True, + default=None, help="Path to the compiled workflow pack JSON (.oapack.json).", ) + config_source.add_argument( + "--from-compiled", + default=None, + help="Directory of JIT CompiledPlan JSON files (.openadapt/compiled).", + ) config_cmd.add_argument( "--client", choices=SUPPORTED_CLIENTS, @@ -1352,7 +1402,11 @@ def main(argv: Optional[Sequence[str]] = None) -> int: args = parser.parse_args(argv) if args.command == "serve": - specs = load_workflow_specs(args.spec) + specs = ( + load_compiled_tools(args.from_compiled) + if args.from_compiled + else load_workflow_specs(args.spec) + ) server_name = args.server_name or specs[0].name signing_key = load_signing_key(args.signing_key) if args.signing_key else None server = McpifyServer(specs, server_name=server_name, signing_key=signing_key) @@ -1371,12 +1425,37 @@ def main(argv: Optional[Sequence[str]] = None) -> int: return 0 if args.command == "config": - snippet = generate_mcp_client_config( - args.spec, - server_name=args.server_name, - client=args.client, - signing_key_path=args.signing_key, - ) + if args.from_compiled: + resolved_dir = Path(args.from_compiled).expanduser().resolve() + specs = load_compiled_tools(resolved_dir) + effective_name = args.server_name or specs[0].name + cmd_args = [ + "-m", + "openadapt_verify.mcpify", + "serve", + "--from-compiled", + str(resolved_dir), + "--server-name", + effective_name, + ] + if args.signing_key: + cmd_args.extend( + [ + "--signing-key", + str(Path(args.signing_key).expanduser().resolve()), + ] + ) + entry: dict[str, Any] = {"command": sys.executable, "args": cmd_args} + if args.client == "cursor": + entry["type"] = "stdio" + snippet = {"mcpServers": {effective_name: entry}} + else: + snippet = generate_mcp_client_config( + args.spec, + server_name=args.server_name, + client=args.client, + signing_key_path=args.signing_key, + ) print(json.dumps(snippet, indent=2)) return 0 diff --git a/packages/verify/tests/test_jit.py b/packages/verify/tests/test_jit.py new file mode 100644 index 0000000000..8bc40516d1 --- /dev/null +++ b/packages/verify/tests/test_jit.py @@ -0,0 +1,589 @@ +"""Unit and mock-page tests for openadapt_verify.jit and mcpify --from-compiled.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import Any + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from openadapt_verify import ( + CompiledPlan, + McpifyServer, + ParameterBinder, + ReadbackResult, + format_scorecard, + jit_wrap, + load_compiled_tools, + verify_mcpify_receipt, +) +from openadapt_verify.mcpify import main as mcpify_main + + +class _MockPortalPage: + """In-memory mock page supporting Playwright-like sync actions and reload.""" + + def __init__( + self, *, submit_selector: str = "#submit-btn", persist: bool = True + ) -> None: + self.url: str = "about:blank" + self.submit_selector: str = submit_selector + self.persist: bool = persist + self.draft: dict[str, str] = {} + self.saved_records: list[dict[str, str]] = [] + self.reloaded: bool = False + self.available_selectors: set[str] = { + "#record-id", + "#amount", + "#secret-pin", + submit_selector, + } + + def rename_submit_button(self, new_selector: str) -> None: + self.available_selectors.discard(self.submit_selector) + self.submit_selector = new_selector + self.available_selectors.add(new_selector) + + def goto(self, url: str) -> None: + self.url = url + + def fill(self, selector: str, value: str) -> None: + if selector not in self.available_selectors: + raise RuntimeError(f"Selector not found: {selector}") + self.draft[selector] = value + + def select_option(self, selector: str, value: str) -> None: + if selector not in self.available_selectors: + raise RuntimeError(f"Selector not found: {selector}") + self.draft[selector] = value + + def press(self, selector: str, key: str) -> None: + if selector not in self.available_selectors: + raise RuntimeError(f"Selector not found: {selector}") + self.draft[f"{selector}:key"] = key + + def click(self, selector: str) -> None: + if selector not in self.available_selectors: + raise RuntimeError(f"Selector not found: {selector}") + if selector == self.submit_selector and self.persist: + self.saved_records.append(dict(self.draft)) + + def reload(self) -> None: + self.reloaded = True + + def content(self) -> str: + # Fresh reload renders only persisted records (never transient draft). + return json.dumps(self.saved_records) + + +class _AsyncMockPortalPage: + """Async counterpart of _MockPortalPage for async jit_wrap tests.""" + + def __init__( + self, *, submit_selector: str = "#submit-btn", persist: bool = True + ) -> None: + self._sync = _MockPortalPage(submit_selector=submit_selector, persist=persist) + + async def goto(self, url: str) -> None: + self._sync.goto(url) + + async def fill(self, selector: str, value: str) -> None: + self._sync.fill(selector, value) + + async def click(self, selector: str) -> None: + self._sync.click(selector) + + async def reload(self) -> None: + self._sync.reload() + + async def content(self) -> str: + return self._sync.content() + + +def test_parameter_binder_longest_match_empty_refusal_and_secret_detection() -> None: + params = {"short_num": "100", "long_num": "10000", "password": "s3cr3t-value"} + templated, bound = ParameterBinder.bind_value("total=10000 ref=100", params) + assert templated == "total={{long_num}} ref={{short_num}}" + assert set(bound) == {"long_num", "short_num"} + + assert ParameterBinder.is_secret_param("password") is True + assert ParameterBinder.is_secret_param("api_key") is True + assert ParameterBinder.is_secret_param("auth_token") is True + assert ParameterBinder.is_secret_param("record_id") is False + + with pytest.raises(ValueError, match="must not be empty"): + ParameterBinder.bind_value("abc", {"record_id": " "}) + + with pytest.raises(ValueError, match="leaked into compiled plan"): + ParameterBinder.assert_no_secrets_leaked( + '{"value": "s3cr3t-value"}', + {"password": "s3cr3t-value"}, + ) + + +def test_cold_run_compiles_and_warm_run_skips_agent_with_different_params( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + signing_key = Ed25519PrivateKey.generate() + agent_calls = 0 + + @jit_wrap( + "submit_invoice", + cache_dir=cache_dir, + signing_key=signing_key, + estimated_cold_usd=0.08, + description="Submit an invoice and verify via fresh reload.", + ) + def submit_invoice(page: Any, params: dict[str, str]) -> str: + nonlocal agent_calls + agent_calls += 1 + page.goto("https://portal.example.test/invoices") + page.fill("#record-id", params["invoice_id"]) + page.fill("#amount", params["amount"]) + page.click("#submit-btn") + return "submitted" + + # Run #1: Cold run invokes agent, verifies via fresh reload, writes cache + signs receipt + page1 = _MockPortalPage() + r1 = submit_invoice(page1, {"invoice_id": "INV-1001", "amount": "250.00"}) + assert r1.mode == "cold" + assert r1.status == "VERIFIED" + assert agent_calls == 1 + assert r1.plan_path == cache_dir / "submit_invoice.json" + assert r1.plan_path.is_file() + assert r1.receipt is not None + assert ( + verify_mcpify_receipt(r1.receipt, trusted_public_key=signing_key.public_key()) + is True + ) + + # Compiled plan on disk must be parameterized (no hardcoded cold-run values) + raw_plan = r1.plan_path.read_text(encoding="utf-8") + assert "{{invoice_id}}" in raw_plan + assert "{{amount}}" in raw_plan + assert "INV-1001" not in raw_plan + assert "250.00" not in raw_plan + + # Run #2: Warm run with DIFFERENT params skips agent completely (0 agent calls) + page2 = _MockPortalPage() + r2 = submit_invoice(page2, {"invoice_id": "INV-2099", "amount": "999.50"}) + assert r2.mode == "warm" + assert r2.status == "VERIFIED" + assert r2.estimated_usd == 0.0 + assert agent_calls == 1 # Agent was NOT called on warm run! + assert page2.reloaded is True + assert page2.saved_records == [{"#record-id": "INV-2099", "#amount": "999.50"}] + assert r2.stats is not None + assert r2.stats.cold_runs == 1 + assert r2.stats.warm_runs == 1 + assert r2.stats.total_usd_saved == pytest.approx(0.08) + + scorecard = format_scorecard(r2) + assert "mode=warm status=VERIFIED" in scorecard + assert "cost=$0.0000" in scorecard + + +def test_cold_run_unconfirmed_write_refuses_to_write_cache(tmp_path: Path) -> None: + cache_dir = tmp_path / "compiled" + + @jit_wrap("silent_drop", cache_dir=cache_dir) + def silent_drop(page: Any, params: dict[str, str]) -> None: + page.goto("https://portal.example.test/invoices") + page.fill("#record-id", params["invoice_id"]) + page.click("#submit-btn") + + # Portal silently drops the write on reload -> read-back fails -> NO cache written + page = _MockPortalPage(persist=False) + res = silent_drop(page, {"invoice_id": "INV-404"}) + assert res.mode == "cold" + assert res.status == "UNCONFIRMED_WRITE" + assert res.plan_path is None + assert not (cache_dir / "silent_drop.json").exists() + + +def test_warm_run_dom_mutation_triggers_bounded_self_heal_and_run3_is_warm_again( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + agent_calls = 0 + healer_calls = 0 + + def step_healer( + page: Any, + params: dict[str, str], + *, + failed_step_index: int, + failed_step: Any, + ) -> None: + nonlocal healer_calls + healer_calls += 1 + assert failed_step_index == 3 + assert failed_step.action == "click" + # Healer discovers the renamed submit button on the live page + page.click("#submit-btn-v2") + + @jit_wrap( + "heal_workflow", + cache_dir=cache_dir, + healer_fn=step_healer, + max_heal_steps=3, + ) + def workflow(page: Any, params: dict[str, str]) -> None: + nonlocal agent_calls + agent_calls += 1 + page.goto("https://portal.example.test/invoices") + page.fill("#record-id", params["invoice_id"]) + page.fill("#amount", params["amount"]) + page.click("#submit-btn") + + # Run #1: Cold + r1 = workflow(_MockPortalPage(), {"invoice_id": "INV-1", "amount": "10.00"}) + assert r1.mode == "cold" and r1.status == "VERIFIED" + assert agent_calls == 1 + + # Run #2: Submit button renamed to #submit-btn-v2 -> step 3 heals -> cache updated + mutated_page = _MockPortalPage() + mutated_page.rename_submit_button("#submit-btn-v2") + r2 = workflow(mutated_page, {"invoice_id": "INV-2", "amount": "20.00"}) + assert r2.mode == "healed" + assert r2.status == "VERIFIED" + assert r2.healed_steps == (3,) + assert healer_calls == 1 + assert agent_calls == 1 + + # Run #3: Warm again on the mutated UI with 0 healer and 0 agent calls! + mutated_page_3 = _MockPortalPage(submit_selector="#submit-btn-v2") + r3 = workflow(mutated_page_3, {"invoice_id": "INV-3", "amount": "30.00"}) + assert r3.mode == "warm" + assert r3.status == "VERIFIED" + assert r3.healed_steps == () + assert healer_calls == 1 + assert agent_calls == 1 + assert mutated_page_3.saved_records == [{"#record-id": "INV-3", "#amount": "30.00"}] + + +def test_failed_self_heal_does_not_overwrite_cached_plan(tmp_path: Path) -> None: + cache_dir = tmp_path / "compiled" + + def bad_healer(page: Any, params: dict[str, str]) -> None: + # Clicks a harmless selector without persisting the write + page.fill("#amount", params["amount"]) + + @jit_wrap("no_poison", cache_dir=cache_dir, healer_fn=bad_healer, max_heal_steps=2) + def workflow(page: Any, params: dict[str, str]) -> None: + page.goto("https://portal.example.test/invoices") + page.fill("#record-id", params["invoice_id"]) + page.fill("#amount", params["amount"]) + page.click("#submit-btn") + + # Cold run succeeds and caches #submit-btn + r1 = workflow(_MockPortalPage(), {"invoice_id": "INV-10", "amount": "50.00"}) + assert r1.status == "VERIFIED" + plan_file = cache_dir / "no_poison.json" + before_bytes = plan_file.read_text(encoding="utf-8") + + # Mutated page where healer fails to persist -> UNCONFIRMED_WRITE -> cache untouched! + mutated = _MockPortalPage(submit_selector="#renamed-btn") + r2 = workflow(mutated, {"invoice_id": "INV-11", "amount": "60.00"}) + assert r2.mode == "healed" + assert r2.status == "UNCONFIRMED_WRITE" + assert plan_file.read_text(encoding="utf-8") == before_bytes + + +def test_secret_named_params_never_persisted_in_plaintext(tmp_path: Path) -> None: + cache_dir = tmp_path / "compiled" + + @jit_wrap("secret_safe", cache_dir=cache_dir) + def login_and_submit(page: Any, params: dict[str, str]) -> None: + page.goto("https://portal.example.test/secure") + page.fill("#record-id", params["record_id"]) + page.fill("#secret-pin", params["api_key"]) + page.click("#submit-btn") + + secret_val = "sk-live-super-secret-998877" + r1 = login_and_submit( + _MockPortalPage(), + {"record_id": "REC-77", "api_key": secret_val}, + ) + assert r1.status == "VERIFIED" + assert r1.plan_path is not None + disk_text = r1.plan_path.read_text(encoding="utf-8") + assert secret_val not in disk_text + assert "{{api_key}}" in disk_text + + loaded = CompiledPlan.load(r1.plan_path) + assert loaded.secret_params == ("api_key",) + assert "api_key" not in loaded.readback_expectations + + +def test_async_jit_wrap_cold_and_warm(tmp_path: Path) -> None: + cache_dir = tmp_path / "compiled" + calls = 0 + + @jit_wrap("async_invoice", cache_dir=cache_dir) + async def submit_async(page: Any, params: dict[str, str]) -> str: + nonlocal calls + calls += 1 + await page.goto("https://portal.example.test/async") + await page.fill("#record-id", params["invoice_id"]) + await page.click("#submit-btn") + return "ok" + + r1 = asyncio.run(submit_async(_AsyncMockPortalPage(), {"invoice_id": "ASYNC-1"})) + assert r1.mode == "cold" and r1.status == "VERIFIED" + assert calls == 1 + + page2 = _AsyncMockPortalPage() + r2 = asyncio.run(submit_async(page2, {"invoice_id": "ASYNC-2"})) + assert r2.mode == "warm" and r2.status == "VERIFIED" + assert calls == 1 + assert page2._sync.saved_records == [{"#record-id": "ASYNC-2"}] + + +def test_mcpify_from_compiled_exposes_compiled_plan_as_callable_mcp_tool( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + cache_dir = tmp_path / "compiled" + + @jit_wrap( + "create_claim", cache_dir=cache_dir, description="Create a claim in the portal." + ) + def create_claim(page: Any, params: dict[str, str]) -> None: + page.goto("https://portal.example.test/claims") + page.fill("#record-id", params["claim_id"]) + page.fill("#amount", params["amount"]) + page.click("#submit-btn") + + r1 = create_claim(_MockPortalPage(), {"claim_id": "CLM-1", "amount": "120.00"}) + assert r1.status == "VERIFIED" + + # 1. load_compiled_tools converts .openadapt/compiled/*.json to WorkflowToolSpec + specs = load_compiled_tools(cache_dir) + assert len(specs) == 1 + assert specs[0].name == "create_claim" + assert set(specs[0].input_schema["required"]) == {"claim_id", "amount"} + + # 2. McpifyServer lists and executes the compiled tool with verified read-back + server = McpifyServer( + specs, + runner=lambda _spec, args: {"written": args}, + readback_oracle=lambda _spec, args, _out: ReadbackResult( + verdict="VERIFIED", + reason="Portal reload confirmed claim.", + expected=dict(args), + observed=dict(args), + ), + ) + server.handle_message( + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}} + ) + server.handle_message({"jsonrpc": "2.0", "method": "notifications/initialized"}) + + listed = server.handle_message({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + assert listed is not None + assert [t["name"] for t in listed["result"]["tools"]] == ["create_claim"] + + called = server.handle_message( + { + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "create_claim", + "arguments": {"claim_id": "CLM-999", "amount": "450.00"}, + }, + } + ) + assert called is not None + assert called["result"]["isError"] is False + payload = json.loads(called["result"]["content"][0]["text"]) + assert payload["status"] == "VERIFIED" + assert payload["llm_calls"] == 0 + + # 3. CLI `config --from-compiled ` outputs valid mcpServers snippet + rc = mcpify_main( + ["config", "--from-compiled", str(cache_dir), "--client", "claude"] + ) + assert rc == 0 + cfg = json.loads(capsys.readouterr().out) + assert "create_claim" in cfg["mcpServers"] + assert "--from-compiled" in cfg["mcpServers"]["create_claim"]["args"] + + +def test_parameter_binder_single_pass_prevents_double_substitution() -> None: + params = {"user": "alice", "field": "user"} + templated, bound = ParameterBinder.bind_value("owner=alice key=user", params) + assert templated == "owner={{user}} key={{field}}" + assert set(bound) == {"user", "field"} + assert ParameterBinder.substitute(templated, params) == "owner=alice key=user" + + +def test_empty_recording_refuses_to_compile_and_from_dict_rejects_empty_steps( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + signing_key = Ed25519PrivateKey.generate() + + @jit_wrap( + "noop_agent", + cache_dir=cache_dir, + signing_key=signing_key, + readback_fn=lambda _p, _params: True, + ) + def noop_agent(_page: Any, _params: dict[str, str]) -> str: + return "did nothing" + + res = noop_agent(_MockPortalPage(), {"invoice_id": "INV-0"}) + assert res.mode == "cold" + assert res.status == "STOPPED" + assert res.plan_path is None + assert res.receipt is None + assert not (cache_dir / "noop_agent.json").exists() + + with pytest.raises(ValueError, match="non-empty list"): + CompiledPlan.from_dict( + { + "schema_version": "openadapt.jit.plan/v1", + "name": "bad_plan", + "steps": [], + } + ) + + +def test_full_agent_fallback_healer_replaces_plan_without_duplicating_prefix( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + submit_sel = "#submit-btn" + + # healer_fn=None -> wrapped fn itself re-runs from scratch on warm failure + @jit_wrap("full_fallback", cache_dir=cache_dir, max_heal_steps=5) + def workflow(page: Any, params: dict[str, str]) -> None: + page.goto("https://portal.example.test/invoices") + page.fill("#record-id", params["invoice_id"]) + page.fill("#amount", params["amount"]) + page.click(submit_sel) + + r1 = workflow(_MockPortalPage(), {"invoice_id": "INV-1", "amount": "10.00"}) + assert r1.mode == "cold" and r1.status == "VERIFIED" + assert len(CompiledPlan.load(cache_dir / "full_fallback.json").steps) == 4 + + # Rename submit button and let full wrapped agent recover + submit_sel = "#submit-btn-v2" + mutated = _MockPortalPage(submit_selector="#submit-btn-v2") + r2 = workflow(mutated, {"invoice_id": "INV-2", "amount": "20.00"}) + assert r2.mode == "healed" and r2.status == "VERIFIED" + + healed_plan = CompiledPlan.load(cache_dir / "full_fallback.json") + # Must be 4 steps, NOT 7 (prefix steps 0..2 must not be duplicated) + assert len(healed_plan.steps) == 4 + assert [s.action for s in healed_plan.steps] == ["goto", "fill", "fill", "click"] + + # Run #3 is warm and clean + page3 = _MockPortalPage(submit_selector="#submit-btn-v2") + r3 = workflow(page3, {"invoice_id": "INV-3", "amount": "30.00"}) + assert r3.mode == "warm" and r3.status == "VERIFIED" + assert page3.saved_records == [{"#record-id": "INV-3", "#amount": "30.00"}] + + +def test_secret_rejected_in_readback_expectations_and_redacted_in_reason( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + + with pytest.raises(ValueError, match="Secret-named key"): + jit_wrap( + "bad_secret_key", + cache_dir=cache_dir, + readback_expectations={"password": "{{password}}"}, + ) + + with pytest.raises(ValueError, match="Secret parameter reference"): + jit_wrap( + "bad_secret_ref", + cache_dir=cache_dir, + readback_expectations={"label": "{{api_key}}"}, + ) + + secret_val = "tok-very-secret-42" + + @jit_wrap( + "redact_reason", + cache_dir=cache_dir, + readback_fn=lambda _p, params: ( + False, + f"rejected token={params['auth_token']}", + ), + ) + def workflow(page: Any, params: dict[str, str]) -> None: + page.fill("#record-id", params["record_id"]) + page.fill("#secret-pin", params["auth_token"]) + page.click("#submit-btn") + + res = workflow(_MockPortalPage(), {"record_id": "R-1", "auth_token": secret_val}) + assert res.status == "UNCONFIRMED_WRITE" + assert secret_val not in res.reason + assert "" in res.reason + + +def test_receipt_llm_calls_readback_error_handling_and_symlink_containment( + tmp_path: Path, +) -> None: + cache_dir = tmp_path / "compiled" + signing_key = Ed25519PrivateKey.generate() + + def step_healer(page: Any, _params: dict[str, str]) -> None: + page.click("#submit-btn-v2") + + @jit_wrap( + "signed_flow", + cache_dir=cache_dir, + signing_key=signing_key, + healer_fn=step_healer, + ) + def workflow(page: Any, params: dict[str, str]) -> None: + page.fill("#record-id", params["record_id"]) + page.click("#submit-btn") + + # Cold run receipt -> llm_calls == 1 + r1 = workflow(_MockPortalPage(), {"record_id": "R-1"}) + assert r1.status == "VERIFIED" and r1.receipt is not None + assert r1.receipt.payload["llm_calls"] == 1 + + # Warm run receipt -> llm_calls == 0 + r2 = workflow(_MockPortalPage(), {"record_id": "R-2"}) + assert r2.mode == "warm" and r2.status == "VERIFIED" and r2.receipt is not None + assert r2.receipt.payload["llm_calls"] == 0 + + # Healed run receipt -> llm_calls == 1 + r3 = workflow( + _MockPortalPage(submit_selector="#submit-btn-v2"), {"record_id": "R-3"} + ) + assert r3.mode == "healed" and r3.status == "VERIFIED" and r3.receipt is not None + assert r3.receipt.payload["llm_calls"] == 1 + + # Reload/transport error during read-back -> UNCONFIRMED_WRITE (no crash) + class _BrokenReloadPage(_MockPortalPage): + def reload(self) -> None: + raise ConnectionError("network reset during reload") + + r4 = workflow( + _BrokenReloadPage(submit_selector="#submit-btn-v2"), {"record_id": "R-4"} + ) + assert r4.status == "UNCONFIRMED_WRITE" + assert "ConnectionError" in r4.reason + + # Symlink escaping cache_dir is refused by load_compiled_tools + outside = tmp_path / "outside.json" + outside.write_text( + (cache_dir / "signed_flow.json").read_text(encoding="utf-8"), encoding="utf-8" + ) + escape_link = cache_dir / "escape.json" + escape_link.symlink_to(outside) + with pytest.raises(ValueError, match="symlink escaping cache directory"): + load_compiled_tools(cache_dir)