"""Build a server-owned purpose binding and collect native calculation receipts.""" from __future__ import annotations from copy import deepcopy from datetime import datetime, timedelta, timezone from hashlib import sha256 import json from math import isfinite from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from scripts.consultation_plan_contract import PLAN_VERSION, plan_route_contract from . import BINDING_KEYS POLICY_VERSION = "purpose_policy_v1" GRANULARITIES = ("structure", "year", "month", "day") DOMAIN_ALIASES = { "career": "career", "事业": "career", "finance": "wealth", "wealth": "wealth", "财富": "wealth", "marriage": "marriage", "relationship": "marriage", "婚恋": "marriage", "structure": "structure", "整体结构": "structure", } SECOND = timedelta(seconds=1) TIMING_LAYERS = frozenset({"Dasha", "Vimshottari", "Narayana", "Transit"}) KNOWN_STATES = frozenset({"executed", "blocked", "not_applicable", "error"}) MISSING_POLICY_LAYER = "purpose_policy" def fingerprint(value) -> str: payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) return sha256(payload.encode("utf-8")).hexdigest() def _text(value, name: str) -> str: if not isinstance(value, str) or not value.strip(): raise ValueError(f"{name}_required") return value.strip() def _number(value, lower: float, upper: float, name: str) -> float: if (not isinstance(value, (int, float)) or isinstance(value, bool) or not isfinite(value) or not lower <= value <= upper): raise ValueError(f"{name}_invalid") return float(value) def stamp(value: str | datetime) -> datetime: """Parse an explicit time and return the UTC instant (without rounding).""" at = value if isinstance(value, datetime) else datetime.fromisoformat(_text(value, "timestamp")) if at.utcoffset() is None: raise ValueError("explicit_timestamp_zone_required") return at.astimezone(timezone.utc) def _parse_range_endpoint(value, profile: dict) -> datetime: local = datetime.fromisoformat(_text(value, "range_endpoint")) if local.microsecond: raise ValueError("range_endpoint_exceeds_second_resolution") if local.utcoffset() is not None: return stamp(local) if "timezone" not in profile: return stamp(local.replace(tzinfo=timezone(timedelta(hours=profile["tz"])))) zone = ZoneInfo(profile["timezone"]) choices = { stamp(local.replace(tzinfo=zone, fold=fold)) for fold in (0, 1) if stamp(local.replace(tzinfo=zone, fold=fold)).astimezone(zone).replace(tzinfo=None) == local } if len(choices) != 1: raise ValueError("ambiguous_or_missing_local_time_use_offset_or_explicit_branches") return choices.pop() def _profiles(profiles: dict) -> dict: branches = profiles.get("branches") if not isinstance(branches, dict) or not branches: raise ValueError("explicit_profile_branches_required") normalized = {} for branch, item in branches.items(): branch = _text(branch, "branch_id") if not isinstance(item, dict) or branch in normalized: raise ValueError("profile_branch_invalid") profile = deepcopy(item) profile["lat"] = _number(item.get("lat"), -90, 90, "latitude") profile["lon"] = _number(item.get("lon"), -180, 180, "longitude") profile["ayanamsa"] = _text(item.get("ayanamsa"), "ayanamsa").lower() profile["node_mode"] = _text(item.get("node_mode"), "node_mode").lower() if profile["node_mode"] not in ("mean", "true"): raise ValueError("node_mode_invalid") if item.get("timezone") is not None: profile["timezone"] = _text(item["timezone"], "timezone") try: ZoneInfo(profile["timezone"]) except ZoneInfoNotFoundError as exc: raise ValueError("timezone_invalid") from exc if "tz" in item: raise ValueError("supply_either_timezone_or_fixed_offset") else: profile.pop("timezone", None) profile["tz"] = _number(item.get("tz"), -14, 14, "timezone_offset") normalized[branch] = profile return dict(sorted(normalized.items())) def _ranges(remaining_ranges: list, branches: dict) -> list[dict]: if not isinstance(remaining_ranges, list) or not remaining_ranges: raise ValueError("remaining_ranges_required") ranges = [] for source in remaining_ranges: if not isinstance(source, dict): raise ValueError("range_invalid") branch = source.get("branch_id") if branch is None and len(branches) == 1: branch = next(iter(branches)) if not isinstance(branch, str) or branch not in branches: raise ValueError("range_branch_required") start = _parse_range_endpoint(source.get("start"), branches[branch]) end = _parse_range_endpoint(source.get("end"), branches[branch]) closed_start, closed_end = source.get("closed_start", True), source.get("closed_end", True) if type(closed_start) is not bool or type(closed_end) is not bool: raise ValueError("range_boundary_invalid") if start + (timedelta(0) if closed_start else SECOND) > end - (timedelta(0) if closed_end else SECOND): raise ValueError("empty_or_reversed_second_resolution_range") ranges.append({ "branch_id": branch, "start": start.isoformat(), "end": end.isoformat(), "closed_start": closed_start, "closed_end": closed_end, "duration_seconds": int((end - start).total_seconds()), "source": deepcopy(source.get("source")), }) if {item["branch_id"] for item in ranges} != set(branches): raise ValueError("profile_branch_without_remaining_range") ordered = sorted(ranges, key=lambda item: (item["branch_id"], item["start"], item["end"], fingerprint(item))) return [{"range_id": f"r{index}", **item} for index, item in enumerate(ordered, 1)] def range_limits(item: dict) -> tuple[datetime, datetime]: start, end = stamp(item["start"]), stamp(item["end"]) return ( start if item["closed_start"] else start + SECOND, end if item["closed_end"] else end - SECOND, ) def profile_clock(at: datetime, profile: dict) -> datetime: zone = ZoneInfo(profile["timezone"]) if "timezone" in profile else timezone(timedelta(hours=profile["tz"])) return stamp(at).astimezone(zone) def _policy(domains: list[str], granularity: str, version: str) -> dict: # 产品约定,待占星师审核。Use the existing server route's machine-readable # layers for domain scopes. "structure" is the explicit basic-chart scope. forecast = granularity != "structure" layers = [] missing = [] for domain in domains: if domain == "structure" and not forecast: layers.extend(("D1", "D9", "moon_nakshatra")) continue route = plan_route_contract(domain) if domain in ("career", "wealth", "marriage") else None if route is None: missing.append(domain) continue for layer in route.required_layers: if layer not in TIMING_LAYERS or forecast: layers.extend(("Vimshottari", "Narayana") if layer == "Dasha" else (layer,)) if missing or version != POLICY_VERSION: layers.append(MISSING_POLICY_LAYER) if version != POLICY_VERSION: layers = [MISSING_POLICY_LAYER] depth = {"structure": 0, "year": 1, "month": 2, "day": 3}[granularity] return { "id": POLICY_VERSION, "version": version, "route_version": PLAN_VERSION, "required_layers": list(dict.fromkeys(layers)), "missing_domains": missing, "vimshottari_depth": depth, "narayana_depth": min(depth, 2), "decision_predicates": ["structure_identity"] + (["window_presence", f"{granularity}_bucket", "target_boundaries"] if forecast else []), "birth_resolution_seconds": 1, } def _forecast(question: dict, granularity: str) -> dict | None: if granularity == "structure": return None start = stamp(question.get("forecast_start")) end = stamp(question.get("forecast_end")) if end <= start: raise ValueError("forecast_window_reversed") original = datetime.fromisoformat(question["forecast_start"]) raw_targets = question.get("target_boundaries", []) if not isinstance(raw_targets, list): raise ValueError("target_boundaries_invalid") targets = sorted({stamp(item).isoformat() for item in raw_targets}) if any(not start <= stamp(target) <= end for target in targets): raise ValueError("target_boundary_outside_forecast_window") return { "start": start.isoformat(), "end": end.isoformat(), "target_boundaries": targets, "comparison_offset_seconds": int(original.utcoffset().total_seconds()), } def build_scope_request(question: dict, original_input: dict, remaining_ranges: list, profiles: dict, evaluated_at: str) -> dict: """Normalize scope and bind it to the exact candidate set and native profile.""" text = _text(question.get("question"), "question") supplied = question.get("domains") if not isinstance(supplied, list) or not supplied: raise ValueError("domains_required") tokens = [_text(token, "domain").casefold() for token in supplied] domains = sorted({DOMAIN_ALIASES.get(token, token) for token in tokens}) granularity = _text(question.get("granularity"), "granularity") if granularity not in GRANULARITIES: raise ValueError("unsupported_granularity") event_class = question.get("event_class") if event_class is not None: event_class = _text(event_class, "event_class") version = _text(question.get("precision_policy_version", POLICY_VERSION), "precision_policy_version") branches = _profiles(profiles) ranges = _ranges(remaining_ranges, branches) forecast = _forecast(question, granularity) evaluated = stamp(evaluated_at).isoformat() policy = _policy(domains, granularity, version) purpose = { "question": " ".join(text.split()), "domains": domains, "event_class": event_class, "granularity": granularity, "required_techniques": policy["required_layers"], "required_outputs": policy["required_layers"], "decision_predicates": policy["decision_predicates"], "precision_policy_id": POLICY_VERSION, "evaluated_at": evaluated, "forecast_window": forecast, } fingerprints = { "input_revision": _text(original_input.get("input_revision"), "input_revision"), "candidate_set_fingerprint": fingerprint({"ranges": ranges, "zone_resolution": original_input.get("zone_resolution")}), "purpose_fingerprint": fingerprint({key: value for key, value in purpose.items() if key != "forecast_window"}), "profile_fingerprint": fingerprint(branches), "engine_version": _text(profiles.get("engine_version"), "engine_version"), "precision_policy_version": f"{version}:{fingerprint(policy)}", "forecast_window_fingerprint": fingerprint({"window": forecast, "evaluated_at": evaluated}), } return { "schema": "jyotish.purpose_scope_request.v1", "original_time_record": deepcopy(original_input), "plausible_ranges": ranges, "purpose_scope": purpose, "policy": policy, "profiles": branches, "binding": {key: fingerprints[key] for key in BINDING_KEYS}, } def usable(output: dict) -> bool: value = output["value"] return (output["status"] == "executed" and value is not None and type(value) is not bool and value not in ("", [], {}, "blocked", "unavailable", "unknown") and all(isinstance(output.get(key), str) and output[key].strip() for key in ("method_id", "result_ref"))) def _output(item: dict | None, layer: str) -> dict: if item is None: return { "layer": layer, "status": "blocked", "reason": "method_unresolved", "value": None, "result_ref": None, "method_id": None, "dependencies": [], } if not isinstance(item, dict): raise ValueError("native_output_invalid") status = item.get("status") dependencies = item.get("dependencies", []) if status not in KNOWN_STATES or not isinstance(dependencies, list) or not all(isinstance(key, str) for key in dependencies): raise ValueError("native_output_status_or_dependencies_invalid") result = { "layer": layer, "status": status, "value": deepcopy(item.get("value")), "method_id": item.get("method_id"), "result_ref": item.get("result_ref"), "dependencies": list(dependencies), "reason": item.get("reason"), } if "periods" in item: result["periods"] = deepcopy(item["periods"]) if status == "executed" and not usable(result): result["status"], result["reason"] = "blocked", "calculation_failure" if result["status"] == "not_applicable": result["reason"] = result["reason"] or "outside_native_method_scope" return result def _complete_ranges(ranges: list[dict], observed: dict[str, set[datetime]]) -> bool: for item in ranges: start, end = range_limits(item) required = int((end - start).total_seconds()) + 1 count = sum(start <= at <= end for at in observed.get(item["branch_id"], ())) if count != required: return False return True def collect_scope_outputs(scope_request: dict, native_results: list) -> dict: """Collect trusted candidate results only; endpoint samples do not establish coverage.""" required = scope_request["policy"]["required_layers"] profiles = scope_request["profiles"] ranges = scope_request["plausible_ranges"] candidates = [] observed: dict[str, set[datetime]] = {} for row in native_results: branch = row.get("branch_id") if not isinstance(branch, str) or branch not in profiles: raise ValueError("unknown_native_branch") at = stamp(row.get("candidate_at")) if at.microsecond or at in observed.setdefault(branch, set()): raise ValueError("duplicate_or_non_second_native_candidate") covered = [] for item in ranges: start, end = range_limits(item) if item["branch_id"] == branch and start <= at <= end: covered.append(item["range_id"]) if not covered: raise ValueError("native_candidate_outside_scope") if row.get("profile") != profiles[branch]: raise ValueError("native_profile_binding_mismatch") observed[branch].add(at) outputs = row.get("outputs", {}) if not isinstance(outputs, dict) or not all(isinstance(layer, str) and layer for layer in outputs): raise ValueError("native_outputs_invalid") layers = sorted(set(required) | outputs.keys()) candidate_id = f"{branch}@{at.isoformat()}" candidates.append({ "candidate_id": candidate_id, "candidate_at": at.isoformat(), "branch_id": branch, "range_ids": covered, "profile": deepcopy(profiles[branch]), "raw": deepcopy(row.get("raw")), "outputs": {layer: _output(outputs.get(layer), layer) for layer in layers}, }) complete = _complete_ranges(ranges, observed) coverage = {} for layer in required: executed = sum(usable(candidate["outputs"][layer]) for candidate in candidates) coverage[layer] = ("executed_complete" if complete and executed == len(candidates) else "partial" if executed else "blocked") return { "binding": dict(scope_request["binding"]), "required_layers": list(required), "layer_coverage": coverage, "domain_complete": complete, "historical_evidence_state": "not_evaluated", "candidates": sorted(candidates, key=lambda row: (row["branch_id"], row["candidate_at"])), }