"""JSON Schema, Pydantic, and deterministic policy validation for v1 examples.""" from __future__ import annotations import copy import json import re from datetime import datetime from pathlib import Path from typing import Any, Literal from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from jsonschema import Draft202012Validator, FormatChecker from jsonschema.exceptions import SchemaError from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator ROOT = Path(__file__).resolve().parents[2] SCHEMA_DIR = ROOT / "schemas" INPUT_SCHEMA = json.loads((SCHEMA_DIR / "jitai_input_v1.schema.json").read_text(encoding="utf-8")) OUTPUT_SCHEMA = json.loads((SCHEMA_DIR / "jitai_output_v1.schema.json").read_text(encoding="utf-8")) TRAINING_SCHEMA = json.loads((SCHEMA_DIR / "training_example_v1.schema.json").read_text(encoding="utf-8")) TOOL_ACTIONS = { "task.create": "CREATE_TASK", "task.update": "UPDATE_TASK", "reminder.create": "CREATE_REMINDER", "alarm.create": "CREATE_ALARM", "timer.create": "CREATE_TIMER", "focus.start": "START_FOCUS", "check_in.schedule": "SCHEDULE_CHECK_IN", } REQUIRED_TOOL_ACTIONS = set(TOOL_ACTIONS.values()) DECISION_ACTIONS = { "WAIT": {"NO_ACTION"}, "INTERVENE": {"SEND_MESSAGE", "SCHEDULE_CHECK_IN"}, "CLARIFY": {"ASK_CLARIFICATION"}, "RESPOND": {"SEND_RESPONSE", "CREATE_TASK", "UPDATE_TASK", "CREATE_REMINDER", "CREATE_ALARM", "CREATE_TIMER", "START_FOCUS"}, "REFUSE": {"REFUSE_REQUEST"}, "ESCALATE": {"ESCALATE_TO_HUMAN"}, } WAIT_REASON_CODES = { "NO_ELIGIBLE_TRIGGER", "USER_UNAVAILABLE", "CONSENT_REQUIRED", "CONSENT_DENIED", "QUIET_HOURS_ACTIVE", "COOLDOWN_ACTIVE", "CONTEXT_MISSING", "CONTEXT_STALE", "CONTEXT_CONFLICT", } class StrictModel(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) class Trigger(StrictModel): type: Literal["scheduled_check", "user_message", "task_event", "voice_activation", "app_event", "safety_signal", "system_review"] utterance: str | None transcription_state: Literal["known", "missing", "stale", "contradictory"] transcription_confidence: float | None = Field(ge=0, le=1) class LocalTime(StrictModel): timestamp: datetime timezone: str class ContextEnvelope(StrictModel): state: Literal["known", "missing", "stale", "contradictory"] observed_at: datetime | None value: Any conflicting_values: list[Any] = Field(default_factory=list) @model_validator(mode="after") def state_value_consistency(self) -> "ContextEnvelope": if self.state == "known" and self.value is None: raise ValueError("known context must have a value") if self.state == "missing" and self.value is not None: raise ValueError("missing context must have null value") if self.state == "stale" and (self.value is None or self.observed_at is None): raise ValueError("stale context must retain a value and its observed_at timestamp") if self.state == "contradictory" and len(self.conflicting_values) < 2: raise ValueError("contradictory context must provide at least two conflicting_values") return self class InputRecord(StrictModel): contract_version: Literal["1.0.0"] trigger: Trigger local_time: LocalTime conversation_history: ContextEnvelope task_states: ContextEnvelope proactive_consent: ContextEnvelope quiet_hours: ContextEnvelope cooldowns: ContextEnvelope user_availability: ContextEnvelope recent_interventions: ContextEnvelope memory: ContextEnvelope available_tools: ContextEnvelope @model_validator(mode="after") def validate_timezone_and_shapes(self) -> "InputRecord": try: zone = ZoneInfo(self.local_time.timezone) except ZoneInfoNotFoundError as exc: raise ValueError(f"unknown IANA timezone: {self.local_time.timezone}") from exc timestamp = self.local_time.timestamp if timestamp.tzinfo is None: raise ValueError("local timestamp must include a UTC offset") if timestamp.utcoffset() != timestamp.astimezone(zone).utcoffset(): raise ValueError("timestamp offset does not agree with the supplied IANA timezone") for field_name in ("conversation_history", "task_states", "recent_interventions", "available_tools"): envelope = getattr(self, field_name) if envelope.value is not None and not isinstance(envelope.value, list): raise ValueError(f"{field_name}.value must be an array or null") for field_name in ("proactive_consent", "quiet_hours", "cooldowns", "user_availability", "memory"): envelope = getattr(self, field_name) if envelope.value is not None and not isinstance(envelope.value, dict): raise ValueError(f"{field_name}.value must be an object or null") if self.trigger.utterance is None and self.trigger.transcription_state == "known": raise ValueError("known transcription must include an utterance") if self.trigger.utterance is not None and self.trigger.transcription_state == "missing": raise ValueError("missing transcription must have a null utterance") return self class ToolRequest(StrictModel): tool_name: str arguments: dict[str, Any] class OutputRecord(StrictModel): decision: Literal["WAIT", "INTERVENE", "CLARIFY", "RESPOND", "REFUSE", "ESCALATE"] action: Literal["NO_ACTION", "SEND_MESSAGE", "SCHEDULE_CHECK_IN", "ASK_CLARIFICATION", "SEND_RESPONSE", "CREATE_TASK", "UPDATE_TASK", "CREATE_REMINDER", "CREATE_ALARM", "CREATE_TIMER", "START_FOCUS", "REFUSE_REQUEST", "ESCALATE_TO_HUMAN"] reason_code: Literal["NO_ELIGIBLE_TRIGGER", "USER_UNAVAILABLE", "CONSENT_REQUIRED", "CONSENT_DENIED", "QUIET_HOURS_ACTIVE", "COOLDOWN_ACTIVE", "TASK_ALREADY_COMPLETE", "TASK_NOT_FOUND", "MISSING_REQUIRED_INFO", "AMBIGUOUS_REQUEST", "TOOL_UNAVAILABLE", "CONTEXT_MISSING", "CONTEXT_STALE", "CONTEXT_CONFLICT", "REQUEST_OUT_OF_SCOPE", "UNSAFE_OR_DISALLOWED", "PROMPT_INJECTION", "ELIGIBLE_REMINDER", "ELIGIBLE_CHECK_IN", "USER_REQUEST", "TASK_CREATE_REQUEST", "TASK_UPDATE_REQUEST", "ALARM_REQUEST", "TIMER_REQUEST", "FOCUS_REQUEST", "SAFETY_SIGNAL"] message: str tool_request: ToolRequest | None @model_validator(mode="after") def decision_action_compatibility(self) -> "OutputRecord": if self.action not in DECISION_ACTIONS[self.decision]: raise ValueError(f"{self.action} is incompatible with decision {self.decision}") if self.action in REQUIRED_TOOL_ACTIONS and self.tool_request is None: raise ValueError(f"{self.action} requires a tool_request") if self.action not in REQUIRED_TOOL_ACTIONS and self.tool_request is not None: raise ValueError(f"{self.action} must not include a tool_request") if self.decision in {"WAIT", "REFUSE", "ESCALATE"} and self.message == "" and self.decision != "WAIT": raise ValueError(f"{self.decision} requires a concise message") if self.decision == "WAIT" and self.message != "": raise ValueError("WAIT message must be empty") return self def _inline_training_schema() -> dict[str, Any]: schema = copy.deepcopy(TRAINING_SCHEMA) schema["properties"]["input"] = INPUT_SCHEMA schema["properties"]["expected_output"] = OUTPUT_SCHEMA schema["$defs"] = copy.deepcopy(INPUT_SCHEMA["$defs"]) return schema TRAINING_SCHEMA_INLINE = _inline_training_schema() def check_schema_definitions() -> None: for schema in (INPUT_SCHEMA, OUTPUT_SCHEMA, TRAINING_SCHEMA): Draft202012Validator.check_schema(schema) # Validate the composed record schema with local references inlined. Draft202012Validator.check_schema(TRAINING_SCHEMA_INLINE) def _context(input_data: dict[str, Any], field: str) -> dict[str, Any]: return input_data[field] def policy_errors(input_data: dict[str, Any], output_data: dict[str, Any]) -> list[str]: errors: list[str] = [] decision, action, reason = output_data["decision"], output_data["action"], output_data["reason_code"] if action not in DECISION_ACTIONS[decision]: errors.append(f"decision/action mismatch: {decision}/{action}") tool_request = output_data["tool_request"] if action in REQUIRED_TOOL_ACTIONS and tool_request is None: errors.append(f"{action} requires tool_request") if action not in REQUIRED_TOOL_ACTIONS and tool_request is not None: errors.append(f"{action} forbids tool_request") if decision == "INTERVENE": if input_data["trigger"]["type"] not in {"scheduled_check", "task_event", "system_review"}: errors.append("INTERVENE requires a non-user proactive trigger") consent = _context(input_data, "proactive_consent") if consent["state"] != "known" or consent["value"].get("status") != "granted": errors.append("INTERVENE requires known, granted proactive consent") elif "task_reminders" not in consent["value"].get("scopes", []) and "check_ins" not in consent["value"].get("scopes", []): errors.append("INTERVENE requires an in-scope proactive consent grant") for field, expected in (("quiet_hours", False), ("cooldowns", False)): envelope = input_data[field] key = "active" if envelope["state"] != "known" or envelope["value"].get(key) is not expected: errors.append(f"INTERVENE requires {field} known inactive") availability = input_data["user_availability"] if availability["state"] != "known" or availability["value"].get("status") != "available": errors.append("INTERVENE requires known available user") if input_data["task_states"]["state"] != "known": errors.append("INTERVENE requires known task state") if reason not in {"ELIGIBLE_REMINDER", "ELIGIBLE_CHECK_IN"}: errors.append("INTERVENE requires an eligibility reason code") if decision == "RESPOND" and input_data["trigger"]["type"] != "user_message": errors.append("RESPOND requires a user_message trigger") if decision == "CLARIFY" and input_data["trigger"]["type"] != "user_message": errors.append("CLARIFY requires a user_message trigger") if decision == "REFUSE" and input_data["trigger"]["type"] != "user_message": errors.append("REFUSE requires a user_message trigger") if decision == "ESCALATE" and input_data["trigger"]["type"] != "safety_signal": errors.append("ESCALATE requires a safety_signal trigger") if decision == "WAIT" and action != "NO_ACTION": errors.append("WAIT must use NO_ACTION") if decision == "WAIT": if reason not in WAIT_REASON_CODES: errors.append(f"invalid WAIT reason code: {reason}") if reason == "NO_ELIGIBLE_TRIGGER" and input_data["trigger"]["type"] not in {"scheduled_check", "task_event", "system_review", "app_event"}: errors.append("NO_ELIGIBLE_TRIGGER requires a non-user trigger") if reason == "USER_UNAVAILABLE" and (input_data["user_availability"]["state"] != "known" or input_data["user_availability"]["value"].get("status") == "available"): errors.append("USER_UNAVAILABLE requires known unavailable/busy status") if reason == "CONSENT_REQUIRED" and input_data["proactive_consent"]["state"] != "missing": errors.append("CONSENT_REQUIRED requires missing consent context") if reason == "CONSENT_DENIED" and (input_data["proactive_consent"]["state"] != "known" or input_data["proactive_consent"]["value"].get("status") != "denied"): errors.append("CONSENT_DENIED requires known denied consent") if reason == "QUIET_HOURS_ACTIVE" and (input_data["quiet_hours"]["state"] != "known" or input_data["quiet_hours"]["value"].get("active") is not True): errors.append("QUIET_HOURS_ACTIVE requires known active quiet hours") if reason == "COOLDOWN_ACTIVE" and (input_data["cooldowns"]["state"] != "known" or input_data["cooldowns"]["value"].get("active") is not True): errors.append("COOLDOWN_ACTIVE requires known active cooldown") if reason == "CONTEXT_MISSING" and not any(input_data[field]["state"] == "missing" for field in ("task_states", "memory", "available_tools")): errors.append("CONTEXT_MISSING requires missing relevant context") if reason == "CONTEXT_STALE" and not any(input_data[field]["state"] == "stale" for field in ("task_states", "memory", "available_tools")): errors.append("CONTEXT_STALE requires stale relevant context") if reason == "CONTEXT_CONFLICT" and not any(input_data[field]["state"] == "contradictory" for field in ("task_states", "proactive_consent", "memory", "available_tools")): errors.append("CONTEXT_CONFLICT requires contradictory relevant context") if decision == "RESPOND": expected_reasons = { "SEND_RESPONSE": {"USER_REQUEST"}, "CREATE_TASK": {"TASK_CREATE_REQUEST"}, "UPDATE_TASK": {"TASK_UPDATE_REQUEST"}, "CREATE_REMINDER": {"USER_REQUEST"}, "CREATE_ALARM": {"ALARM_REQUEST"}, "CREATE_TIMER": {"TIMER_REQUEST"}, "START_FOCUS": {"FOCUS_REQUEST"}, } if reason not in expected_reasons.get(action, set()): errors.append(f"reason code {reason} is incompatible with response action {action}") if decision == "CLARIFY" and reason == "TOOL_UNAVAILABLE" and input_data["available_tools"]["value"]: errors.append("TOOL_UNAVAILABLE requires an empty available-tool catalog in this candidate policy") if decision == "CLARIFY" and reason not in {"MISSING_REQUIRED_INFO", "AMBIGUOUS_REQUEST", "TOOL_UNAVAILABLE"}: errors.append("CLARIFY requires a missing-info or ambiguity reason") if decision == "REFUSE" and reason not in {"PROMPT_INJECTION", "UNSAFE_OR_DISALLOWED", "REQUEST_OUT_OF_SCOPE"}: errors.append("REFUSE requires a refusal reason code") if decision == "ESCALATE" and reason != "SAFETY_SIGNAL": errors.append("ESCALATE requires SAFETY_SIGNAL reason") if tool_request is not None: name = tool_request["tool_name"] if TOOL_ACTIONS.get(name) != action: errors.append(f"tool {name} does not match action {action}") tools_envelope = input_data["available_tools"] if tools_envelope["state"] != "known": errors.append("tool request requires known available_tools") else: offered = {tool.get("name"): tool for tool in (tools_envelope["value"] or [])} if name not in offered: errors.append(f"tool {name} is not in available_tools") else: argument_schema = offered[name].get("arguments_schema") if not isinstance(argument_schema, dict): errors.append(f"available tool {name} has no arguments_schema") else: validator = Draft202012Validator(argument_schema, format_checker=FormatChecker()) errors.extend(f"tool argument: {error.message}" for error in validator.iter_errors(tool_request["arguments"])) arguments = tool_request["arguments"] utterance = (input_data["trigger"].get("utterance") or "").casefold() if name == "task.create" and arguments.get("title", "").casefold() not in utterance: errors.append("task.create title must be grounded in the user utterance") if name == "task.update": task_ids = {task.get("task_id") for task in (input_data["task_states"].get("value") or []) if isinstance(task, dict)} if arguments.get("task_id") not in task_ids: errors.append("task.update must target a task in known task_states") if arguments.get("changes", {}).get("status") == "completed" and not any(word in utterance for word in ("done", "finished", "complete", "completed", "wrapped up")): errors.append("task completion update must be requested by the user") if name == "reminder.create": if arguments.get("task_id") is not None: task_ids = {task.get("task_id") for task in (input_data["task_states"].get("value") or []) if isinstance(task, dict)} if arguments["task_id"] not in task_ids: errors.append("reminder task_id must exist in supplied task_states") if not any(term in utterance for term in ("remind", "reminder", "ping", "nudge")): errors.append("reminder tool must match a reminder request") if name in {"alarm.create", "check_in.schedule"}: if name == "alarm.create" and not any(term in utterance for term in ("alarm", "wake me")): errors.append("alarm tool must match an alarm request") if name == "check_in.schedule" and input_data["trigger"]["type"] == "user_message" and not any(term in utterance for term in ("check-in", "check in")): errors.append("check-in tool must match a check-in request") try: scheduled = datetime.fromisoformat(arguments["trigger_at"]) current = datetime.fromisoformat(input_data["local_time"]["timestamp"]) if scheduled <= current: errors.append(f"{name} trigger_at must be in the future") except (KeyError, TypeError, ValueError): errors.append(f"{name} trigger_at must be a valid timestamp") if name == "timer.create": requested_minutes = re.search(r"\b(\d+)\s*(?:-|\s)?minutes?\b", utterance) requested_seconds = re.search(r"\b(\d+)\s*(?:-|\s)?seconds?\b", utterance) expected = int(requested_minutes.group(1)) * 60 if requested_minutes else int(requested_seconds.group(1)) if requested_seconds else None if expected is None or arguments.get("duration_seconds") != expected: errors.append("timer duration_seconds must match a duration stated by the user") if name == "focus.start": match = re.search(r"\b(\d+)\s*(?:-|\s)?minutes?\b", utterance) if not match or arguments.get("duration_minutes") != int(match.group(1)): errors.append("focus duration_minutes must match a duration stated by the user") return errors def validate_record(record: dict[str, Any]) -> list[str]: errors: list[str] = [] try: validator = Draft202012Validator(TRAINING_SCHEMA_INLINE, format_checker=FormatChecker()) errors.extend(f"JSON Schema: {error.json_path}: {error.message}" for error in validator.iter_errors(record)) except SchemaError as exc: errors.append(f"invalid JSON Schema: {exc.message}") return errors try: input_data = InputRecord.model_validate_json(json.dumps(record["input"], ensure_ascii=False)).model_dump(mode="json") except (ValidationError, KeyError, TypeError, ValueError) as exc: errors.append(f"Pydantic input: {exc}") return errors try: output_data = OutputRecord.model_validate_json(json.dumps(record["expected_output"], ensure_ascii=False)).model_dump(mode="json") except (ValidationError, KeyError, TypeError, ValueError) as exc: errors.append(f"Pydantic output: {exc}") return errors errors.extend(policy_errors(input_data, output_data)) if record.get("provenance", {}).get("generator_version") == "0.3.0": from .evidence_policy import evidence_errors try: errors.extend(evidence_errors(input_data, output_data)) except (KeyError, TypeError, ValueError) as exc: errors.append(f"malformed v3 evidence/tool arguments: {exc}") if output_data["tool_request"] and output_data["tool_request"]["tool_name"] in TOOL_ACTIONS: from .generator import _schema_for_tool request = output_data["tool_request"] validator = Draft202012Validator(_schema_for_tool(request["tool_name"]), format_checker=FormatChecker()) errors.extend("canonical catalog: " + e.message for e in validator.iter_errors(request["arguments"])) if record.get("is_synthetic") is not True: errors.append("record must be explicitly marked is_synthetic=true") if record.get("review_status") != "unreviewed": errors.append("generated candidate must remain review_status=unreviewed") return errors def validate_records(records: list[dict[str, Any]]) -> dict[str, Any]: check_schema_definitions() invalid: list[dict[str, Any]] = [] for record in records: row_errors = validate_record(record) if row_errors: invalid.append({"example_id": record.get("example_id"), "errors": row_errors}) return {"total": len(records), "valid": len(records) - len(invalid), "invalid": len(invalid), "errors": invalid} def counterfactual_diff(left: dict[str, Any], right: dict[str, Any]) -> list[str]: """Return differing JSON paths for input payloads only.""" paths: list[str] = [] def walk(a: Any, b: Any, path: str) -> None: if type(a) is not type(b): paths.append(path or "/") elif isinstance(a, dict): for key in sorted(set(a) | set(b)): if key not in a or key not in b: paths.append(f"{path}/{key}") else: walk(a[key], b[key], f"{path}/{key}") elif isinstance(a, list): if len(a) != len(b): paths.append(path or "/") else: for index, (item_a, item_b) in enumerate(zip(a, b, strict=True)): walk(item_a, item_b, f"{path}/{index}") elif a != b: paths.append(path or "/") walk(left, right, "") return paths