diff --git a/packages/flow/openadapt_flow/wrap/__init__.py b/packages/flow/openadapt_flow/wrap/__init__.py index a839dc92d4..bf8fcd0624 100644 --- a/packages/flow/openadapt_flow/wrap/__init__.py +++ b/packages/flow/openadapt_flow/wrap/__init__.py @@ -10,6 +10,19 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Protocol +from openadapt_flow.wrap.checkpoint_spec import ( + CheckpointSpec as CheckpointSpec, +) +from openadapt_flow.wrap.checkpoint_spec import ( + compile_checkpoint_spec as compile_checkpoint_spec, +) +from openadapt_flow.wrap.entity_ledger import ( + CheckpointEnforcer as CheckpointEnforcer, +) +from openadapt_flow.wrap.entity_ledger import ( + EntityLedger as EntityLedger, +) + if TYPE_CHECKING: # Imported lazily: the agent integrations pull in POSIX-only modules, # and building the openadapt-flow parser imports this package. diff --git a/packages/flow/openadapt_flow/wrap/checkpoint_spec.py b/packages/flow/openadapt_flow/wrap/checkpoint_spec.py new file mode 100644 index 0000000000..2fb8373738 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/checkpoint_spec.py @@ -0,0 +1,513 @@ +"""Compile a multi-surface demonstration trace into a layout-independent CheckpointSpec. + +A recorded demonstration trace contains raw UI coordinates (``x``, ``y``, +``viewport``, ``field_rect``), observed entities read from source surfaces, +staged writes on destination surfaces, and irreversible commit requests with +their responses. + +:func:`compile_checkpoint_spec` strips all pixel coordinates, viewports, and +DOM selectors and emits an ``openadapt.checkpoint-spec/v1`` specification with +four semantic checkpoint classes: + +1. ``required_source_reads``: source sections and fields that must be observed + before a downstream commit. +2. ``cross_tab_invariants``: entity values read on one surface that must match + values submitted on another surface (using format-aware normalization). +3. ``approval_rules``: pre-commit policy thresholds and stop-on-uncertainty + gates attached to irreversible commits. +4. ``confirmation_checks``: post-commit confirmation status/field checks and + optional cross-surface confirmation writeback checks. + +Zero per-application hardcoding: all rules are inferred generically from +cross-surface dataflow and explicit operator policy declarations. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from typing import Any + +SPEC_SCHEMA = "openadapt.checkpoint-spec/v1" + +#: Layout keys that must never appear in a compiled CheckpointSpec. +FORBIDDEN_LAYOUT_KEYS: frozenset[str] = frozenset( + {"x", "y", "end_x", "end_y", "viewport", "field_rect", "selector", "xpath", "bbox"} +) + +_ISO_DATE_RE = re.compile(r"^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$") +_US_DATE_RE = re.compile(r"^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$") + + +def normalize_date(value: Any) -> str | None: + """Normalize ``YYYY-MM-DD``, ``YYYY/MM/DD``, or ``MM/DD/YYYY`` into ``YYYY-MM-DD``.""" + if not isinstance(value, str): + return None + text = value.strip() + match = _ISO_DATE_RE.match(text) + if match: + year, month, day = int(match.group(1)), int(match.group(2)), int(match.group(3)) + if 1 <= month <= 12 and 1 <= day <= 31: + return f"{year:04d}-{month:02d}-{day:02d}" + match = _US_DATE_RE.match(text) + if match: + month, day, year = int(match.group(1)), int(match.group(2)), int(match.group(3)) + if 1 <= month <= 12 and 1 <= day <= 31: + return f"{year:04d}-{month:02d}-{day:02d}" + return None + + +def normalize_scalar(value: Any) -> str: + """Case-insensitive, whitespace-collapsed scalar normalization.""" + if value is None: + return "" + return re.sub(r"\s+", " ", str(value).strip()).upper() + + +def normalize_token_set(value: Any) -> frozenset[str]: + """Normalize a list, set, or delimited string of tokens into an uppercase set.""" + if isinstance(value, (list, tuple, set, frozenset)): + return frozenset( + normalize_scalar(item) for item in value if normalize_scalar(item) + ) + if isinstance(value, str) and value.strip(): + return frozenset( + normalize_scalar(part) + for part in re.split(r"[,;\s]+", value.strip()) + if normalize_scalar(part) + ) + return frozenset() + + +def values_match(source_val: Any, dest_val: Any, match_mode: str) -> bool: + """Return True when ``dest_val`` satisfies ``match_mode`` relative to ``source_val``.""" + if match_mode == "exact_ci": + return bool(normalize_scalar(source_val)) and ( + normalize_scalar(source_val) == normalize_scalar(dest_val) + ) + if match_mode == "date_iso": + src_date = normalize_date(source_val) + dst_date = normalize_date(dest_val) + return src_date is not None and dst_date is not None and src_date == dst_date + if match_mode == "set_exact": + src_set = normalize_token_set(source_val) + dst_set = normalize_token_set(dest_val) + return bool(src_set) and src_set == dst_set + if match_mode == "subset_ci": + src_set = normalize_token_set(source_val) + dst_set = normalize_token_set(dest_val) + return bool(dst_set) and dst_set.issubset(src_set) + if match_mode == "contains_ci": + src_s = normalize_scalar(source_val) + dst_s = normalize_scalar(dest_val) + return bool(src_s) and src_s in dst_s + return False + + +def _detect_match_mode(source_val: Any, dest_val: Any) -> str | None: + """Infer whether ``dest_val`` came from ``source_val`` and select a match mode.""" + if source_val is None or dest_val is None: + return None + + if isinstance(source_val, (list, tuple, set)) and isinstance( + dest_val, (list, tuple, set) + ): + src_set = normalize_token_set(source_val) + dst_set = normalize_token_set(dest_val) + if src_set and dst_set and dst_set.issubset(src_set): + return "set_exact" if dst_set == src_set else "subset_ci" + return None + + src_date = normalize_date(source_val) + dst_date = normalize_date(dest_val) + if src_date is not None and dst_date is not None and src_date == dst_date: + return "date_iso" + + src_s = normalize_scalar(source_val) + dst_s = normalize_scalar(dest_val) + if not src_s or not dst_s or len(src_s) < 3: + return None + if src_s == dst_s: + return "exact_ci" + if len(src_s) >= 6 and src_s in dst_s: + return "contains_ci" + return None + + +@dataclass(frozen=True) +class SourceReadCheckpoint: + """A source-surface read that must occur before a downstream commit.""" + + id: str + surface: str + section: str + required_fields: tuple[str, ...] + before_commit: str + + +@dataclass(frozen=True) +class CrossTabInvariant: + """An anchor entity that must match between a source surface and a commit surface.""" + + id: str + source_surface: str + source_field: str + dest_surface: str + dest_field: str + match_mode: str + enforced_on_commit: str + + +@dataclass(frozen=True) +class ApprovalRule: + """Pre-commit policy threshold or approval gate on an irreversible commit.""" + + id: str + surface: str + commit_action: str + field_name: str + operator: str # lte | gte | in + threshold: float | tuple[str, ...] + on_violation: str = "escalate" # escalate | block + description: str = "" + + +@dataclass(frozen=True) +class ConfirmationCheck: + """Post-commit confirmation and optional cross-surface writeback check.""" + + id: str + surface: str + commit_action: str + expected_status_codes: tuple[int, ...] + required_response_fields: tuple[str, ...] + writeback_surface: str | None = None + writeback_field: str | None = None + writeback_before_commit: str | None = None + + +@dataclass(frozen=True) +class CheckpointSpec: + """Compiled, UI-layout-independent checkpoint specification.""" + + schema: str + workflow_id: str + source_trace_id: str + surfaces: tuple[str, ...] + commit_sequence: tuple[str, ...] + required_source_reads: tuple[SourceReadCheckpoint, ...] + cross_tab_invariants: tuple[CrossTabInvariant, ...] + approval_rules: tuple[ApprovalRule, ...] + confirmation_checks: tuple[ConfirmationCheck, ...] + stop_on_uncertainty: bool = True + + def to_dict(self) -> dict[str, Any]: + """Serialize to a JSON-compatible dictionary.""" + return asdict(self) + + def to_json(self, indent: int = 2) -> str: + """Serialize to formatted JSON.""" + return json.dumps(self.to_dict(), indent=indent) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> CheckpointSpec: + """Deserialize and validate layout-independence.""" + assert_layout_independent(data) + rules: list[ApprovalRule] = [] + for raw_rule in data["approval_rules"]: + raw_threshold = raw_rule["threshold"] + threshold: float | tuple[str, ...] = ( + tuple(str(item) for item in raw_threshold) + if isinstance(raw_threshold, (list, tuple)) + else float(raw_threshold) + ) + rules.append( + ApprovalRule( + id=str(raw_rule["id"]), + surface=str(raw_rule["surface"]), + commit_action=str(raw_rule["commit_action"]), + field_name=str(raw_rule["field_name"]), + operator=str(raw_rule["operator"]), + threshold=threshold, + on_violation=str(raw_rule.get("on_violation", "escalate")), + description=str(raw_rule.get("description", "")), + ) + ) + return cls( + schema=str(data["schema"]), + workflow_id=str(data["workflow_id"]), + source_trace_id=str(data["source_trace_id"]), + surfaces=tuple(str(s) for s in data["surfaces"]), + commit_sequence=tuple(str(c) for c in data["commit_sequence"]), + required_source_reads=tuple( + SourceReadCheckpoint( + id=str(r["id"]), + surface=str(r["surface"]), + section=str(r["section"]), + required_fields=tuple(str(f) for f in r["required_fields"]), + before_commit=str(r["before_commit"]), + ) + for r in data["required_source_reads"] + ), + cross_tab_invariants=tuple( + CrossTabInvariant( + id=str(inv["id"]), + source_surface=str(inv["source_surface"]), + source_field=str(inv["source_field"]), + dest_surface=str(inv["dest_surface"]), + dest_field=str(inv["dest_field"]), + match_mode=str(inv["match_mode"]), + enforced_on_commit=str(inv["enforced_on_commit"]), + ) + for inv in data["cross_tab_invariants"] + ), + approval_rules=tuple(rules), + confirmation_checks=tuple( + ConfirmationCheck( + id=str(c["id"]), + surface=str(c["surface"]), + commit_action=str(c["commit_action"]), + expected_status_codes=tuple( + int(code) for code in c["expected_status_codes"] + ), + required_response_fields=tuple( + str(f) for f in c["required_response_fields"] + ), + writeback_surface=c.get("writeback_surface"), + writeback_field=c.get("writeback_field"), + writeback_before_commit=c.get("writeback_before_commit"), + ) + for c in data["confirmation_checks"] + ), + stop_on_uncertainty=bool(data.get("stop_on_uncertainty", True)), + ) + + +def assert_layout_independent(obj: Any, path: str = "$") -> None: + """Raise ValueError if any pixel coordinate, viewport, or selector key appears.""" + if isinstance(obj, Mapping): + for key, value in obj.items(): + if key in FORBIDDEN_LAYOUT_KEYS: + raise ValueError(f"Layout-dependent key {key!r} leaked at {path}.{key}") + assert_layout_independent(value, f"{path}.{key}") + elif isinstance(obj, (list, tuple)): + for idx, item in enumerate(obj): + assert_layout_independent(item, f"{path}[{idx}]") + + +def compile_checkpoint_spec( + trace: Mapping[str, Any], + policy_rules: Sequence[Mapping[str, Any]] | None = None, +) -> CheckpointSpec: + """Compile a recorded multi-surface demonstration trace into a CheckpointSpec. + + Parameters + ---------- + trace: + Mapping with ``meta`` (``id``, ``workflow_id``) and ``events`` (ordered + list of recorded multi-surface events). Raw UI coordinates are ignored. + policy_rules: + Optional operator policy rules (thresholds or allowed value sets) + attached to matching irreversible commits. + """ + meta = trace.get("meta") or {} + events = list(trace.get("events") or []) + workflow_id = str(meta.get("workflow_id", meta.get("id", "unknown-workflow"))) + source_trace_id = str(meta.get("id", "demo-trace")) + + surfaces_seen: list[str] = [] + reads_by_key: dict[tuple[str, str], tuple[str, Any]] = {} + section_fields: dict[tuple[str, str], list[str]] = {} + staged_writes: dict[str, dict[str, Any]] = {} + commit_outputs: dict[tuple[str, str], tuple[str, Any]] = {} + + commit_sequence: list[str] = [] + source_read_checkpoints: list[SourceReadCheckpoint] = [] + invariants: list[CrossTabInvariant] = [] + confirmation_checks: list[ConfirmationCheck] = [] + seen_invariants: set[tuple[str, str, str, str, str]] = set() + seen_source_sections: set[tuple[str, str, str]] = set() + pending_confirmations: dict[str, dict[str, Any]] = {} + + for ev in events: + surface = str(ev.get("surface", "primary")) + if surface not in surfaces_seen: + surfaces_seen.append(surface) + + kind = str(ev.get("kind", "")) + section = str(ev.get("section", "default")) + + read_entities = ev.get("read_entities") or {} + if isinstance(read_entities, Mapping) and read_entities: + sec_key = (surface, section) + section_fields.setdefault(sec_key, []) + for fname, fval in read_entities.items(): + reads_by_key[(surface, str(fname))] = (section, fval) + if str(fname) not in section_fields[sec_key]: + section_fields[sec_key].append(str(fname)) + + if kind in ("type", "attach", "note", "select"): + fname = ev.get("field_name") or ev.get("field_label") + fval = ev.get("value") if "value" in ev else ev.get("text") + if fname is not None and fval is not None: + staged_writes.setdefault(surface, {})[str(fname)] = fval + + for (c_surf, _c_field), (c_action, c_val) in commit_outputs.items(): + if c_surf == surface: + continue + mode = _detect_match_mode(c_val, fval) + if mode is not None and c_action in pending_confirmations: + pending_confirmations[c_action]["writeback_surface"] = surface + pending_confirmations[c_action]["writeback_field"] = str(fname) + + if kind == "submit" or ev.get("action_type") == "irreversible_commit": + commit_action = str(ev.get("commit_action", f"{surface}:submit")) + commit_sequence.append(commit_action) + + payload: dict[str, Any] = dict(staged_writes.get(surface, {})) + if isinstance(ev.get("payload"), Mapping): + payload.update(ev["payload"]) + + matched_source_surfaces: set[str] = set() + for dst_field, dst_val in payload.items(): + for (src_surf, src_field), ( + _src_section, + src_val, + ) in reads_by_key.items(): + if src_surf == surface: + continue + mode = _detect_match_mode(src_val, dst_val) + if mode is None: + continue + inv_key = (src_surf, src_field, surface, dst_field, commit_action) + if inv_key not in seen_invariants: + seen_invariants.add(inv_key) + invariants.append( + CrossTabInvariant( + id=f"inv_{len(invariants) + 1:02d}", + source_surface=src_surf, + source_field=src_field, + dest_surface=surface, + dest_field=dst_field, + match_mode=mode, + enforced_on_commit=commit_action, + ) + ) + matched_source_surfaces.add(src_surf) + + if matched_source_surfaces: + for (src_surf, src_sec), fields_in_sec in section_fields.items(): + if src_surf not in matched_source_surfaces: + continue + req_key = (src_surf, src_sec, commit_action) + if req_key not in seen_source_sections: + seen_source_sections.add(req_key) + source_read_checkpoints.append( + SourceReadCheckpoint( + id=f"read_{len(source_read_checkpoints) + 1:02d}", + surface=src_surf, + section=src_sec, + required_fields=tuple(fields_in_sec), + before_commit=commit_action, + ) + ) + + for conf_meta in pending_confirmations.values(): + if ( + conf_meta.get("writeback_surface") == surface + and conf_meta.get("writeback_before_commit") is None + ): + conf_meta["writeback_before_commit"] = commit_action + + response = ev.get("response") or {} + if isinstance(response, Mapping) and response: + status = int(response.get("status", 200)) + resp_fields = tuple( + str(k) + for k, v in response.items() + if k != "status" and v not in (None, "", False) + ) + pending_confirmations[commit_action] = { + "surface": surface, + "commit_action": commit_action, + "expected_status_codes": (status,) + if 200 <= status < 300 + else (200, 201), + "required_response_fields": resp_fields, + "writeback_surface": None, + "writeback_field": None, + "writeback_before_commit": None, + } + for rf in resp_fields: + commit_outputs[(surface, rf)] = (commit_action, response[rf]) + + for idx, c_action in enumerate(commit_sequence, start=1): + if c_action in pending_confirmations: + meta_c = pending_confirmations[c_action] + confirmation_checks.append( + ConfirmationCheck( + id=f"confirm_{idx:02d}", + surface=meta_c["surface"], + commit_action=meta_c["commit_action"], + expected_status_codes=tuple(meta_c["expected_status_codes"]), + required_response_fields=tuple(meta_c["required_response_fields"]), + writeback_surface=meta_c["writeback_surface"], + writeback_field=meta_c["writeback_field"], + writeback_before_commit=meta_c["writeback_before_commit"], + ) + ) + + approval_rules: list[ApprovalRule] = [] + for idx, rule in enumerate(policy_rules or (), start=1): + raw_threshold = rule["threshold"] + threshold: float | tuple[str, ...] = ( + tuple(str(item) for item in raw_threshold) + if isinstance(raw_threshold, (list, tuple)) + else float(raw_threshold) + ) + approval_rules.append( + ApprovalRule( + id=str(rule.get("id", f"policy_{idx:02d}")), + surface=str(rule["surface"]), + commit_action=str(rule["commit_action"]), + field_name=str(rule["field_name"]), + operator=str(rule["operator"]), + threshold=threshold, + on_violation=str(rule.get("on_violation", "escalate")), + description=str(rule.get("description", "")), + ) + ) + + spec = CheckpointSpec( + schema=SPEC_SCHEMA, + workflow_id=workflow_id, + source_trace_id=source_trace_id, + surfaces=tuple(surfaces_seen), + commit_sequence=tuple(commit_sequence), + required_source_reads=tuple(source_read_checkpoints), + cross_tab_invariants=tuple(invariants), + approval_rules=tuple(approval_rules), + confirmation_checks=tuple(confirmation_checks), + stop_on_uncertainty=True, + ) + assert_layout_independent(spec.to_dict()) + return spec + + +__all__ = [ + "ApprovalRule", + "CheckpointSpec", + "ConfirmationCheck", + "CrossTabInvariant", + "FORBIDDEN_LAYOUT_KEYS", + "SPEC_SCHEMA", + "SourceReadCheckpoint", + "assert_layout_independent", + "compile_checkpoint_spec", + "normalize_date", + "normalize_scalar", + "normalize_token_set", + "values_match", +] diff --git a/packages/flow/openadapt_flow/wrap/entity_ledger.py b/packages/flow/openadapt_flow/wrap/entity_ledger.py new file mode 100644 index 0000000000..7b20d31239 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/entity_ledger.py @@ -0,0 +1,630 @@ +"""Cross-tab EntityLedger and CheckpointEnforcer for ``openadapt wrap``. + +:class:`EntityLedger` records entities observed on source surfaces, staged +writes on destination surfaces, and post-commit confirmation outputs across +tabs/surfaces during a wrapped agent run. + +:class:`CheckpointEnforcer` evaluates a compiled :class:`CheckpointSpec` +against an :class:`EntityLedger` before and after each irreversible commit: + +- Ignores pixel coordinates, viewports, selectors, and navigation order so + frontier agents can adapt to UI layout changes. +- Blocks commits when required source reads were skipped, cross-tab entity + values do not match, or prior confirmation writebacks are missing. +- Escalates or blocks when policy thresholds are exceeded without operator + approval, or when required anchor/policy fields are missing (stopping on + uncertainty). +- Inspects post-commit responses so failed or unconfirmed writes never pass + silently. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +from openadapt_flow.wrap.checkpoint_spec import ( + CheckpointSpec, + normalize_scalar, + values_match, +) + +DECISION_ALLOW = "allow" +DECISION_BLOCK = "block" +DECISION_ESCALATE = "escalate" + +OUTCOME_COMPLETE = "complete" +OUTCOME_BLOCKED = "blocked" +OUTCOME_ESCALATED = "escalated" +OUTCOME_INCOMPLETE = "incomplete" + + +@dataclass(frozen=True) +class CheckpointViolation: + """A single checkpoint failure detected during enforcement.""" + + step_index: int + checkpoint_id: str + code: str + action: str # DECISION_BLOCK | DECISION_ESCALATE + commit_action: str + detail: str + + +@dataclass(frozen=True) +class CommitGateDecision: + """Before-click decision for a single irreversible commit attempt.""" + + commit_action: str + decision: str # DECISION_ALLOW | DECISION_BLOCK | DECISION_ESCALATE + violations: tuple[CheckpointViolation, ...] + + +@dataclass(frozen=True) +class EnforcementReport: + """Outcome of enforcing a CheckpointSpec over an agent trajectory.""" + + trajectory_id: str + outcome: str # OUTCOME_COMPLETE | OUTCOME_BLOCKED | OUTCOME_ESCALATED | OUTCOME_INCOMPLETE + commits_attempted: tuple[str, ...] + commits_executed: tuple[str, ...] + commits_blocked: tuple[str, ...] + violations: tuple[CheckpointViolation, ...] + checked_invariants: int + checked_source_reads: int + checked_policy_rules: int + checked_confirmations: int + + +@dataclass(frozen=True) +class SuiteMetrics: + """Aggregate metrics across a labeled suite of clean and failure trajectories.""" + + total_trajectories: int + clean_count: int + bad_count: int + clean_auto_completed: int + clean_false_escalations: int + bad_caught: int + bad_silent_errors: int + silent_error_rate: float + auto_completion_rate: float + escalation_precision: float + + +class EntityLedger: + """Cross-surface entity ledger for an ``openadapt wrap`` session. + + Tracks what was read on each surface/section, what was staged for writing + on each surface, and what confirmation fields were returned by prior + commits. Carries no pixel coordinates or DOM selectors. + """ + + def __init__(self) -> None: + self._reads: dict[tuple[str, str], Any] = {} + self._sections: set[tuple[str, str]] = set() + self._staged_writes: dict[str, dict[str, Any]] = {} + self._commit_confirmations: dict[str, dict[str, Any]] = {} + + def record_read( + self, surface: str, section: str, entities: Mapping[str, Any] + ) -> None: + """Record non-empty entity observations on ``(surface, section)``.""" + if not entities: + return + self._sections.add((surface, section)) + for field_name, value in entities.items(): + if value is not None and value != "" and value != []: + self._reads[(surface, str(field_name))] = value + + def record_write(self, surface: str, field_name: str, value: Any) -> None: + """Record a staged write, selection, attachment, or note on ``surface``.""" + self._staged_writes.setdefault(surface, {})[str(field_name)] = value + + def record_confirmation( + self, commit_action: str, fields: Mapping[str, Any] + ) -> None: + """Record verified post-commit confirmation outputs for ``commit_action``.""" + self._commit_confirmations[commit_action] = dict(fields) + + def has_section(self, surface: str, section: str) -> bool: + """Return True if ``(surface, section)`` has been observed.""" + return (surface, section) in self._sections + + def has_read(self, surface: str, field_name: str) -> bool: + """Return True if ``(surface, field_name)`` has a non-empty observation.""" + return (surface, field_name) in self._reads + + def get_read(self, surface: str, field_name: str) -> Any: + """Return the last observed value for ``(surface, field_name)``.""" + return self._reads.get((surface, field_name)) + + def staged_payload( + self, surface: str, explicit_payload: Mapping[str, Any] | None = None + ) -> dict[str, Any]: + """Merge staged writes on ``surface`` with an explicit commit payload.""" + merged: dict[str, Any] = dict(self._staged_writes.get(surface, {})) + if explicit_payload: + merged.update(explicit_payload) + return merged + + def get_staged_write(self, surface: str, field_name: str) -> Any: + """Return the staged value for ``(surface, field_name)``, if any.""" + return self._staged_writes.get(surface, {}).get(field_name) + + def get_confirmation(self, commit_action: str) -> dict[str, Any] | None: + """Return recorded confirmation fields for ``commit_action``, if any.""" + return self._commit_confirmations.get(commit_action) + + +def _policy_holds(value: Any, operator: str, threshold: Any) -> bool: + if operator == "lte": + try: + return float(value) <= float(threshold) + except (TypeError, ValueError): + return False + if operator == "gte": + try: + return float(value) >= float(threshold) + except (TypeError, ValueError): + return False + if operator == "in": + allowed = {normalize_scalar(item) for item in threshold} + return normalize_scalar(value) in allowed + return False + + +class CheckpointEnforcer: + """Enforce a compiled :class:`CheckpointSpec` using an :class:`EntityLedger`.""" + + def __init__( + self, + spec: CheckpointSpec, + ledger: EntityLedger | None = None, + ) -> None: + self.spec = spec + self.ledger = ledger if ledger is not None else EntityLedger() + self.checked_invariants = 0 + self.checked_source_reads = 0 + self.checked_policy_rules = 0 + self.checked_confirmations = 0 + + def observe_event(self, event: Mapping[str, Any]) -> None: + """Update the ledger from a non-commit navigation, read, or write event.""" + surface = str(event.get("surface", "primary")) + section = str(event.get("section", "default")) + kind = str(event.get("kind", "")) + + read_entities = event.get("read_entities") or {} + if isinstance(read_entities, Mapping) and read_entities: + self.ledger.record_read(surface, section, read_entities) + + if kind in ("type", "attach", "note", "select"): + fname = event.get("field_name") or event.get("field_label") + fval = event.get("value") if "value" in event else event.get("text") + if fname is not None and fval is not None: + self.ledger.record_write(surface, str(fname), fval) + + def check_before_commit( + self, + *, + step_index: int, + surface: str, + commit_action: str, + payload: Mapping[str, Any] | None = None, + human_approved: bool = False, + ) -> CommitGateDecision: + """Run all pre-commit checkpoints for ``commit_action`` before execution.""" + merged_payload = self.ledger.staged_payload(surface, payload) + step_violations: list[CheckpointViolation] = [] + + # 1. Required source reads + for req in self.spec.required_source_reads: + if req.before_commit != commit_action: + continue + self.checked_source_reads += 1 + if not self.ledger.has_section(req.surface, req.section): + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=req.id, + code="skipped_source_read", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Required source section {req.surface}.{req.section} " + f"was not read before {commit_action}." + ), + ) + ) + continue + missing_fields = [ + f + for f in req.required_fields + if not self.ledger.has_read(req.surface, f) + ] + if missing_fields: + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=req.id, + code="missing_source_field", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Required fields {missing_fields} on " + f"{req.surface}.{req.section} were not observed before {commit_action}." + ), + ) + ) + + # 2. Cross-tab entity consistency invariants + for inv in self.spec.cross_tab_invariants: + if inv.enforced_on_commit != commit_action: + continue + self.checked_invariants += 1 + if not self.ledger.has_read(inv.source_surface, inv.source_field): + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=inv.id, + code="missing_source_anchor", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Cannot match {inv.dest_surface}.{inv.dest_field}: " + f"source anchor {inv.source_surface}.{inv.source_field} was never read." + ), + ) + ) + continue + dst_val = merged_payload.get(inv.dest_field) + if dst_val in (None, "", []): + if self.spec.stop_on_uncertainty: + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=inv.id, + code="missing_dest_field", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Destination field {inv.dest_surface}.{inv.dest_field} " + f"is missing on {commit_action}; stopping on uncertainty." + ), + ) + ) + continue + src_val = self.ledger.get_read(inv.source_surface, inv.source_field) + if not values_match(src_val, dst_val, inv.match_mode): + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=inv.id, + code="cross_tab_entity_mismatch", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Entity mismatch on {inv.dest_field} ({inv.match_mode}): " + f"{inv.source_surface}.{inv.source_field}={src_val!r} != " + f"{inv.dest_surface}.{inv.dest_field}={dst_val!r}." + ), + ) + ) + + # 3. Prior confirmation writebacks required before this commit + for conf in self.spec.confirmation_checks: + if conf.writeback_before_commit != commit_action: + continue + self.checked_confirmations += 1 + prior_out = self.ledger.get_confirmation(conf.commit_action) + if not prior_out: + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=conf.id, + code="missing_prior_confirmation", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Prior commit {conf.commit_action} has no confirmation " + f"before {commit_action}." + ), + ) + ) + continue + if conf.writeback_surface and conf.writeback_field: + wb_val = self.ledger.get_staged_write( + conf.writeback_surface, conf.writeback_field + ) + if wb_val is None or str(wb_val).strip() == "": + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=conf.id, + code="missing_confirmation_writeback", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Required writeback to " + f"{conf.writeback_surface}.{conf.writeback_field} " + f"is missing before {commit_action}." + ), + ) + ) + else: + for rf in conf.required_response_fields: + expected_token = prior_out.get(rf) + if expected_token and not values_match( + expected_token, wb_val, "contains_ci" + ): + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=conf.id, + code="confirmation_writeback_mismatch", + action=DECISION_BLOCK, + commit_action=commit_action, + detail=( + f"Writeback {conf.writeback_surface}.{conf.writeback_field} " + f"does not contain {rf}={expected_token!r}." + ), + ) + ) + + # 4. Pre-commit policy and approval rules + for rule in self.spec.approval_rules: + if rule.commit_action != commit_action or rule.surface != surface: + continue + self.checked_policy_rules += 1 + raw_val = merged_payload.get(rule.field_name) + if raw_val in (None, ""): + if self.spec.stop_on_uncertainty and not human_approved: + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=rule.id, + code="uncertain_policy_field", + action=DECISION_ESCALATE, + commit_action=commit_action, + detail=( + f"Policy field {rule.field_name} missing on {commit_action}; " + f"stopping on uncertainty." + ), + ) + ) + continue + if ( + not _policy_holds(raw_val, rule.operator, rule.threshold) + and not human_approved + ): + step_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=rule.id, + code="policy_violation", + action=rule.on_violation, + commit_action=commit_action, + detail=( + f"Policy {rule.id} violated: {rule.field_name}={raw_val!r} " + f"failed {rule.operator} {rule.threshold!r} without approval." + ), + ) + ) + + if step_violations: + actions = {v.action for v in step_violations} + decision = ( + DECISION_BLOCK if DECISION_BLOCK in actions else DECISION_ESCALATE + ) + return CommitGateDecision( + commit_action=commit_action, + decision=decision, + violations=tuple(step_violations), + ) + + return CommitGateDecision( + commit_action=commit_action, + decision=DECISION_ALLOW, + violations=(), + ) + + def check_after_commit( + self, + *, + step_index: int, + surface: str, + commit_action: str, + response: Mapping[str, Any] | None, + ) -> tuple[CheckpointViolation, ...]: + """Inspect post-commit response and record confirmation fields in the ledger.""" + resp = response or {} + post_violations: list[CheckpointViolation] = [] + for conf in self.spec.confirmation_checks: + if conf.commit_action != commit_action or conf.surface != surface: + continue + self.checked_confirmations += 1 + status = resp.get("status") + if status not in conf.expected_status_codes: + post_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=conf.id, + code="confirmation_status_failed", + action=DECISION_ESCALATE, + commit_action=commit_action, + detail=( + f"Commit {commit_action} returned HTTP {status!r}, " + f"expected {conf.expected_status_codes}." + ), + ) + ) + continue + missing_resp = [ + rf + for rf in conf.required_response_fields + if resp.get(rf) in (None, "", False) + ] + if missing_resp: + post_violations.append( + CheckpointViolation( + step_index=step_index, + checkpoint_id=conf.id, + code="missing_confirmation_field", + action=DECISION_ESCALATE, + commit_action=commit_action, + detail=( + f"Commit {commit_action} response missing required " + f"confirmation fields {missing_resp}." + ), + ) + ) + continue + self.ledger.record_confirmation( + commit_action, {rf: resp[rf] for rf in conf.required_response_fields} + ) + return tuple(post_violations) + + def enforce_trajectory(self, trajectory: Mapping[str, Any]) -> EnforcementReport: + """Enforce ``self.spec`` across a complete recorded or replayed trajectory.""" + traj_id = str(trajectory.get("id", "unknown-trajectory")) + events = list(trajectory.get("events") or []) + + commits_attempted: list[str] = [] + commits_executed: list[str] = [] + commits_blocked: list[str] = [] + violations: list[CheckpointViolation] = [] + + for idx, ev in enumerate(events): + step_i = int(ev.get("i", idx)) + surface = str(ev.get("surface", "primary")) + kind = str(ev.get("kind", "")) + + self.observe_event(ev) + + if kind != "submit" and ev.get("action_type") != "irreversible_commit": + continue + + commit_action = str(ev.get("commit_action", f"{surface}:submit")) + commits_attempted.append(commit_action) + payload = ( + ev.get("payload") if isinstance(ev.get("payload"), Mapping) else None + ) + gate = self.check_before_commit( + step_index=step_i, + surface=surface, + commit_action=commit_action, + payload=payload, + human_approved=bool(ev.get("human_approved", False)), + ) + if gate.decision != DECISION_ALLOW: + violations.extend(gate.violations) + commits_blocked.append(commit_action) + continue + + commits_executed.append(commit_action) + response = ( + ev.get("response") if isinstance(ev.get("response"), Mapping) else None + ) + post_violations = self.check_after_commit( + step_index=step_i, + surface=surface, + commit_action=commit_action, + response=response, + ) + violations.extend(post_violations) + + if violations: + actions = {v.action for v in violations} + outcome = ( + OUTCOME_BLOCKED if DECISION_BLOCK in actions else OUTCOME_ESCALATED + ) + elif set(self.spec.commit_sequence).issubset(set(commits_executed)) and bool( + self.spec.commit_sequence + ): + outcome = OUTCOME_COMPLETE + else: + outcome = OUTCOME_INCOMPLETE + + return EnforcementReport( + trajectory_id=traj_id, + outcome=outcome, + commits_attempted=tuple(commits_attempted), + commits_executed=tuple(commits_executed), + commits_blocked=tuple(commits_blocked), + violations=tuple(violations), + checked_invariants=self.checked_invariants, + checked_source_reads=self.checked_source_reads, + checked_policy_rules=self.checked_policy_rules, + checked_confirmations=self.checked_confirmations, + ) + + +def evaluate_suite( + spec: CheckpointSpec, + labeled_trajectories: Sequence[Mapping[str, Any]], +) -> SuiteMetrics: + """Evaluate a labeled suite of clean and failure trajectories against ``spec``.""" + clean_count = 0 + bad_count = 0 + clean_auto_completed = 0 + clean_false_escalations = 0 + bad_caught = 0 + bad_silent_errors = 0 + + for item in labeled_trajectories: + is_clean = bool(item["is_clean"]) + enforcer = CheckpointEnforcer(spec) + report = enforcer.enforce_trajectory(item) + + if is_clean: + clean_count += 1 + if report.outcome == OUTCOME_COMPLETE: + clean_auto_completed += 1 + else: + clean_false_escalations += 1 + else: + bad_count += 1 + if report.outcome in (OUTCOME_BLOCKED, OUTCOME_ESCALATED): + bad_caught += 1 + else: + bad_silent_errors += 1 + + total_escalations = bad_caught + clean_false_escalations + silent_error_rate = (bad_silent_errors / bad_count) if bad_count else 0.0 + auto_completion_rate = (clean_auto_completed / clean_count) if clean_count else 0.0 + escalation_precision = ( + (bad_caught / total_escalations) if total_escalations else 1.0 + ) + + return SuiteMetrics( + total_trajectories=len(labeled_trajectories), + clean_count=clean_count, + bad_count=bad_count, + clean_auto_completed=clean_auto_completed, + clean_false_escalations=clean_false_escalations, + bad_caught=bad_caught, + bad_silent_errors=bad_silent_errors, + silent_error_rate=silent_error_rate, + auto_completion_rate=auto_completion_rate, + escalation_precision=escalation_precision, + ) + + +__all__ = [ + "CheckpointEnforcer", + "CheckpointViolation", + "CommitGateDecision", + "DECISION_ALLOW", + "DECISION_BLOCK", + "DECISION_ESCALATE", + "EnforcementReport", + "EntityLedger", + "OUTCOME_BLOCKED", + "OUTCOME_COMPLETE", + "OUTCOME_ESCALATED", + "OUTCOME_INCOMPLETE", + "SuiteMetrics", + "evaluate_suite", +] diff --git a/packages/flow/tests/test_wrap_checkpoint_ledger.py b/packages/flow/tests/test_wrap_checkpoint_ledger.py new file mode 100644 index 0000000000..4c8e61ae49 --- /dev/null +++ b/packages/flow/tests/test_wrap_checkpoint_ledger.py @@ -0,0 +1,509 @@ +"""Unit tests for openadapt_flow.wrap CheckpointSpec + Cross-Tab EntityLedger.""" + +from __future__ import annotations + +import copy +import json +from typing import Any + +import pytest + +from openadapt_flow.wrap import ( + CheckpointEnforcer, + CheckpointSpec, + EntityLedger, + compile_checkpoint_spec, +) +from openadapt_flow.wrap.checkpoint_spec import ( + FORBIDDEN_LAYOUT_KEYS, + SPEC_SCHEMA, + assert_layout_independent, +) +from openadapt_flow.wrap.entity_ledger import ( + DECISION_ALLOW, + DECISION_BLOCK, + DECISION_ESCALATE, + OUTCOME_BLOCKED, + OUTCOME_COMPLETE, + OUTCOME_INCOMPLETE, + evaluate_suite, +) + +POLICY_RULES: list[dict[str, Any]] = [ + { + "id": "policy_01_amount_cap", + "surface": "portal_b", + "commit_action": "portal_b:submit_request", + "field_name": "requested_units", + "operator": "lte", + "threshold": 15.0, + "on_violation": "escalate", + "description": "Requests above 15.0 units require operator approval.", + }, + { + "id": "policy_02_request_type", + "surface": "portal_b", + "commit_action": "portal_b:submit_request", + "field_name": "request_type", + "operator": "in", + "threshold": ["standard", "expedited"], + "on_violation": "block", + "description": "Request type must be an allowed category.", + }, +] + + +def _demo_trace() -> dict[str, Any]: + """Generic two-surface demonstration trace with raw UI coordinates.""" + return { + "meta": { + "id": "demo-cross-tab-001", + "workflow_id": "cross-tab:submit-and-close", + "viewport": [1440, 900], + "coordinate_space": "page", + }, + "events": [ + { + "i": 0, + "kind": "click", + "surface": "source_app", + "section": "summary", + "x": 312, + "y": 198, + "selector": "#row-CASE-2026-001", + "read_entities": { + "case_id": "CASE-2026-001", + "subject_name": "Doe, John", + "notes_summary": "0.5 units x 2 x 12 months", + }, + }, + { + "i": 1, + "kind": "click", + "surface": "source_app", + "section": "codes", + "x": 420, + "y": 140, + "selector": "button[data-tab='codes']", + "read_entities": { + "category_codes": ["A10.1", "A10.2", "B20.0"], + }, + }, + { + "i": 2, + "kind": "click", + "surface": "source_app", + "section": "items", + "x": 510, + "y": 140, + "selector": "button[data-tab='items']", + "read_entities": { + "item_codes": ["10001", "20002"], + }, + }, + { + "i": 3, + "kind": "click", + "surface": "source_app", + "section": "account", + "x": 605, + "y": 140, + "selector": "button[data-tab='account']", + "read_entities": { + "account_id": "ACC123456789", + "effective_date": "1965-03-15", + }, + }, + { + "i": 4, + "kind": "download", + "surface": "source_app", + "section": "attachments", + "x": 880, + "y": 410, + "selector": "button.download-attachment", + "read_entities": { + "supporting_document": "Supporting_Letter.pdf", + }, + }, + { + "i": 5, + "kind": "switch_surface", + "surface": "portal_b", + "section": "form", + }, + { + "i": 6, + "kind": "select", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 260, + "field_name": "request_type", + "value": "standard", + }, + { + "i": 7, + "kind": "type", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 320, + "field_rect": [300, 305, 280, 32], + "field_name": "account_id", + "text": "ACC123456789", + }, + { + "i": 8, + "kind": "type", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 380, + "field_rect": [300, 365, 280, 32], + "field_name": "effective_date", + "text": "03/15/1965", + }, + { + "i": 9, + "kind": "type", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 440, + "field_name": "category_codes", + "value": ["A10.1", "A10.2", "B20.0"], + }, + { + "i": 10, + "kind": "type", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 500, + "field_name": "item_codes", + "value": ["10001", "20002"], + }, + { + "i": 11, + "kind": "attach", + "surface": "portal_b", + "section": "form", + "x": 440, + "y": 560, + "field_name": "attached_document", + "value": "Supporting_Letter.pdf", + }, + { + "i": 12, + "kind": "submit", + "action_type": "irreversible_commit", + "commit_action": "portal_b:submit_request", + "surface": "portal_b", + "section": "form", + "x": 720, + "y": 810, + "payload": { + "requested_units": 12.0, + }, + "response": { + "status": 201, + "confirmation_id": "CONF-2026-88421", + }, + }, + { + "i": 13, + "kind": "switch_surface", + "surface": "source_app", + "section": "notes", + }, + { + "i": 14, + "kind": "note", + "surface": "source_app", + "section": "notes", + "x": 520, + "y": 600, + "field_name": "completion_note", + "text": "Submitted request. Confirmation ID: CONF-2026-88421.", + }, + { + "i": 15, + "kind": "submit", + "action_type": "irreversible_commit", + "commit_action": "source_app:close_case", + "surface": "source_app", + "section": "queue", + "x": 910, + "y": 190, + "payload": {"case_id": "CASE-2026-001"}, + "response": {"status": 200, "closed": True}, + }, + ], + } + + +def _base_events() -> list[dict[str, Any]]: + return copy.deepcopy(_demo_trace()["events"]) + + +@pytest.fixture(scope="module") +def compiled_spec() -> CheckpointSpec: + return compile_checkpoint_spec(_demo_trace(), policy_rules=POLICY_RULES) + + +def test_compile_strips_layout_and_record_literals( + compiled_spec: CheckpointSpec, +) -> None: + assert compiled_spec.schema == SPEC_SCHEMA + assert compiled_spec.surfaces == ("source_app", "portal_b") + assert compiled_spec.commit_sequence == ( + "portal_b:submit_request", + "source_app:close_case", + ) + assert len(compiled_spec.required_source_reads) == 5 + assert len(compiled_spec.cross_tab_invariants) == 5 + assert len(compiled_spec.approval_rules) == 2 + assert len(compiled_spec.confirmation_checks) == 2 + + raw_json = compiled_spec.to_json() + parsed = json.loads(raw_json) + assert_layout_independent(parsed) + for forbidden in FORBIDDEN_LAYOUT_KEYS: + assert f'"{forbidden}"' not in raw_json + + for literal in ("Doe, John", "ACC123456789", "1965-03-15", "CONF-2026-88421"): + assert literal not in raw_json + + reloaded = CheckpointSpec.from_dict(parsed) + assert reloaded == compiled_spec + + with pytest.raises(ValueError, match="Layout-dependent key"): + assert_layout_independent({"nested": {"x": 100}}) + + +def test_infers_date_normalization_and_confirmation_writeback( + compiled_spec: CheckpointSpec, +) -> None: + date_invs = [ + inv + for inv in compiled_spec.cross_tab_invariants + if inv.dest_field == "effective_date" + ] + assert len(date_invs) == 1 + assert date_invs[0].match_mode == "date_iso" + + first_confirm = [ + c + for c in compiled_spec.confirmation_checks + if c.commit_action == "portal_b:submit_request" + ][0] + assert first_confirm.required_response_fields == ("confirmation_id",) + assert first_confirm.writeback_surface == "source_app" + assert first_confirm.writeback_field == "completion_note" + assert first_confirm.writeback_before_commit == "source_app:close_case" + + +def test_shifted_layout_and_different_record_complete_cleanly( + compiled_spec: CheckpointSpec, +) -> None: + # 1. Shifted coordinates, renamed selectors, extra scroll, ISO date format + ev_shifted = _base_events() + for ev in ev_shifted: + if "x" in ev: + ev["x"] += 410 + ev["y"] += 220 + if "selector" in ev: + ev["selector"] = "div.new-layout > button" + if ev.get("field_name") == "effective_date": + ev["text"] = "1965-03-15" + ev_shifted.insert( + 6, + { + "i": 99, + "kind": "scroll", + "surface": "portal_b", + "section": "form", + "dy": 500, + }, + ) + report_shifted = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "clean_shifted", "events": ev_shifted} + ) + assert report_shifted.outcome == OUTCOME_COMPLETE + assert report_shifted.commits_blocked == () + + # 2. Different record values using the same compiled spec + ev_other = _base_events() + ev_other[0]["read_entities"] = { + "case_id": "CASE-2026-002", + "subject_name": "Smith, Emily", + "notes_summary": "1.0 unit monthly", + } + ev_other[1]["read_entities"] = {"category_codes": ["C30.5"]} + ev_other[2]["read_entities"] = {"item_codes": ["30003"]} + ev_other[3]["read_entities"] = { + "account_id": "ACC987654321", + "effective_date": "1958-06-20", + } + ev_other[4]["read_entities"] = {"supporting_document": "Case_002_Letter.pdf"} + ev_other[7]["text"] = "ACC987654321" + ev_other[8]["text"] = "06/20/1958" + ev_other[9]["value"] = ["C30.5"] + ev_other[10]["value"] = ["30003"] + ev_other[11]["value"] = "Case_002_Letter.pdf" + ev_other[12]["response"]["confirmation_id"] = "CONF-2026-99104" + ev_other[14]["text"] = "Closed under CONF-2026-99104." + ev_other[15]["payload"]["case_id"] = "CASE-2026-002" + + report_other = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "clean_other_record", "events": ev_other} + ) + assert report_other.outcome == OUTCOME_COMPLETE + assert report_other.commits_executed == compiled_spec.commit_sequence + + +def test_blocks_cross_tab_mismatch_and_skipped_reads( + compiled_spec: CheckpointSpec, +) -> None: + # Skipped source read + ev_skip = [ev for ev in _base_events() if ev.get("section") != "summary"] + r_skip = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_skip", "events": ev_skip} + ) + assert r_skip.outcome == OUTCOME_BLOCKED + assert "portal_b:submit_request" in r_skip.commits_blocked + assert "skipped_source_read" in {v.code for v in r_skip.violations} + + # Wrong-record cross-tab paste + ev_mismatch = _base_events() + ev_mismatch[7]["text"] = "ACC999888777" + r_mismatch = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_mismatch", "events": ev_mismatch} + ) + assert r_mismatch.outcome == OUTCOME_BLOCKED + assert "portal_b:submit_request" in r_mismatch.commits_blocked + assert "cross_tab_entity_mismatch" in {v.code for v in r_mismatch.violations} + + +def test_policy_thresholds_and_stop_on_uncertainty( + compiled_spec: CheckpointSpec, +) -> None: + # Exceeded cap without approval -> blocked/escalated before commit + ev_over = _base_events() + ev_over[12]["payload"]["requested_units"] = 24.0 + r_over = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_over_cap", "events": ev_over} + ) + assert "portal_b:submit_request" in r_over.commits_blocked + assert "policy_violation" in {v.code for v in r_over.violations} + + # Exceeded cap WITH explicit human approval -> completes + ev_approved = _base_events() + ev_approved[12]["payload"]["requested_units"] = 24.0 + ev_approved[12]["human_approved"] = True + r_approved = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "clean_approved", "events": ev_approved} + ) + assert r_approved.outcome == OUTCOME_COMPLETE + + # Missing policy field -> stops on uncertainty + ev_missing = _base_events() + del ev_missing[12]["payload"]["requested_units"] + r_missing = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_uncertain", "events": ev_missing} + ) + assert "portal_b:submit_request" in r_missing.commits_blocked + assert "uncertain_policy_field" in {v.code for v in r_missing.violations} + + +def test_confirmation_readback_and_writeback_enforcement( + compiled_spec: CheckpointSpec, +) -> None: + # Missing confirmation ID in writeback note blocks closing case + ev_no_wb = _base_events() + ev_no_wb[14]["text"] = "Submitted request. Done." + r_no_wb = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_no_wb", "events": ev_no_wb} + ) + assert r_no_wb.outcome == OUTCOME_BLOCKED + assert "source_app:close_case" in r_no_wb.commits_blocked + assert "confirmation_writeback_mismatch" in {v.code for v in r_no_wb.violations} + + # Upstream HTTP 500 on first commit escalates and blocks downstream commit + ev_500 = _base_events() + ev_500[12]["response"] = {"status": 500, "error": "timeout"} + r_500 = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "fail_500", "events": ev_500} + ) + assert r_500.outcome == OUTCOME_BLOCKED + assert "source_app:close_case" in r_500.commits_blocked + codes = {v.code for v in r_500.violations} + assert "confirmation_status_failed" in codes + assert "missing_prior_confirmation" in codes + + +def test_live_entity_ledger_hooks_and_suite_metrics( + compiled_spec: CheckpointSpec, +) -> None: + # Live step-by-step check_before_commit / check_after_commit API + ledger = EntityLedger() + enforcer = CheckpointEnforcer(compiled_spec, ledger=ledger) + events = _base_events() + for ev in events[:12]: + enforcer.observe_event(ev) + + gate_ok = enforcer.check_before_commit( + step_index=12, + surface="portal_b", + commit_action="portal_b:submit_request", + payload={"requested_units": 12.0}, + ) + assert gate_ok.decision == DECISION_ALLOW + + gate_over = enforcer.check_before_commit( + step_index=12, + surface="portal_b", + commit_action="portal_b:submit_request", + payload={"requested_units": 99.0}, + ) + assert gate_over.decision == DECISION_ESCALATE + + gate_bad_type = enforcer.check_before_commit( + step_index=12, + surface="portal_b", + commit_action="portal_b:submit_request", + payload={"requested_units": 12.0, "request_type": "unknown"}, + ) + assert gate_bad_type.decision == DECISION_BLOCK + + post_viols = enforcer.check_after_commit( + step_index=12, + surface="portal_b", + commit_action="portal_b:submit_request", + response={"status": 201, "confirmation_id": "CONF-2026-88421"}, + ) + assert post_viols == () + assert ledger.get_confirmation("portal_b:submit_request") == { + "confirmation_id": "CONF-2026-88421" + } + + # Incomplete trajectory (stopped before any commits) + r_inc = CheckpointEnforcer(compiled_spec).enforce_trajectory( + {"id": "incomplete", "events": events[:5]} + ) + assert r_inc.outcome == OUTCOME_INCOMPLETE + + # Suite metrics + ev_bad = _base_events() + ev_bad[7]["text"] = "ACC000000000" + metrics = evaluate_suite( + compiled_spec, + [ + {"id": "clean_1", "is_clean": True, "events": _base_events()}, + {"id": "bad_1", "is_clean": False, "events": ev_bad}, + ], + ) + assert metrics.silent_error_rate == 0.0 + assert metrics.auto_completion_rate == 1.0 + assert metrics.escalation_precision == 1.0