"""Frozen normalization, validation and DOM delta helpers from PreVision. The selected functions retain the original implementation. Source hashes and symbols are recorded in source_provenance.json. Apache-2.0; see LICENSE.code. """ from __future__ import annotations import copy import json import re from collections import Counter from collections.abc import Mapping, Sequence from typing import Any BRANCH_CORE = "observation_repository" BRANCH_TEST = "official_tests" BRANCH_RENDER = "render_product" BRANCHES = (BRANCH_CORE, BRANCH_TEST, BRANCH_RENDER) ORACLE_STATUSES = ("pass", "fail", "not_run", "unknown") ISSUE_STATES = ("satisfied", "not_satisfied", "unknown") PRODUCT_OUTCOMES = ( "rendered_product", "repository_build_failure", "repository_execution_failure", "repository_execution_timeout", "repository_product_not_emitted", "repository_browser_ready_timeout", ) _ANSI_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") _ANSI_OSC_RE = re.compile(r"\x1b\][^\x07]*(?:\x07|\x1b\\)") _TERMINAL_C0_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f]") _WHITESPACE_RE = re.compile(r"[ \t]+") def strip_terminal_control_sequences(value: object) -> str: """Drop non-semantic terminal controls while preserving visible output. The deterministic OpenHands completion wrapper and real warning text stay intact. Only OSC/CSI escape sequences, orphan ESC bytes, and non-printing C0 controls are removed; tabs, newlines, and carriage returns are retained for the scoring normalizer to handle explicitly. """ text = str(value or "") text = _ANSI_OSC_RE.sub("", text) text = _ANSI_RE.sub("", text) text = text.replace("\x1b", "") return _TERMINAL_C0_RE.sub("", text) def normalize_text(value: object) -> str: """Conservative normalization used in addition to, never instead of, raw exact.""" text = strip_terminal_control_sequences(value) text = text.replace("\r\n", "\n").replace("\r", "\n") lines = [_WHITESPACE_RE.sub(" ", line).rstrip() for line in text.split("\n")] while lines and not lines[0]: lines.pop(0) while lines and not lines[-1]: lines.pop() return "\n".join(lines) def json_equal(left: object, right: object) -> bool: return json.dumps(left, sort_keys=True, ensure_ascii=False) == json.dumps( right, sort_keys=True, ensure_ascii=False ) def validate_prediction( branch: str, value: Mapping[str, Any], *, required_oracle_ids: Sequence[str] = (), required_decision_fields: Sequence[str] = (), environment_patch_field: str = "repository_patch", ) -> str | None: if environment_patch_field not in {"repository_patch", "step_patch"}: raise ValueError("unknown environment patch field") required = { BRANCH_CORE: ("observation", "environment"), BRANCH_TEST: ("execution", "resolved", "reward", "oracles", "summary"), BRANCH_RENDER: ( "outcome", "decision_fields", "document_tree", "visible_text", "change", ), }[branch] missing = [key for key in required if key not in value] if missing: return "prediction is missing required top-level keys: " + ", ".join(missing) confidence = value.get("confidence") if ( isinstance(confidence, bool) or not isinstance(confidence, (int, float)) or not 0 <= float(confidence) <= 1 ): return "confidence must be a number in [0,1]" def object_with_fields(name: str, fields: Sequence[str]) -> Mapping[str, Any] | str: nested = value.get(name) if not isinstance(nested, Mapping): return f"{name} must be an object" absent = [field for field in fields if field not in nested] if absent: return f"{name} is missing required keys: {', '.join(absent)}" return nested def is_bool_or_none(candidate: object) -> bool: return candidate is None or isinstance(candidate, bool) def is_int_or_none(candidate: object) -> bool: return candidate is None or ( isinstance(candidate, int) and not isinstance(candidate, bool) ) def is_number_or_none(candidate: object) -> bool: return candidate is None or ( isinstance(candidate, (int, float)) and not isinstance(candidate, bool) ) if branch == BRANCH_CORE: observation = object_with_fields( "observation", ( "kind", "observation_kind", "is_error", "exit_code", "timed_out", "output_text", "summary", ), ) if isinstance(observation, str): return observation if observation.get("kind") not in {"observation", "error", None}: return "observation.kind is outside the allowed vocabulary" if observation.get("observation_kind") not in { "FileEditorObservation", "TerminalObservation", "AgentErrorEvent", None, }: return "observation.observation_kind is outside the allowed vocabulary" if not isinstance(observation.get("output_text"), str): return "observation.output_text must be a string" if not isinstance(observation.get("summary"), str): return "observation.summary must be a string" if not is_bool_or_none(observation.get("is_error")): return "observation.is_error must be boolean or null" if not is_int_or_none(observation.get("exit_code")): return "observation.exit_code must be integer or null" if not is_bool_or_none(observation.get("timed_out")): return "observation.timed_out must be boolean or null" environment = object_with_fields( "environment", ( "action_status", "repository_changed", "changed_paths", "path_changes", "head_changed", "git_status_changed", "process_state_changed", "terminal_session_changed", "browser_session_changed", environment_patch_field, "summary", ), ) if isinstance(environment, str): return environment if environment.get("action_status") not in { "succeeded_changed", "succeeded_no_change", "failed", "timed_out", "unknown", }: return "environment.action_status is outside the allowed vocabulary" if not isinstance(environment.get("changed_paths"), list) or not isinstance( environment.get("path_changes"), Mapping ): return "environment paths must be an array plus an object" if not all( isinstance(path, str) for path in environment.get("changed_paths") or [] ): return "environment.changed_paths entries must be strings" if not isinstance(environment.get("repository_changed"), bool): return "environment.repository_changed must be boolean" for field in ( "head_changed", "git_status_changed", "process_state_changed", "terminal_session_changed", "browser_session_changed", ): if not is_bool_or_none(environment.get(field)): return f"environment.{field} must be boolean or null" if environment.get(environment_patch_field) is not None and not isinstance( environment.get(environment_patch_field), str ): return f"environment.{environment_patch_field} must be a string or null" if not isinstance(environment.get("summary"), str): return "environment.summary must be a string" return None if branch == BRANCH_TEST: execution = object_with_fields( "execution", ("completed", "timed_out", "exit_code", "failure_mode") ) if isinstance(execution, str): return execution if execution.get("failure_mode") not in { "none", "timed_out", "grading_error", "not_completed", "nonzero_exit", "unknown", }: return "execution.failure_mode is outside the allowed vocabulary" for field in ("completed", "timed_out"): if not is_bool_or_none(execution.get(field)): return f"execution.{field} must be boolean or null" if not is_int_or_none(execution.get("exit_code")): return "execution.exit_code must be integer or null" if not is_bool_or_none(value.get("resolved")): return "resolved must be boolean or null" if not is_number_or_none(value.get("reward")): return "reward must be a number or null" if not isinstance(value.get("summary"), str): return "summary must be a string" oracles = value.get("oracles") if not isinstance(oracles, list): return "oracles must be an array" predicted_ids: list[str] = [] for oracle in oracles: if not isinstance(oracle, Mapping) or not isinstance( oracle.get("oracle_id"), str ): return "every oracle must contain a string oracle_id" if oracle.get("status") not in ORACLE_STATUSES: return "every oracle status must use the allowed vocabulary" predicted_ids.append(str(oracle["oracle_id"])) if len(predicted_ids) != len(set(predicted_ids)): return "oracle_id values must be unique" missing_oracles = sorted(set(required_oracle_ids) - set(predicted_ids)) if missing_oracles: return "prediction is missing queried oracle_id values: " + json.dumps( missing_oracles, ensure_ascii=False ) unexpected_oracles = sorted(set(predicted_ids) - set(required_oracle_ids)) if unexpected_oracles: return "prediction contains unqueried oracle_id values: " + json.dumps( unexpected_oracles, ensure_ascii=False ) return None outcome = object_with_fields( "outcome", ("kind", "render_available", "failure_stage", "exit_code") ) if isinstance(outcome, str): return outcome if outcome.get("kind") not in PRODUCT_OUTCOMES: return "outcome.kind is outside the allowed vocabulary" if not is_bool_or_none(outcome.get("render_available")): return "outcome.render_available must be boolean or null" if outcome.get("failure_stage") is not None and not isinstance( outcome.get("failure_stage"), str ): return "outcome.failure_stage must be a string or null" if not is_int_or_none(outcome.get("exit_code")): return "outcome.exit_code must be integer or null" decisions = value.get("decision_fields") if not isinstance(decisions, Mapping): return "decision_fields must be an object" missing_decisions = sorted(set(required_decision_fields) - set(decisions)) if missing_decisions: return "prediction is missing decision fields: " + json.dumps( missing_decisions, ensure_ascii=False ) document = object_with_fields( "document_tree", ("title", "active_element", "headings", "alerts", "controls", "links"), ) if isinstance(document, str): return document if any( not isinstance(document.get(field), list) for field in ("headings", "alerts", "controls", "links") ): return "document_tree collections must be arrays" change = object_with_fields( "change", ( "decision_fields_changed", "document_changed", "pixels_changed", "issue_state_after", "after_description", "change_description", ), ) if isinstance(change, str): return change if change.get("issue_state_after") not in ISSUE_STATES: return "change.issue_state_after is outside the allowed vocabulary" for field in ("decision_fields_changed", "document_changed"): if not isinstance(change.get(field), bool): return f"change.{field} must be boolean" if not is_bool_or_none(change.get("pixels_changed")): return "change.pixels_changed must be boolean or null" for field in ("after_description", "change_description"): if not isinstance(change.get(field), str): return f"change.{field} must be a string" if not isinstance(value.get("visible_text"), str): return "visible_text must be a string" return None def validate_oneshot_prediction(branch: str, value: Mapping, **kwargs: Any) -> str | None: """V3 accepts explicit unknown leaves, without replacing them for scoring. Containers, required keys, oracle identifiers, and confidence remain strict. A validation-only copy substitutes type witnesses at leaves that v2 did not allow to be null. The actual prediction and all scored values stay intact. """ missing = value.get("missing_evidence") if not isinstance(missing, list) or not all(isinstance(x, str) for x in missing): return "missing_evidence must be an array of strings" candidate = copy.deepcopy(value) witnesses = { "observation_repository": { ("observation", "output_text"): "", ("observation", "summary"): "", ("environment", "action_status"): "unknown", ("environment", "repository_changed"): False, ("environment", "summary"): "", }, "official_tests": {("execution", "failure_mode"): "unknown", ("summary",): ""}, "render_product": { ("outcome", "kind"): "rendered_product", ("change", "decision_fields_changed"): False, ("change", "document_changed"): False, ("change", "issue_state_after"): "unknown", ("change", "after_description"): "", ("change", "change_description"): "", ("visible_text",): "", }, } for path, witness in witnesses[branch].items(): node = candidate for key in path[:-1]: node = node.get(key) if isinstance(node, dict) else None if isinstance(node, dict) and path[-1] in node and node[path[-1]] is None: node[path[-1]] = witness if branch == "official_tests" and isinstance(candidate.get("oracles"), list): for oracle in candidate["oracles"]: if isinstance(oracle, dict) and "status" in oracle and oracle["status"] is None: oracle["status"] = "unknown" return validate_prediction(branch, candidate, **kwargs) def parse_answer(text: str) -> dict: def pairs(values: list[tuple]) -> dict: result = {} for key, value in values: if key in result: raise ValueError(f"duplicate JSON key: {key}") result[key] = value return result def reject_constant(value: str) -> None: raise ValueError(f"non-finite JSON constant: {value}") value = json.loads(text, object_pairs_hook=pairs, parse_constant=reject_constant) if not isinstance(value, dict): raise ValueError("answer must be exactly one JSON object") return value def _mapping(value: object) -> Mapping[str, Any]: return value if isinstance(value, Mapping) else {} def _list(value: object) -> list[Any]: return list(value) if isinstance(value, list) else [] def _f1_counts(correct: int, predicted: int, target: int) -> dict[str, float]: precision = correct / predicted if predicted else (1.0 if target == 0 else 0.0) recall = correct / target if target else (1.0 if predicted == 0 else 0.0) f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 return {"precision": precision, "recall": recall, "f1": f1} def _multiset_f1(predicted: Sequence[str], target: Sequence[str]) -> dict[str, float]: left = Counter(predicted) right = Counter(target) correct = sum((left & right).values()) return _f1_counts(correct, sum(left.values()), sum(right.values())) def _canonical_items(values: object) -> list[str]: return [ json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")) for value in _list(values) ] def _document_delta_events(reference: object, candidate: object) -> list[str]: """Encode only DOM-like changes relative to the public reference state. Collections keep the scorer's existing order-insensitive multiset semantics. A replacement is represented by one removal plus one addition. Scalars emit a single set event containing the predicted/target after value. Therefore stable headings, controls, links, and alerts never create true positives. """ reference = _mapping(reference) candidate = _mapping(candidate) events: list[str] = [] missing = object() for field in ("title", "active_element"): before = reference.get(field, missing) after = candidate.get(field, missing) if (before is missing and after is missing) or ( before is not missing and after is not missing and json_equal(before, after) ): continue after_value: object = {"missing": True} if after is missing else after events.append( json.dumps( {"field": field, "operation": "set", "value": after_value}, sort_keys=True, ensure_ascii=False, separators=(",", ":"), ) ) for field in ("headings", "alerts", "controls", "links"): before = Counter(_canonical_items(reference.get(field))) after = Counter(_canonical_items(candidate.get(field))) for operation, changes in (("remove", before - after), ("add", after - before)): for value, count in sorted(changes.items()): event = json.dumps( {"field": field, "operation": operation, "value": value}, sort_keys=True, ensure_ascii=False, separators=(",", ":"), ) events.extend([event] * count) return events def _document_delta_grade( prediction: object, target: object, reference: object ) -> dict[str, Any]: """Score predicted DOM change events without rewarding stable background.""" predicted_events = _document_delta_events(reference, prediction) target_events = _document_delta_events(reference, target) score = _multiset_f1(predicted_events, target_events) target_changed = bool(target_events) return { **score, "target_changed": target_changed, "prediction_changed": bool(predicted_events), "target_event_count": len(target_events), "prediction_event_count": len(predicted_events), "changed_target_f1": score["f1"] if target_changed else None, }