"""JSON Schema loading, validation, and one-shot JSON repair parsing. The pipeline persists every model output and intermediate artifact as JSON validated against a schema in ``schemas/``. Model JSON is parsed strictly: a malformed response is repaired at most once, and a second failure routes the item to the human queue (never a silent regex fallback). """ from __future__ import annotations import json from collections.abc import Callable from pathlib import Path from typing import Any from jsonschema import Draft202012Validator from .hashing import sha256_text ParseStatus = str # "valid_first_response" | "valid_after_one_repair" | "invalid" class SchemaError(ValueError): """Raised when a schema document itself is invalid.""" def load_schema(path: str | Path) -> dict[str, Any]: """Load and compile-check a JSON Schema (draft 2020-12) from ``path``.""" schema: dict[str, Any] = json.loads(Path(path).read_text(encoding="utf-8")) try: Draft202012Validator.check_schema(schema) except Exception as exc: # jsonschema raises various error types raise SchemaError(f"invalid schema {path}: {exc}") from exc return schema def validate(instance: Any, schema: dict[str, Any]) -> list[str]: """Return a list of human-readable validation errors (empty if valid).""" validator = Draft202012Validator(schema) return [ _format_error(error) for error in sorted(validator.iter_errors(instance), key=lambda e: list(e.path)) ] def is_valid(instance: Any, schema: dict[str, Any]) -> bool: """True when ``instance`` satisfies ``schema``.""" return not validate(instance, schema) def _format_error(error: Any) -> str: path = ".".join(str(part) for part in error.path) or "$" return f"{path}: {error.message}" def parse_json(raw: str) -> Any: """Parse a JSON document, tolerating a leading/trailing code fence. Raises ``json.JSONDecodeError`` on failure (no silent fallback). """ text = raw.strip() if text.startswith("```"): # Strip a single surrounding fenced block (```json ... ``` or ``` ... ```). lines = text.splitlines() if lines and lines[0].startswith("```"): lines = lines[1:] if lines and lines[-1].strip().startswith("```"): lines = lines[:-1] text = "\n".join(lines).strip() return json.loads(text) def parse_with_repair( raw: str, schema: dict[str, Any], repair: Callable[[str, list[str]], str | None], ) -> tuple[Any | None, ParseStatus, list[str]]: """Parse ``raw`` against ``schema``, allowing at most one repair call. ``repair(raw, errors)`` must return either a repaired raw string (re-parsed and re-validated) or ``None``/empty to give up. Returns ``(parsed_or_None, parse_status, final_errors)``. """ try: candidate = parse_json(raw) except json.JSONDecodeError as exc: candidate = None first_errors = [f"json: {exc}"] else: first_errors = validate(candidate, schema) if not first_errors: return candidate, "valid_first_response", [] repaired = repair(raw, first_errors) if not repaired: return None, "invalid", first_errors try: candidate = parse_json(repaired) except json.JSONDecodeError as exc: return None, "invalid", [*first_errors, f"repair-json: {exc}"] second_errors = validate(candidate, schema) if second_errors: return None, "invalid", [*first_errors, *second_errors] return candidate, "valid_after_one_repair", [] def request_hash(payload: Any) -> str: """Stable SHA-256 of a request payload for idempotent response caching.""" return sha256_text(json.dumps(payload, sort_keys=True, ensure_ascii=False))