Files
Jyotisha/scripts/vedastro_priority.py
T
ClaudeandClaude Opus 5.5 18d17250fe
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m48s
Independent Staging Quality Gate / validate-python (push) Successful in 6m9s
Independent Staging Quality Gate / publish (push) Skipped
fix(report): with VedAstro off the local chart still goes to the top of the reading, so the report packet has D1 and personal reports stop failing as calculation_unavailable (BUG-2429)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-27 00:42:01 +08:00

343 lines
14 KiB
Python

"""Shared VedAstro-first source priority helpers.
This module keeps the user-facing data order identical across the CLI engine,
API server, and MCP strict workflow:
1. VedAstro official full snapshot when it contains an official chart.
2. Local modules as supplemental evidence and cross-checks.
3. Local chart as fallback only when the official snapshot is blocked.
"""
from __future__ import annotations
import re
from copy import deepcopy
from typing import Any
try:
from scripts.vedastro_echo_guard import ayanamsa_code
from scripts.vedastro_switch import DISABLED_REASON, is_disabled_packet
except ModuleNotFoundError: # pragma: no cover - script execution path
from vedastro_echo_guard import ayanamsa_code
from vedastro_switch import DISABLED_REASON, is_disabled_packet
SOURCE_PRIORITY = [
"vedastro_official_snapshot",
"local_supplemental_modules",
"local_engine_fallback_when_official_blocked",
]
def official_chart_available(official_snapshot: dict[str, Any] | None) -> bool:
if not isinstance(official_snapshot, dict):
return False
official_chart = official_snapshot.get("official_chart")
if not isinstance(official_chart, dict):
return False
return (
isinstance(official_chart.get("planets"), dict)
and bool(official_chart.get("planets"))
and isinstance(official_chart.get("ascendant"), dict)
and bool(official_chart.get("ascendant"))
)
# --- BUG-2427: the official chart may replace the local chart only for the same birth ---
# The VedAstro API answers "Pass" for its own sample chart when it ignores a request
# (BUG-2172). The transport already rejects such answers; this second check sits at the
# one place where an official chart can replace the local one, so a future re-enable,
# a stale cache, or a new transport cannot silently swap in somebody else's chart.
_CHART_SECTIONS = ("chart_core", "house_core")
_STD_TIME = re.compile(r"^\s*(\d{1,2}):(\d{2})\s+(\d{1,2})/(\d{1,2})/(\d{4})\s+([+-])(\d{1,2}):(\d{2})\s*$")
_COORD_TOLERANCE = 0.01
_TZ_TOLERANCE_HOURS = 1 / 120 # half a minute
def _num(value: Any) -> float | None:
if isinstance(value, bool):
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _tz_hours(value: Any) -> float | None:
number = _num(value)
if number is not None:
return number
text = str(value or "").strip().upper().replace("UTC", "").replace("GMT", "").strip()
match = re.fullmatch(r"([+-]?)(\d{1,2}):(\d{2})", text)
if match:
sign = -1 if match.group(1) == "-" else 1
return sign * (int(match.group(2)) + int(match.group(3)) / 60)
return _num(text)
def _requested_birth(report: dict[str, Any]) -> dict[str, Any] | None:
"""The birth the caller asked for, read from the local report (never from VedAstro)."""
candidates = [report.get("birth_info"), report.get("birth")]
chart = report.get("chart")
if isinstance(chart, dict):
candidates.append(chart.get("birth_info"))
for info in candidates:
if not isinstance(info, dict):
continue
date_text = str(info.get("date") or "")
date_match = re.fullmatch(r"(\d{4})-(\d{1,2})-(\d{1,2})", date_text)
hour, minute = info.get("hour"), info.get("minute")
if (hour is None or minute is None) and isinstance(info.get("time"), str):
parts = info["time"].split(":")
if len(parts) >= 2:
hour, minute = parts[0], parts[1]
values = {
"hour": _num(hour),
"minute": _num(minute),
"lat": _num(info.get("lat")),
"lon": _num(info.get("lon")),
"tz": _tz_hours(info.get("tz")),
}
if not date_match or any(value is None for value in values.values()):
continue
return {
"date": tuple(int(part) for part in date_match.groups()),
**values,
"ayanamsa": info.get("ayanamsa_name") or info.get("ayanamsa") or report.get("ayanamsa_name"),
}
return None
def _echo_time_objects(value: Any):
if isinstance(value, dict):
if isinstance(value.get("StdTime"), str):
yield value
for item in value.values():
yield from _echo_time_objects(item)
elif isinstance(value, list):
for item in value:
yield from _echo_time_objects(item)
def _echo_matches_birth(time_object: dict[str, Any], birth: dict[str, Any]) -> bool:
match = _STD_TIME.match(str(time_object.get("StdTime") or ""))
if not match:
return False
hour, minute, day, month, year = (int(match.group(i)) for i in range(1, 6))
tz = (-1 if match.group(6) == "-" else 1) * (int(match.group(7)) + int(match.group(8)) / 60)
location = time_object.get("Location") if isinstance(time_object.get("Location"), dict) else {}
lat, lon = _num(location.get("Latitude")), _num(location.get("Longitude"))
return (
(year, month, day) == birth["date"]
and hour == int(birth["hour"])
and minute == int(birth["minute"])
and abs(tz - birth["tz"]) <= _TZ_TOLERANCE_HOURS
and lat is not None
and lon is not None
and abs(lat - birth["lat"]) <= _COORD_TOLERANCE
and abs(lon - birth["lon"]) <= _COORD_TOLERANCE
)
def _snapshot_sections(official_snapshot: dict[str, Any]) -> dict[str, Any]:
sections = official_snapshot.get("snapshot_sections")
if not isinstance(sections, dict):
raw = official_snapshot.get("raw_response")
sections = raw.get("sections") if isinstance(raw, dict) else None
return sections if isinstance(sections, dict) else {}
def official_chart_echo_check(report: dict[str, Any], official_snapshot: dict[str, Any] | None) -> dict[str, Any]:
"""``matched`` only when every chart/house answer echoes the requested birth and ayanamsa."""
if not isinstance(official_snapshot, dict):
return {"status": "mismatch", "reason": "official_snapshot_missing"}
birth = _requested_birth(report) if isinstance(report, dict) else None
if birth is None:
return {"status": "mismatch", "reason": "requested_birth_missing"}
wanted_ayanamsa = ayanamsa_code(birth.get("ayanamsa"))
if wanted_ayanamsa is None:
return {"status": "mismatch", "reason": "requested_ayanamsa_unverifiable"}
sections = _snapshot_sections(official_snapshot)
checked = 0
for section in _CHART_SECTIONS:
answers = sections.get(section)
if not isinstance(answers, dict) or not answers:
return {"status": "mismatch", "reason": f"{section}_missing"}
for payload in answers.values():
if not isinstance(payload, dict) or str(payload.get("Status") or "") != "Pass":
return {"status": "mismatch", "reason": f"{section}_not_pass"}
echoed = payload.get("Input")
if not isinstance(echoed, dict):
return {"status": "mismatch", "reason": "echo_input_missing"}
times = list(_echo_time_objects(echoed))
if not times or not all(_echo_matches_birth(item, birth) for item in times):
return {"status": "mismatch", "reason": "echo_time_or_place_differs"}
try:
if int(echoed.get("Ayanamsa")) != wanted_ayanamsa:
return {"status": "mismatch", "reason": "echo_ayanamsa_differs"}
except (TypeError, ValueError):
return {"status": "mismatch", "reason": "echo_ayanamsa_missing"}
checked += 1
return {"status": "matched", "checked_answers": checked}
def _local_chart_from(report: dict[str, Any], modules: dict[str, Any]) -> dict[str, Any]:
chart = report.get("chart")
if isinstance(chart, dict) and chart:
return chart
chart = modules.get("chart")
return chart if isinstance(chart, dict) else {}
def _blocked_reason(official_snapshot: dict[str, Any] | None) -> str:
status = "missing"
if isinstance(official_snapshot, dict):
status = str(official_snapshot.get("status") or "blocked")
return f"VedAstro official snapshot blocked: {status}"
def build_source_priority_metadata(
official_snapshot: dict[str, Any] | None,
*,
official_primary: bool,
) -> dict[str, Any]:
status = official_snapshot.get("status") if isinstance(official_snapshot, dict) else "missing"
return {
"mode": "vedastro_official_primary" if official_primary else "local_fallback_official_blocked",
"priority": list(SOURCE_PRIORITY),
"official_snapshot_first": True,
"official_snapshot_status": status or "blocked",
"local_engine_role": (
"supplemental_crosscheck_or_fallback"
if official_primary
else "fallback_only_because_official_blocked"
),
"user_visible_policy": (
"show_vedastro_verified_when_official_chart_available"
if official_primary
else "show_local_fallback_with_official_blocked_boundary"
),
}
def apply_vedastro_source_priority(
report: dict[str, Any],
*,
official_snapshot: dict[str, Any] | None,
) -> dict[str, Any]:
if not isinstance(report, dict):
return report
modules = report.setdefault("modules", {})
if not isinstance(modules, dict):
modules = {}
report["modules"] = modules
if isinstance(official_snapshot, dict):
modules["vedastro_official_full_snapshot"] = official_snapshot
local_chart = _local_chart_from(report, modules)
if is_disabled_packet(official_snapshot):
# BUG-2427: VedAstro is off by decision. The local chart is the chart; nothing is
# rewritten and no "official blocked" fallback wording is attached to it.
# BUG-2429: the local chart's planets / ascendant / houses still go to the top of
# the report, as every other branch does. 原值:直接返回,顶层没有这三项,报告包的
# core_chart 只剩 chart,D1 盘取不到,长报告快照校验失败(calculation_unavailable)。
for key in ("planets", "ascendant", "houses"):
if key in local_chart:
report[key] = local_chart[key]
modules["source_priority"] = {
"mode": "local_engine_vedastro_disabled",
"official_snapshot_status": "disabled",
"reason": DISABLED_REASON,
"user_visibility": "backstage_only",
}
return report
echo_check = (
official_chart_echo_check(report, official_snapshot)
if official_chart_available(official_snapshot)
else None
)
if echo_check is not None:
modules["vedastro_official_echo_check"] = echo_check
if echo_check is not None and echo_check.get("status") == "matched":
official_chart = official_snapshot.get("official_chart") # type: ignore[union-attr]
modules["local_engine_chart_fallback"] = deepcopy(local_chart)
public_chart = {
**deepcopy(local_chart),
"source": "vedastro_official_primary",
"primary_source": "vedastro_official",
"fallback_source": "local_engine",
"local_engine_role": "supplemental_crosscheck_or_fallback",
"local_crosscheck_status": "pending",
"source_priority": list(SOURCE_PRIORITY),
"planets": official_chart.get("planets", {}),
"ascendant": official_chart.get("ascendant", {}),
"houses": official_chart.get("houses", {}),
"birth_info": local_chart.get("birth_info", report.get("birth_info", report.get("birth", {}))),
"official_coverage": official_chart.get("coverage", {}),
}
report["chart"] = public_chart
modules["chart"] = public_chart
for key in ("source", "primary_source", "fallback_source", "planets", "ascendant", "houses"):
if key in public_chart:
report[key] = public_chart[key]
modules["source_priority"] = build_source_priority_metadata(
official_snapshot,
official_primary=True,
)
return report
if local_chart:
fallback_chart = {
**deepcopy(local_chart),
"source": "local_engine_fallback",
"primary_source": "local_engine",
"fallback_reason": (
f"VedAstro official chart rejected: {echo_check.get('reason')}"
if echo_check is not None
else _blocked_reason(official_snapshot)
),
"local_engine_role": "fallback_only_because_official_blocked",
"source_priority": list(SOURCE_PRIORITY),
}
report["chart"] = fallback_chart
modules["chart"] = fallback_chart
for key in ("source", "primary_source", "planets", "ascendant", "houses"):
if key in fallback_chart:
report[key] = fallback_chart[key]
modules["source_priority"] = build_source_priority_metadata(
official_snapshot,
official_primary=False,
)
return report
def official_snapshot_evidence(modules: dict[str, Any]) -> dict[str, Any]:
snapshot = modules.get("vedastro_official_full_snapshot") if isinstance(modules, dict) else {}
source_priority = modules.get("source_priority") if isinstance(modules, dict) else {}
if not isinstance(snapshot, dict) or not snapshot:
return {
"level": "blocked",
"source": "vedastro_official",
"status": "missing",
"operation": "official_full_snapshot",
"source_priority": source_priority if isinstance(source_priority, dict) else {},
"reason": "VedAstro official full snapshot is not attached.",
}
level = "primary" if official_chart_available(snapshot) else "blocked"
return {
"level": level,
"source": "vedastro_official",
"status": snapshot.get("status") or "blocked",
"available": bool(snapshot.get("available")),
"operation": snapshot.get("operation") or "official_full_snapshot",
"source_priority": source_priority if isinstance(source_priority, dict) else {},
"section_statuses": snapshot.get("section_statuses") or {},
"chart_available": official_chart_available(snapshot),
"reason": snapshot.get("reason"),
}