Files
Jyotisha/scripts/report_render/reading_facts.py
T
ClaudeandClaude Opus 5.5 bbdb274931
Independent Staging Quality Gate / validate-python (push) Successful in 10m15s
Independent Staging Quality Gate / validate-frontend (push) Successful in 14m5s
Independent Staging Quality Gate / publish (push) Successful in 3m26s
fix(report,chat): reading facts and the chat card follow the astrologer's D/E/G states; chat basis reads the shared topic chart table (BUG-2163)
- Debilitation: verified reads 「落陷;另有缓解条件,不代表困难全部消失」, a candidate (neecha_states)
  reads 「落陷;缓解条件待核」, uncomputed / not met / self-reference only stay 「落陷」; the
  chat card, evidence pack, computed fallback and writer rule R-06 follow.
- Connections: plain words for pd_range_split / pd_stability_not_assessed and for a truncated or
  missing chain; an unassessed topic chart no longer hides an undetermined house; the use rule says
  unfinished or unassessed is never 'no connection'.
- Chat basis completion reads references/topic_varga_routes.json (parents D12 only, children D7,
  siblings D3, residence D4, education D24; D9 never a career chart).
- test_reading_facts_2126 follows the BUG-2151 wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-22 12:46:35 +08:00

1503 lines
76 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Facts for the model-written reading at the front of the report (issue #113 R1).
The reading is written by a model, but only from what the engine already
computed. This module copies the consult-card leaves (the same facts the chat
uses) from the report's own full-data packet and adds the rest of the
calculation the astrologer's skill asks a reading to stand on.
产品 2026-11-07 占星师方案 item 10 (reading_facts contract): one contract with
birth parameters, all houses, every domain's vargas, lords, functional roles,
yogas with their conditions, all current dasha layers (Vimshottari and
Narayana with dates, plus every other family's current period and status),
transits, strengths, Ashtakavarga, KP, Jaimini, the annual chart, evidence
paths, method differences and blocked states. The birth-precision margins
reuse the natal engine's ascendant calculation to bracket sign changes.
"""
from __future__ import annotations
import copy
import re
from datetime import date
from typing import Any
from .birth_precision_margins import ascendant_margins
from .birth_precision_window import (
DEFAULT_WINDOW_SCENARIO, DEFAULT_WINDOW_SOURCE, birth_window_label_zh, report_birth_window,
)
from .evidence_grade import evidence_grades
from .narayana_extras_store import ensure_narayana_report_extras
from .neecha_witness import neecha_states as _neecha_states
from .indirect_activation import PATHS as CONNECTION_PATHS, attach_indirect_activation, path_cell
from .parity_chapters import _VIMSOPAKA_DIGNITY
from .technique_status_axes import technique_audit_axes
from .yoga_status_words import rule_condition_text
from .transit_natal_sign import (
SADE_SATI_SCOPE_ZH, sade_sati_summary_zh, saturn_from_moon, slow_transit_key_dates, transit_natal_sign_facts,
)
try:
from scripts.consult_facts.evidence_ids import dasha_id, house_id, point_id, shadbala_id, transit_id, yoga_id
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
from consult_facts.evidence_ids import dasha_id, house_id, point_id, shadbala_id, transit_id, yoga_id
# BUG-2113 follow-up: the gap line rule_condition_text returns for definitions it cannot word.
_RULE_CONDITION_GAP_ZH = "条件没有随报告列出"
# BUG-1976: special-lagna keys named the way the chat facts name the same points.
POINT_IDS = {"Indu_Lagna": "Indu", "Pranapada_Lagna": "Pranapada", "ViGhati_Lagna": "Vighati"}
try:
from scripts.consult_card_domain_facts import (
HORA_OF_SIGN,
HORA_VARGAS,
PLANETS,
PRECISION_SENTENCE,
PRECISION_VARGA,
_house_record,
_varga_chart,
_varga_planet_path,
assert_fact_leaves,
build_consult_card_facts,
dig,
)
from scripts.consult_full_data_cache import _attach_graha_drishti
from scripts.narayana_legacy_label import (
narayana_report_branch_periods,
narayana_report_date_pair,
narayana_report_unresolved,
)
from scripts.shadbala_display import row_fields
from scripts.pl9_full_data_export import full_data_domain_base, read_full_data_domain
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
from consult_card_domain_facts import (
HORA_OF_SIGN,
HORA_VARGAS,
PLANETS,
PRECISION_SENTENCE,
PRECISION_VARGA,
_house_record,
_varga_chart,
_varga_planet_path,
assert_fact_leaves,
build_consult_card_facts,
dig,
)
from consult_full_data_cache import _attach_graha_drishti
from narayana_legacy_label import (
narayana_report_branch_periods,
narayana_report_date_pair,
narayana_report_unresolved,
)
from shadbala_display import row_fields
from pl9_full_data_export import full_data_domain_base, read_full_data_domain
READING_FACTS_SCHEMA = "report-reading-facts-v3"
READING_DOMAINS = ("general", "career", "wealth", "marriage", "health")
TIMING = "worksheets.timing_and_predictive_systems"
DASHA = f"{TIMING}.dasha.current_dasha"
NARAYANA = f"{TIMING}.narayana_dasha"
FAMILIES = f"{TIMING}.dasha_master_pack.families"
TRANSIT = f"{TIMING}.transit_positions"
TRANSIT_REF = f"{TIMING}.transit_multi_reference"
DOUBLE_TRANSIT = f"{TIMING}.double_transit_pac"
ANNUAL = f"{TIMING}.annual_tajika_pack"
FUNCTIONAL = "worksheets.strengths_and_scores.functional_benefic_malefic"
ASHTAKAVARGA = "worksheets.strengths_and_scores.ashtakavarga"
VIMSOPAKA = "worksheets.strengths_and_scores.vimsopaka"
AVASTHA = "worksheets.advanced_systems.avasthas"
KP = "worksheets.advanced_systems.kp"
JAIMINI = "worksheets.advanced_systems.jaimini"
YOGA = "worksheets.advanced_systems.yoga"
SADE_SATI = "worksheets.advanced_systems.yogas_doshas.sade_sati"
DIVISIONAL = "worksheets.divisional_and_special_charts"
LAGNAS = f"{DIVISIONAL}.special_lagnas"
LEDGER = "full_report_pack.sections.d1_d60_ledger"
UPCOMING_SUB_PERIODS = 2
# BUG-1976: read the report's yoga layer once for the evidence ids (it is cached on the packet).
YOGA_LAYER_FOR_IDS = True
UPCOMING_NARAYANA = 2
SLOW_TRANSITS = ("Jupiter", "Saturn", "Rahu", "Ketu")
NATURAL_BENEFICS = ("Jupiter", "Venus", "Mercury", "Moon")
PRECISION_POINTS = ("Ghati_Lagna", "ViGhati_Lagna", "Pranapada_Lagna")
NOTE_LIMIT = 280
# Statuses that keep a technique out of the judgment (interpretation_status_contract.md).
BLOCKED_STATES = {"blocked", "gap", "error", "missing"}
CONDITIONAL_STATES = {"parameter_sensitive", "partial", "partial_verified", "conflict", "conditional"}
UNUSED_REASONS = {"not_routed", "not_in_domain_route"}
# BUG-1964 (占星师 2026-11-17 第二批第 1–3 项): Vighati keeps its position only, the 64th Navamsa
# and Pranapada are auxiliary layers; none of the three is a blocked row any more.
# BUG-1965 (第 4–6 项): AL's 2nd / 11th and UL's 2nd are derived rows now, not blocked ones.
PARTICIPATION_REASON_CODES = {
("education", "D5"): "not_in_domain_route",
("migration", "D12"): "not_routed",
("family", "D4"): "not_routed",
("family", "D7"): "not_routed",
("general", "D10"): "not_routed",
("general", "D2"): "not_routed",
}
STRUCTURED_VALUES = {
"Badhaka": ("ascendant_sign", "ascendant_modality", "badhaka_sthana", "badhakesh", "source", "status",
"profile", "profile_rule"),
}
PARTICIPATION_BLOCKED_REASONS = {
"missing_input": "missing_input", "error": "call_failed",
"calculation_failed": "call_failed", "call_failed": "call_failed",
"validation_failed": "validation_failed",
}
UNUSED_POINT_PATHS = {
"Indu": f"{LAGNAS}.Indu_Lagna.sign",
"Vighati": f"{LAGNAS}.ViGhati_Lagna.sign",
"Pranapada": f"{LAGNAS}.Pranapada_Lagna.sign",
"Gulika": f"{DIVISIONAL}.upagrahas.raw.Gulika.sign_idx",
"Mandi": f"{DIVISIONAL}.upagrahas.raw.Maandi.sign_idx",
"navamsa64": f"{DIVISIONAL}.sensitive_points.navamsa_64th.sign",
}
_ISSUE_REFERENCE = r"#\d+(?:[ \t]+Q\d+\b(?:[ \t]*/[ \t]*Q\d+\b)*)?"
_INTERNAL_ISSUE_REFERENCE = re.compile(
rf"\([ \t]*{_ISSUE_REFERENCE}[ \t]*\)|([ \t]*{_ISSUE_REFERENCE}[ \t]*)|{_ISSUE_REFERENCE}"
)
def _strip_internal_issue_references(node: Any) -> Any:
"""Remove internal issue references from model-facing string values."""
if isinstance(node, dict):
return {key: _strip_internal_issue_references(value) for key, value in node.items()}
if isinstance(node, list):
return [_strip_internal_issue_references(value) for value in node]
if not isinstance(node, str):
return node
text, removed = _INTERNAL_ISSUE_REFERENCE.subn(" ", node)
if not removed:
return node
text = re.sub(r"([,;:,;:、])[ \t]+[,;:,;:、]", r"\1", text)
text = re.sub(r"[ \t]+([,.;:!?,。;:!?、])", r"\1", text)
text = re.sub(r"[ \t]{2,}", " ", text).strip().strip(" \t,;:,;:、")
text = re.sub(r"^[//] | [//]$", "", text)
return text if text.strip(".!?。!?//") else None
def _compact(node: Any) -> Any:
"""Leaf values only. Gaps, withheld and blocked leaves are left out."""
if isinstance(node, dict):
if "status" in node and "check" in node:
return node.get("value") if node["status"] == "value" else None
out = {}
for key, value in node.items():
kept = _compact(value)
if kept is not None and kept != {} and kept != []:
out[key] = kept
return out
if isinstance(node, list):
return [item for item in (_compact(entry) for entry in node) if item is not None]
return node
def _pick(node: Any, keys: tuple[str, ...]) -> dict[str, Any]:
if not isinstance(node, dict):
return {}
return {key: node[key] for key in keys if node.get(key) not in (None, "", [], {})}
def _day(value: Any) -> str | None:
return value[:10] if isinstance(value, str) and len(value) >= 10 else None
def _period(row: Any) -> dict[str, Any] | None:
if not isinstance(row, dict) or not isinstance(row.get("lord"), str):
return None
out = {"lord": row["lord"]}
for key in ("start", "end"):
if isinstance(row.get(key), str):
out[key] = row[key]
return out
def _with_dasha_id(row: dict[str, Any] | None, level: str, parents: tuple[str, ...] = ()) -> dict[str, Any] | None:
"""BUG-1976 / BUG-1978: the period's evidence id by its lord chain, the same the chat facts give it."""
if row and isinstance(row.get("lord"), str) and all(isinstance(lord, str) for lord in parents):
return {"evidence_id": dasha_id("vim", level, (*parents, row["lord"])), **row}
return row
def _vimshottari(packet: dict) -> dict[str, Any]:
current = dig(packet, DASHA)
if not isinstance(current, dict):
return {}
dates: dict[str, Any] = {}
md = _with_dasha_id(_period(current), "md")
md_lord = (md or {}).get("lord")
if md:
dates["mahadasha"] = md
rows = current.get("antardasha_timeline")
if isinstance(rows, list):
index = next((i for i, row in enumerate(rows) if isinstance(row, dict) and row.get("is_current") is True), None)
if index is not None:
now = _with_dasha_id(_period(rows[index]), "ad", (md_lord,))
if now:
dates["antardasha"] = now
nested = rows[index].get("pratyantar_dasha_timeline")
if isinstance(nested, list):
pd = next((_period(item) for item in nested if isinstance(item, dict) and item.get("is_current") is True), None)
if pd:
dates["pratyantardasha"] = _with_dasha_id(pd, "pd", (md_lord, (now or {}).get("lord")))
upcoming = [_with_dasha_id(_period(row), "ad", (md_lord,))
for row in rows[index + 1:index + 1 + UPCOMING_SUB_PERIODS]]
dates["next_antardashas"] = [row for row in upcoming if row]
return dates
def _narayana_row(row: Any) -> dict[str, Any] | None:
if not isinstance(row, dict) or not isinstance(row.get("sign"), str):
return None
out = _pick(row, ("sign", "lord", "start_age", "end_age"))
if dates := narayana_report_date_pair(row.get("start_date"), row.get("end_date")):
out["start"], out["end"] = dates
else:
out["date_status"] = "no_engine_date"
return out
def _following(rows: Any, current: dict | None, count: int) -> list[dict[str, Any]]:
if not isinstance(rows, list) or not current:
return []
index = next((i for i, row in enumerate(rows) if isinstance(row, dict)
and row.get("sign") == current.get("sign") and row.get("start_age") == current.get("start_age")), None)
if index is None:
return []
following = [_narayana_row(row) for row in rows[index + 1:index + 1 + count]]
return [row for row in following if row]
def _narayana(packet: dict) -> dict[str, Any]:
"""Preserve the engine's periods, unresolved steps and independent candidates."""
node = dig(packet, NARAYANA)
if not isinstance(node, dict):
return {}
current = node.get("current_dasha") or {}
out = _pick(node, ("profile", "algorithm_label", "direction_text", "status", "date_basis"))
for key in ("algorithm_label", "direction_text"):
if isinstance(out.get(key), str):
out[key] = without_citations(out[key]) # BUG-2130
method = node.get("method_status") or {}
if method:
out["method_status"] = {key: copy.deepcopy(method[key])
for key in ("status", "unresolved_steps", "text") if key in method}
md = _narayana_row(current.get("md"))
ad = _narayana_row(current.get("ad"))
if md:
out["mahadasha"] = md
out["next_mahadashas"] = _following(node.get("mahadasha"), md, UPCOMING_NARAYANA)
if ad:
out["antardasha"] = ad
out["next_antardashas"] = _following(node.get("current_md_antardasha"), ad, UPCOMING_SUB_PERIODS)
out.update(_pick(current, ("ad_status", "ad_reason")))
legacy = node.get("legacy") or {}
legacy_md = _narayana_row(dig(legacy, "current_dasha.md"))
if legacy_md:
legacy_label = _pick(legacy, ("algorithm_label",))
if isinstance(legacy_label.get("algorithm_label"), str):
legacy_label["algorithm_label"] = without_citations(legacy_label["algorithm_label"]) # BUG-2130
out["legacy_comparison"] = {"mahadasha": legacy_md, **legacy_label}
if narayana_report_unresolved(node):
out["branches"] = [
{**{key: branch.get(key) for key in ("branch_id", "parent_branch_id", "unresolved_step", "candidate")},
"used_for_scoring": False,
"md_periods": narayana_report_branch_periods(branch.get("md_periods") or []),
"ad_periods": narayana_report_branch_periods(branch.get("ad_periods") or [])}
for branch in node.get("branches") or []
]
out["branch_summary"] = _pick(node.get("branch_summary"), ("candidates_exhausted",))
if node.get("years_unresolved"):
out["years_unresolved"] = copy.deepcopy(node["years_unresolved"])
if readings := _narayana_direction_readings(packet):
out["direction_readings"] = readings
return out
NARAYANA_REPORT_EXTRAS = f"{TIMING}.narayana_dasha_report_extras"
def _narayana_reading_period(value: Any) -> dict[str, Any] | None:
if not isinstance(value, dict) or not isinstance(value.get("sign"), str):
return None
out = _pick(value, ("sign", "lord", "start_age", "end_age"))
if dates := narayana_report_date_pair(value.get("start_date"), value.get("end_date")):
out["start"], out["end"] = dates
return out
_SIGN_ZH_NARAYANA = {
"Aries": "白羊座", "Taurus": "金牛座", "Gemini": "双子座", "Cancer": "巨蟹座", "Leo": "狮子座",
"Virgo": "处女座", "Libra": "天秤座", "Scorpio": "天蝎座", "Sagittarius": "射手座",
"Capricorn": "摩羯座", "Aquarius": "水瓶座", "Pisces": "双鱼座",
}
_DIRECTION_ZH_NARAYANA = {"zodiacal": "顺排", "reverse": "逆排"}
# BUG-2130 (产品负责人 2026-11-21): report text names no books, authors, tables, chapters or pages. Applied to the
# labels the writer may copy; ids stay. The patterns mirror frontend/src/lib/report-citations.ts.
_CITATION_TOKEN = r"(?:p\.\s*\d|表\s*\d|Table\s*\d|第\s*\d+\s*[节章]|\bRath\b|\bPVR\b|\bBPHS\b|J\.S\.|原书|裁定|《)"
# A parenthesis (one nested level allowed) that carries a citation is dropped whole: 「(默认;按原书 p.43 正文(第七轮裁定))」.
_CITATION_PAREN = re.compile(
r"[((](?:[^()()]|[((][^()()]*[))])*?" + _CITATION_TOKEN + r"(?:[^()()]|[((][^()()]*[))])*[))]")
# A citation at the head or tail of a parenthesis that also says something: 「(PVR 表 74,按回归时刻昼夜取式)」 keeps the rest.
_CITATION_LEAD = re.compile(r"(?<=[((])\s*(?:按\s*)?(?:PVR|Rath|BPHS)\s*表\s*\d+(?:\.\d+)?\s*[,,;;]\s*")
_CITATION_TAIL = re.compile(r"\s*[,,;;]\s*(?:按\s*)?(?:PVR|Rath|BPHS)\s*表\s*\d+(?:\.\d+)?(?=\s*[))])")
_CITATION_WORDS = (
(re.compile(r"Sanjay\s+Rath\s*版"), "默认排法"),
(re.compile(r"Rath\s*版"), "默认排法"),
(re.compile(r"Rath\s*规则"), "传统规则"),
(re.compile(r"按\s*PVR\s*表\s*\d+(?:\.\d+)?"), "按传统划分"),
(re.compile(r"PVR\s*表\s*\d+(?:\.\d+)?"), "传统划分"),
(re.compile(r"BPHS\s*例外表"), "另一套具名划分"),
(re.compile(r"(?:移植上游\s*)?PVR\s*\d+(?:\.\d+)?\s*"), ""), # 「移植上游 PVR 30.4 太阳角距版」
)
_FUNCTIONAL_PROFILE_PLAIN = {
"pvr_table30_v1": "按这张盘上升星座的传统功能吉凶划分",
"bphs_exception_profile": "另一套按上升星座的具名划分",
}
def _citation_gap(match: re.Match) -> str:
"""「Narayana(Rath 版)同期」 → 「Narayana 同期」: a space keeps a Latin word apart from the Chinese after it."""
before, after = match.string[:match.start()], match.string[match.end():]
return " " if re.search(r"[A-Za-z0-9]$", before) and re.match(r"[\u4e00-\u9fff]", after) else ""
def without_citations(text: str) -> str:
"""Drop citations and name the method plainly (BUG-2130, 产品负责人 2026-11-21「报告里的书名引文也去掉」)."""
text = _CITATION_TAIL.sub("", _CITATION_LEAD.sub("", text))
previous = None
while previous != text:
previous = text
text = _CITATION_PAREN.sub(_citation_gap, text)
for pattern, plain in _CITATION_WORDS:
text = pattern.sub(plain, text)
# 「用 Rath 规则」 → 「用传统规则」: a space the citation left between two Chinese characters goes.
text = re.sub(r"(?<=[\u4e00-\u9fff])[ \t]+(?=[\u4e00-\u9fff])", "", text)
return re.sub(r"\s{2,}", " ", text).strip()
def _narayana_reading_description(row: dict) -> str:
"""BUG-2108: the plain words the writer uses for one reading; the profile id stays out of the text."""
rule = row.get("rule_text") if isinstance(row.get("rule_text"), str) else ""
while (stripped := re.sub(r"[((][^()()]*[))]", "", rule)) != rule: # nested book citations
rule = stripped
rule = without_citations(rule.strip())
parts = ["默认排法" if row.get("default") is True else "另一种排法"]
detail = []
if rule:
detail.append(rule)
if isinstance(row.get("start_sign"), str):
detail.append(f"从{_SIGN_ZH_NARAYANA.get(row['start_sign'], row['start_sign'])}起")
if (word := _DIRECTION_ZH_NARAYANA.get(row.get("direction"))):
detail.append(word)
return parts[0] + (":" + ",".join(detail) if detail else "")
def _narayana_direction_readings(packet: dict) -> dict[str, Any] | None:
"""Both direction readings of the running Narayana sub-periods, when the report stored them (BUG-2106).
The report computes them with narayana_report_extras (BUG-2088) and stores the result at
NARAYANA_REPORT_EXTRAS (BUG-2105); absent → nothing. Narayana is conditional (占星师 2026-11-07 Q1,
2026-11-08 profiles) and the reading names techniques only in 「依据与边界」 (BUG-2098), so the block is
marked for that section.
"""
extras = dig(packet, NARAYANA_REPORT_EXTRAS)
rows = extras.get("ad_direction_readings") if isinstance(extras, dict) else None
if not isinstance(rows, list):
return None
readings = []
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("profile"), str):
continue
# BUG-2130: rule_text carries book pages and tables (「p.50 规则 (12)」「Rath 表 13」); description_zh says it plainly.
item = {**_pick(row, ("profile", "status", "reason", "start_sign", "direction")),
"default": row.get("default") is True}
item["description_zh"] = _narayana_reading_description(row)
if isinstance(row.get("exception_applied"), bool):
item["exception_applied"] = row["exception_applied"]
for level in ("md", "ad"):
if period := _narayana_reading_period(row.get(level)):
item[level] = period
readings.append(item)
if not readings:
return None
return {"use_in": "依据与边界",
# BUG-2108: profile ids are internal codes; the reading writes description_zh instead.
"text_rule": "写进「依据与边界」时用 description_zh 说这一种排法,不写 profile 代号,也不写书名、作者、表号和页码",
"readings": readings}
def _current_row(rows: Any, today: str) -> tuple[int, dict] | None:
if not isinstance(rows, list):
return None
for index, row in enumerate(rows):
if not isinstance(row, dict):
continue
start, end = _day(row.get("start") or row.get("start_date")), _day(row.get("end") or row.get("end_date"))
if start and end and start <= today < end:
return index, row
return None
def _family_period(row: dict) -> dict[str, Any]:
out = _pick(row, ("lord", "sign"))
if not out.get("lord") and isinstance(row.get("planet"), str):
out["lord"] = row["planet"]
if not out.get("sign") and isinstance(row.get("rashi"), str):
out["sign"] = row["rashi"]
for key, alt in (("start", "start_date"), ("end", "end_date")):
value = _day(row.get(key) or row.get(alt))
if value:
out[key] = value
return out
def _dasha_families(packet: dict, today: str) -> list[dict[str, Any]]:
"""Every dasha family the engine ran: status and its running period on `today`."""
families = dig(packet, FAMILIES)
if not isinstance(families, dict):
return []
out = []
for name, family in families.items():
if not isinstance(family, dict):
continue
row: dict[str, Any] = {"family": name, **_pick(family, ("status", "execution_status"))}
found = _current_row(family.get("periods"), today)
if found:
period = found[1]
row["current"] = _family_period(period)
sub = _current_row(period.get("antardasha"), today)
if sub:
row["current_sub"] = _family_period(sub[1])
elif family.get("reason"):
row["reason"] = str(family["reason"])[:NOTE_LIMIT]
out.append(row)
return out
def _functional(packet: dict) -> dict[str, Any]:
from .technique_status_axes import FUNCTIONAL_PROFILE_LABELS
table = dig(packet, FUNCTIONAL)
if not isinstance(table, dict):
return {"status": "blocked", "functional_profile": None, "functional_profile_label": "口径未注明"}
out = _pick(table, (
"status", "lagna_lord", "functional_benefics", "functional_malefics",
"functional_neutrals", "yogakarakas", "owned_houses", "effect_on_confidence",
))
profile = table.get("functional_profile")
out["functional_profile"] = profile
# BUG-2130 (产品负责人 2026-11-21「报告里的书名引文也去掉」): the writer gets a plain description instead of the
# table citation (原值「PVR 表 30」); the profile id stays for traceability.
out["functional_profile_label"] = _FUNCTIONAL_PROFILE_PLAIN.get(
profile, without_citations(FUNCTIONAL_PROFILE_LABELS.get(profile, "口径未注明")))
benefic = set(table.get("functional_benefics") or []) | set(table.get("yogakarakas") or [])
malefic = set(table.get("functional_malefics") or [])
conflicts = []
for planet in PLANETS:
if planet in ("Rahu", "Ketu"):
continue
natural = "benefic" if planet in NATURAL_BENEFICS else "malefic"
functional = "benefic" if planet in benefic else "malefic" if planet in malefic else None
if functional and functional != natural:
conflicts.append({"planet": planet, "natural": natural, "functional": functional})
out["natural_vs_functional_conflicts"] = conflicts
return out
def _avastha(packet: dict, name: str) -> dict[str, Any]:
states = dig(packet, f"{AVASTHA}.{name}.avasthas")
if not isinstance(states, dict):
return {}
return {key: row["state"] for key, row in states.items() if isinstance(row, dict) and isinstance(row.get("state"), str)}
def _kp_lords(node: Any) -> dict[str, Any]:
lords = node.get("kp_lords") if isinstance(node, dict) else None
return _pick(lords, ("sign", "rasi_lord", "nakshatra", "nakshatra_lord", "sub_lord", "sub_sub_lord"))
def _planet_extras(packet: dict, name: str) -> dict[str, Any]:
extra: dict[str, Any] = {"natural": "benefic" if name in NATURAL_BENEFICS else "malefic"}
owned = dig(packet, f"{FUNCTIONAL}.owned_houses.{name}")
if isinstance(owned, list) and owned:
extra["owns_houses"] = owned
degree = dig(packet, f"core_chart.planets.{name}.degree_in_sign")
if isinstance(degree, (int, float)) and not isinstance(degree, bool):
extra["d1_degree"] = round(float(degree), 2)
for key in ("nakshatra", "retrograde"):
value = dig(packet, f"core_chart.planets.{name}.{key}")
if value not in (None, ""):
extra[key] = value
avastha = _avastha(packet, name)
if avastha:
extra["avastha"] = avastha
vimsopaka = dig(packet, f"{VIMSOPAKA}.{name}")
if isinstance(vimsopaka, dict):
extra["vimsopaka"] = _pick(vimsopaka, ("total_score", "category"))
kp = _kp_lords(dig(packet, f"{KP}.planets.{name}"))
if kp:
extra["kp"] = kp
return extra
def _houses(view: dict, packet: dict) -> dict[str, Any]:
out = {}
for number in range(1, 13):
record = _compact(_house_record(view, number))
cusp = _kp_lords(dig(packet, f"{KP}.houses.{number}"))
if cusp:
record["kp_cusp"] = cusp
# BUG-1982: the same house id the chat card's evidence index gives (ev:house:D1:<n>).
out[str(number)] = {"evidence_id": house_id("D1", number), **record}
return out
def _unused_value(view: dict, item_id: str, minute_confirmed: bool) -> str | None:
if item_id in ("Vighati", "Pranapada") and not minute_confirmed:
return None
if path := UNUSED_POINT_PATHS.get(item_id):
value = dig(view, path)
if type(value) is int and 0 <= value < len(SIGN_ORDER):
return SIGN_ORDER[value]
return value if isinstance(value, str) and value else None
chart, _ = _varga_chart(view, item_id)
if isinstance(chart, dict):
return dig(chart, "Ascendant.sign") or dig(chart, "ascendant.sign")
return None
def _participation_axes(row: dict[str, Any], item: dict[str, Any], view: dict) -> dict[str, Any]:
state, item_id = row["state"], row["id"]
if item_id == "kp" and item.get("check") == "label":
# The participation label describes the method, even when no KP results were supplied.
if not (dig(view, f"{KP}.planets") or dig(view, f"{KP}.houses")):
return {"execution_status": "not_computed", "interpretation_usage": "not_used"}
if state == "executed" or "value" in row:
usage = "not_used"
if state == "executed":
usage = {"Badhaka": "supporting", "kp": "conditional"}.get(item_id, "primary")
# BUG-1955 (占星师 2026-11-17 Q5, follow-up of BUG-1954): Gulika / Maandi / Indu Lagna are
# auxiliary layers. They were read here as primary after the chat-side change.
if item.get("check") == "auxiliary":
usage = "supporting"
# BUG-1964: Vighati is kept for the record and takes no part (her item 1); the 64th
# Navamsa is a derived auxiliary layer (her item 2).
elif item.get("check") == "raw_only":
usage = "not_used"
elif item_id == "navamsa64":
usage = "supporting"
axes = technique_audit_axes({}, {"calculation_status": "executed", "interpretation_status": usage})
return {"execution_status": axes["calculation_status"], "interpretation_usage": axes["interpretation_status"]}
if item.get("status") == "not_applicable" and isinstance(item.get("reason"), str) and item["reason"].strip():
return {"execution_status": "not_applicable", "interpretation_usage": "not_used", "reason": item["reason"]}
raw_reason = item.get("blocked_reason") or item.get("reason_code") or item.get("status")
blocked_reason = (
"missing_input" if state == "withheld"
else PARTICIPATION_BLOCKED_REASONS.get(raw_reason)
or PARTICIPATION_BLOCKED_REASONS.get(row.get("reason_code"))
)
if blocked_reason:
return {"execution_status": "blocked", "interpretation_usage": "not_used", "blocked_reason": blocked_reason}
return {"execution_status": "not_computed", "interpretation_usage": "not_used"}
def _participation(rows: list[dict[str, Any]], domain: str, view: dict, minute_confirmed: bool) -> list[dict[str, Any]]:
"""Each technique's state for the domain; small values ride along."""
out = []
for item in rows:
if not isinstance(item, dict) or not isinstance(item.get("id"), str):
continue
status = item.get("status")
item_id = item["id"]
reason = None
if status == "blocked":
reason = PARTICIPATION_REASON_CODES.get((domain, item_id), "not_computed")
elif status != "value" and status != "withheld":
reason = "not_computed" # A packet leaf is absent. The card does not report an engine exception.
state = {"value": "executed", "withheld": "withheld"}.get(status, "blocked")
if reason in UNUSED_REASONS:
state = reason
row: dict[str, Any] = {"id": item_id, "state": state}
if isinstance(item.get("evidence_id"), str):
row["evidence_id"] = item["evidence_id"]
if reason is not None:
row["reason_code"] = reason
value = item.get("value")
if state == "executed" and isinstance(value, (str, int, float, bool)):
row["value"] = value
elif state == "executed" and item_id in STRUCTURED_VALUES and isinstance(value, dict):
# BUG-1853: Badhaka is a small record; the reading needs its positions, not just "executed".
row["value"] = {key: value[key] for key in STRUCTURED_VALUES[item_id] if value.get(key) not in (None, "", [])}
elif state == "executed" and item.get("check") in ("auxiliary", "raw_only", "derived") and isinstance(value, dict):
# The computed position with its record; the chat-only analysis note stays off the report.
# Position keeps the zodiac placement only: a key named `longitude` reads as a birth
# coordinate to the report's privacy check.
position = value.get("position")
if isinstance(position, dict):
position = {key: position[key] for key in ("sign", "sign_idx", "degree_in_sign", "sign_degree", "house")
if position.get(key) is not None}
row["value"] = {**{key: item for key, item in value.items() if key not in ("analysis_note", "position")},
**({"position": position} if position is not None else {})}
if state in UNUSED_REASONS and (value := _unused_value(view, item_id, minute_confirmed)) is not None:
row.update(computed=True, value=value)
if state == "withheld":
row["reason"] = PRECISION_SENTENCE
if isinstance(item.get("citation"), str):
row["source"] = item["citation"]
row.update(_participation_axes(row, item, view))
if row["execution_status"] == "not_computed":
row.pop("value", None)
out.append(row)
return out
def _domain_factors(row: dict) -> list[dict[str, Any]]:
factors = []
for factor in row.get("factors") or []:
if isinstance(factor, dict) and factor.get("kind") == "planet" and isinstance(factor.get("planet"), str):
factors.append({"role": factor.get("role"), "planet": factor["planet"]})
return factors
SIGN_ORDER = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio",
"Sagittarius", "Capricorn", "Aquarius", "Pisces")
def _dignity_zh(value: str) -> str | None:
chinese, opening, english = value.partition("(")
label = english.removesuffix(")") if opening else value
key = {"Friendly Sign": "Friend", "Enemy Sign": "Enemy"}.get(label, label)
entry = _VIMSOPAKA_DIGNITY.get(key)
if entry:
return entry[0]
return chinese if opening else None
def _varga_signs(view: dict, code: str, minute_confirmed: bool) -> Any:
"""The varga as the packet holds it: ascendant sign, each planet's sign and dignity.
A house the packet does not give is counted whole-sign from that varga's
own ascendant (``house_basis``); nothing else is derived.
"""
if code in PRECISION_VARGA and not minute_confirmed:
return PRECISION_SENTENCE
chart, chart_path = _varga_chart(view, code)
if not chart_path or not isinstance(chart, dict):
return None
ascendant = chart.get("Ascendant") if isinstance(chart.get("Ascendant"), dict) else chart.get("ascendant")
asc_sign = ascendant.get("sign") if isinstance(ascendant, dict) else None
out: dict[str, Any] = {"ascendant": asc_sign} if asc_sign else {}
dignities = chart.get("_dignity") if isinstance(chart.get("_dignity"), dict) else {}
for planet in PLANETS:
path = _varga_planet_path(chart_path, chart, planet)
node = dig(view, path) if path else None
if not isinstance(node, dict) or not node.get("sign"):
continue
row = {"sign": node["sign"]}
if code in HORA_VARGAS:
# BUG-1955 (占星师 2026-11-17 Q8): D2 is the two-Hora mapping; the reading material
# carries each planet's Hora, never a house counted in it.
hora = HORA_OF_SIGN.get(node["sign"])
if hora:
row["hora"] = hora
out["construction"] = "two_hora_sun_moon"
house = None
else:
house = node.get("house")
if not isinstance(house, int) and asc_sign in SIGN_ORDER and node["sign"] in SIGN_ORDER:
house = (SIGN_ORDER.index(node["sign"]) - SIGN_ORDER.index(asc_sign)) % 12 + 1
out["house_basis"] = "whole_sign_from_varga_ascendant"
if isinstance(house, int):
row["house"] = house
dignity = dignities.get(planet) or node.get("dignity")
if isinstance(dignity, str) and dignity:
row["dignity"] = dignity
row["dignity_zh"] = _dignity_zh(dignity)
out[planet] = row
return out
def _domain(row: dict, view: dict, shared: set[str], checked_houses: list[int]) -> dict[str, Any]:
primary = row["domain_varga"]
vargas = list(row.get("domain_vargas") or [primary])
varga_houses: dict[str, dict[str, Any]] = {}
for code in vargas:
houses = {}
for planet, record in row["planets"].items():
leaves = record.get("domain_varga_houses") or {}
if code in HORA_VARGAS:
leaves = record.get("domain_varga_horas") or {}
leaf = leaves.get(code) if code in leaves else (
record.get("domain_varga_hora" if code in HORA_VARGAS else "domain_varga_house") if code == primary else None)
house = _compact(leaf)
if house is not None:
houses[planet] = house
if houses:
varga_houses[code] = houses
items = [item for item in row["participation"] if item["id"] not in shared]
if not any(str(house) in row["houses"] for house in checked_houses):
items = [item for item in items if item["id"] != "double_transit"]
participation = _participation(items, row["domain"], view, row["minute_confirmed"])
states = {item["id"]: item["state"] for item in participation}
charts = {code: chart for code in vargas if (chart := _varga_signs(view, code, row["minute_confirmed"])) is not None}
for code, chart in charts.items():
if isinstance(chart, dict):
item_id = "D9_7" if row["domain"] == "marriage" and code == "D9" else code
chart["routed_for_domain"] = states.get(item_id) == "executed"
return {
"varga": primary,
"vargas": vargas,
"houses": _compact(row["houses"]),
"planets_in_varga": varga_houses.get(primary, {}),
"varga_charts": charts,
"significators": _domain_factors(row),
"participation": participation,
"not_executed": [item["id"] for item in participation if item["state"] != "executed"],
}
def _special_points(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
out: dict[str, Any] = {}
lagnas = dig(packet, LAGNAS)
if isinstance(lagnas, dict):
for key, node in lagnas.items():
if not isinstance(node, dict) or not node.get("sign"):
continue
if key in PRECISION_POINTS and not minute_confirmed:
out[key] = PRECISION_SENTENCE
continue
out[key] = _pick(node, ("sign", "house"))
if key in POINT_IDS and isinstance(node.get("sign"), str):
out[key] = {"evidence_id": point_id(POINT_IDS[key]), **out[key]}
padas = dig(packet, f"{JAIMINI}.arudha_padas.padas")
if isinstance(padas, dict):
out["arudha_padas"] = {
key: _pick(node, ("sign", "house_num", "lord"))
for key, node in sorted(padas.items())
if isinstance(node, dict) and node.get("sign")
}
return out
def _jaimini(packet: dict) -> dict[str, Any]:
out: dict[str, Any] = {}
for scheme, folder, key in (("7", "chara_karaka_7", "karaka_table"), ("8", "chara_karaka_8", "karaka_table_8")):
table = dig(packet, f"{JAIMINI}.{folder}.{key}")
if isinstance(table, dict):
out[f"karakas_{scheme}"] = {
role: node["planet"] for role, node in table.items()
if isinstance(node, dict) and isinstance(node.get("planet"), str)
}
karakamsha = dig(packet, f"{JAIMINI}.karakamsha")
if isinstance(karakamsha, dict):
out["karakamsha"] = _pick(karakamsha, ("karakamsha_sign", "karakamsha_lord"))
chara = dig(packet, f"{JAIMINI}.chara_dasha")
if isinstance(chara, dict):
out["chara_dasha"] = _pick(chara, ("method", "capability_status", "variant_profile", "variant_profile_status"))
return out
def _engine_yoga_rows(packet: dict) -> list[dict[str, Any]]:
advanced = dig(packet, "worksheets.advanced_systems.yoga")
if not isinstance(advanced, dict):
return []
rows = advanced.get("detected_yogas") or advanced.get("yogas") or []
return [row for row in rows if isinstance(row, dict)]
def _planet_names(value: Any) -> tuple[str, ...]:
if isinstance(value, (list, tuple, dict)):
return tuple(sorted(name for name in value if isinstance(name, str)))
return ()
def _engine_row_for(evidence: Any, engine_rows: list[dict[str, Any]]) -> dict[str, Any] | None:
"""The engine's own row for one table row, matched by rule id (and participants when a rule has several rows).
BUG-2106: the shared report table matches engine rows by English name, so two rules that share an English
name (amala_yoga / bvr_amala_precise, kalatra_dosha_mars_7 / kalatra_dosha_mars_1_4_7_8_12,
bvr_durumukha_precise / bvr_durmukha_yoga) printed each other's Chinese name in the model input.
"""
if not isinstance(evidence, dict) or not isinstance(evidence.get("rule_id"), str):
return None
same_rule = [row for row in engine_rows if row.get("rule_id") == evidence["rule_id"]]
if len(same_rule) > 1:
wanted = _planet_names(evidence.get("planets"))
for row in same_rule:
if _planet_names(row.get("planets")) == wanted:
return row
return same_rule[0] if same_rule else None
def _neecha_roles_fields(engine_row: dict[str, Any] | None, packet: dict, active: list[str]) -> dict[str, Any]:
"""The fallen planet and the cancellation witnesses as two roles, in the data chapters' own words (BUG-2106).
The facts are built before the report's interpretation step writes ``cancellation_witnesses`` on the
engine rows (pl9_interpretation_packs → attach_neecha_witness_roles), so the roles are read here the same
way, from the detector's executed conditions (占星师 2026-11-20 Q4: separate roles; a self-reference witness
is recorded, not independent support; one witness is one planet).
"""
from .neecha_witness import participant_cells
if engine_row is None:
return {}
cells = participant_cells(engine_row, active, "zh", dig(packet, "worksheets.advanced_systems.yogas_doshas"))
if cells is None:
return {}
roles = cells["roles"]
out: dict[str, Any] = {
"fallen_planets": list(roles["fallen"]),
"witnesses_returned": roles["witnesses_returned"],
}
if roles["witnesses_returned"]:
out["cancellation_witnesses"] = list(roles["witnesses"])
out["self_reference_witnesses"] = list(roles["self_reference_witnesses"])
# BUG-2151 (复测第二十九轮): the data chapters keep 「(自我参照,不作独立印证)」; the reading gets reader words.
out["witness_text_zh"] = f"化解条件的见证星:{cells['witness_cell']}".replace(SELF_REFERENCE_DATA_ZH, SELF_REFERENCE_READER_ZH)
if cells["witness_status"]:
out["current_lord_witness_text_zh"] = cells["witness_status"]
return out
def _active_lords(packet: dict) -> list[str]:
current = dig(packet, DASHA)
if not isinstance(current, dict):
return []
lords = [current.get("lord")]
for key in ("antardasha_timeline", "pratyantardasha_timeline"):
rows = current.get(key) if isinstance(current.get(key), list) else []
lords += [row.get("lord") for row in rows if isinstance(row, dict) and row.get("is_current") is True]
return [name for name in dict.fromkeys(lords) if isinstance(name, str)]
def _yogas(packet: dict) -> list[dict[str, Any]]:
from .neecha_witness import is_neecha_bhanga_row
from .yoga_status_words import report_yoga_table, yoga_status
layer, rows, _observations = report_yoga_table(packet)
if layer["status"] != "executed":
return []
engine_rows = _engine_yoga_rows(packet)
active = _active_lords(packet)
out = []
for evidence, row in rows:
state, state_text = yoga_status(evidence)
engine_row = _engine_row_for(evidence, engine_rows)
entry = {
**({"evidence_id": yoga_id(evidence["rule_id"], obj=evidence.get("instance_object")
if isinstance(evidence.get("instance_object"), str) else None)}
if isinstance(evidence, dict) and isinstance(evidence.get("rule_id"), str) else {}),
**_pick(row, ("name", "name_cn", "category", "source", "planets")),
**({"conditions": row["combination"]} if row.get("combination") else {}),
**({"detector_strength": row["strength"]} if row.get("strength") else {}),
"state": state,
"state_text": state_text,
}
# BUG-2106: each rule's own Chinese name, by rule id.
if engine_row is not None and isinstance(engine_row.get("name_cn"), str) and engine_row["name_cn"].strip():
entry["name_cn"] = engine_row["name_cn"]
if is_neecha_bhanga_row(evidence if isinstance(evidence, dict) else row):
entry.update(_neecha_roles_fields(engine_row, packet, active))
if isinstance(row.get("same_fact"), list) and row["same_fact"]:
entry["same_fact"] = _same_fact_block(evidence, row, engine_rows)
out.append(entry)
return out
_LATIN_PLANET_AFTER_HAN = re.compile(r"(?<=[\u4e00-\u9fff])(?:Sun|Moon|Mars|Mercury|Jupiter|Venus|Saturn|Rahu|Ketu)(?![A-Za-z])")
def _own_rule_condition(engine_row: dict[str, Any] | None, row: dict[str, Any]) -> str | None:
"""Each merged rule's own condition (BUG-2113 follow-up, jyotisha-32's BUG-2110 rule_condition_text).
The shared report function only knows in_houses definitions and otherwise returns a gap line; that line is
never written into the facts, so the rule falls back to the shared fact (the row's combination).
"""
for source in (engine_row, row):
if isinstance(source, dict):
text = rule_condition_text(source, "zh")
if isinstance(text, str) and text.strip() and text != _RULE_CONDITION_GAP_ZH:
return text
combination = row.get("combination")
return combination if isinstance(combination, str) else None
def _same_fact_rule(evidence: Any, row: dict[str, Any], engine_rows: list[dict[str, Any]]) -> dict[str, Any]:
engine_row = _engine_row_for(evidence, engine_rows) if isinstance(evidence, dict) else None
name_cn = engine_row.get("name_cn") if engine_row is not None else None
if not (isinstance(name_cn, str) and name_cn.strip()):
name_cn = row.get("name_cn") if isinstance(row.get("name_cn"), str) else None
effects = row.get("effects")
return _compact({
"rule_id": row.get("rule_id") if isinstance(row.get("rule_id"), str) else None,
"name": row.get("name") if isinstance(row.get("name"), str) else None,
"name_cn": name_cn,
"conditions": _own_rule_condition(engine_row, row),
"effects_zh": [item for item in effects if isinstance(item, str) and item.strip()]
if isinstance(effects, list) else None,
})
def _same_fact_block(evidence: Any, row: dict[str, Any], engine_rows: list[dict[str, Any]]) -> dict[str, Any]:
"""Rules that hit one chart fact: one fact, each rule's own meaning kept (占星师 2026-11-21, BUG-2113).
The shared report table folds such rules into the first one (``display["same_fact"]``, BUG-2089). The
facts carry all of them under the kept row's evidence id: the merged rules get no id of their own, so a
reading cannot cite them as extra support and nothing downstream counts the fact twice.
"""
rules = [_same_fact_rule(evidence, row, engine_rows)]
for other in row["same_fact"]:
if isinstance(other, dict):
rules.append(_same_fact_rule(other, other, engine_rows))
fact = row.get("combination") if isinstance(row.get("combination"), str) else ""
fact = _LATIN_PLANET_AFTER_HAN.sub("", fact).strip()
names = [rule.get("name_cn") or rule.get("name") for rule in rules]
return _compact({
"counts_as": "one_fact",
"shared_fact_zh": fact or None,
"rules": rules,
"text_zh": (f"共同的星盘事实:{fact}。" if fact else "")
+ "这几条规则说的是同一个事实(" + "/".join(name for name in names if name)
+ "),只算一个事实;各条规则的含义分别保留,引用时用这一行的 evidence_id。",
})
def _saturn_sign_end(key_dates: list[dict], out: dict) -> dict[str, Any] | None:
"""When transit Saturn leaves its current sign, from the same ingress records; None without one."""
sign = dig(out, "planets.Saturn.sign")
day = out.get("target_date")
if not isinstance(sign, str) or not isinstance(day, str):
return None
rows = sorted(
(row for row in key_dates
if row.get("kind") == "ingress" and str(row.get("body")).lower() == "saturn"
and isinstance(row.get("date"), str) and row["date"] > day),
key=lambda row: row["date"],
)
return {"end": rows[0]["date"]} if rows and rows[0].get("from_sign") == sign else None
def _transits(packet: dict, full_reading: dict | None = None) -> dict[str, Any]:
out: dict[str, Any] = {}
positions = dig(packet, TRANSIT)
if isinstance(positions, dict):
out.update(_pick(positions, ("target_date", "ayanamsa", "node_mode")))
planets = positions.get("planets") if isinstance(positions.get("planets"), dict) else {}
out["planets"] = {}
for name in PLANETS:
node = planets.get(name)
if not isinstance(node, dict):
continue
row = _pick(node, ("sign", "retrograde"))
if isinstance(node.get("sign"), str) and isinstance(positions.get("target_date"), str):
row = {"evidence_id": transit_id(name), **row}
if isinstance(node.get("degree_in_sign"), (int, float)):
row["degree_in_sign"] = round(float(node["degree_in_sign"]), 2)
houses = dig(packet, f"{TRANSIT_REF}.transit_analysis.{name}.house_from_ref")
if isinstance(houses, dict):
row["house_from"] = houses
out["planets"][name] = row
divergences = dig(packet, f"{TRANSIT_REF}.divergences")
if isinstance(divergences, list):
out["reference_divergences"] = [
_pick(row, ("planet", "houses")) for row in divergences
if isinstance(row, dict) and row.get("planet") in SLOW_TRANSITS
]
# BUG-2021: Saturn / Jupiter back in their natal sign, the fact the chat card has had since BUG-1995.
# Signs are the packet's; the dates of the visit are existing ingress records (see transit_natal_sign.py).
key_dates = slow_transit_key_dates(packet, full_reading or {}, out.get("target_date"))
returns = transit_natal_sign_facts(
dig(packet, "core_chart.planets"), out.get("planets"), key_dates, out.get("target_date"),
)
# BUG-2038 原值:两颗星各一行,same_sign 为 false 的也给。新值:只给回到本命星座的行。
# 原因:复测第九轮正文写出「行运木星从出生时的摩羯座走到狮子座,不在同一个星座」这种没有内容的话;
# 问答的关键事实行同样只列 same_sign 为 true 的(BUG-2006)。`returns` 仍完整,用于下面取土星离开日期。
back = [row for row in returns if row.get("same_sign") is True]
if back:
out["transit_natal_sign"] = back
sade = dig(packet, SADE_SATI)
if isinstance(sade, dict):
out["sade_sati"] = _pick(sade, ("is_active", "phase", "moon_sign", "phases"))
# BUG-2021: 「Sade Sati 未启动」 read alone as "no Saturn pressure" while the chat described Saturn
# in the 7th from the Moon. The same block now names Saturn's house from the Moon (the packet's
# own count) and whether that house is Kantaka or Ashtama Shani under her 2026-11-16 ruling.
house = dig(packet, f"{TRANSIT_REF}.transit_analysis.Saturn.house_from_ref.Chandra_Lagna.house")
saturn_row = next((row for row in returns if row["planet"] == "Saturn"), None)
if saturn_row is None or saturn_row.get("end") in (None, "not_available"):
# Saturn is not in its natal sign: the leave date of its current sign is the same ingress record.
saturn_row = _saturn_sign_end(key_dates, out)
from_moon = saturn_from_moon(house, saturn_row)
if from_moon:
out["sade_sati"]["saturn_from_moon"] = from_moon
out["sade_sati"]["scope"] = SADE_SATI_SCOPE_ZH
# BUG-2024: the finished fact sentence; the rules only say to use it.
summary = sade_sati_summary_zh(out["sade_sati"].get("is_active"), from_moon)
if summary:
out["sade_sati"]["summary_zh"] = summary
double = dig(packet, DOUBLE_TRANSIT)
if isinstance(double, dict):
event_house = double.get("event_house")
out["double_transit"] = {
**_pick(double, ("status", "summary", "event_house", "transit_date", "claim_boundary")),
"checked_houses": [event_house] if type(event_house) is int and 1 <= event_house <= 12 else [],
"scope": "Only the listed houses were checked. This does not indicate activation of other houses or domains.",
"hits": [
_pick(row, ("layer", "target", "strength"))
for row in (double.get("double_transit") or []) if isinstance(row, dict)
][:8],
}
return out
def _annual(packet: dict) -> dict[str, Any]:
pack = dig(packet, ANNUAL)
out: dict[str, Any] = {} if isinstance(pack, dict) else {"status": "blocked"}
target = dig(pack, "profile.target_year")
if target is not None:
out["target_year"] = target
muntha = dig(pack, "muntha.data")
if isinstance(muntha, dict):
out["muntha"] = {**_pick(muntha, ("muntha_sign", "muntha_lord")), **_pick(pack.get("muntha"), ("status",))}
year_lord = dig(pack, "year_lord.data")
if isinstance(year_lord, dict):
out["year_lord"] = {
**_pick(year_lord, ("year_lord", "year_lord_sign", "year_lord_house", "annual_asc_sign")),
**_pick(pack.get("year_lord"), ("status",)),
}
periods = dig(pack, "mudda_dasha.periods")
mudda = dig(pack, "mudda_dasha.data")
mudda = mudda if isinstance(mudda, dict) else {}
moon_source = mudda.get("moon_source")
if moon_source is None:
moon_source = {
"moon_at_birth_time": "natal", "moon_in_varshaphala": "varshaphala",
}.get(mudda.get("balance_profile"))
out["mudda_dasha"] = {
"moon_source": moon_source,
"balance_method": mudda.get("balance_method"),
"periods": [
{**_pick(row, ("lord",)), **{key: _day(row.get(key)) for key in ("start", "end") if _day(row.get(key))}}
for row in (periods if isinstance(periods, list) else []) if isinstance(row, dict)
],
}
return out
def _clean_note(note: Any) -> str:
text = str(note or "")
return text if len(text) <= NOTE_LIMIT else text[:NOTE_LIMIT] + "…"
def _evidence(packet: dict) -> dict[str, Any]:
from .technique_status_axes import technique_audit_axes
audit = packet.get("technique_audit_table") if isinstance(packet.get("technique_audit_table"), list) else []
ledger = dig(packet, LEDGER)
summary = ledger.get("summary") if isinstance(ledger, dict) and isinstance(ledger.get("summary"), dict) else {}
gate = packet.get("report_quality_gate") if isinstance(packet.get("report_quality_gate"), dict) else {}
return {
"technique_audit": [
{**technique_audit_axes(packet, row), "technique": row.get("technique"),
"status": row.get("status"), "note": _clean_note(row.get("note"))}
for row in audit if isinstance(row, dict) and row.get("technique")
],
"d1_d60_ledger": {
**_pick(ledger, ("status",)),
**_pick(summary, ("formal_traditional_division_count", "research_generic_dn_division_count")),
"boundary": "D-N research rows are raw data only; they cannot carry a thematic conclusion.",
},
**({"report_quality_gate": gate.get("status")} if gate.get("status") else {}),
# Where each layer lives in the report's own packet (evidence paths).
"evidence_paths": {
"functional": FUNCTIONAL,
"vimshottari": DASHA,
"narayana": NARAYANA,
"dasha_families": FAMILIES,
"transits": TRANSIT,
"transit_references": TRANSIT_REF,
"double_transit": DOUBLE_TRANSIT,
"ashtakavarga": ASHTAKAVARGA,
"shadbala": "worksheets.strengths_and_scores.shadbala",
"kp": KP,
"jaimini": JAIMINI,
"yogas": f"{YOGA}.yogas",
"annual": ANNUAL,
"d1_d60_ledger": LEDGER,
"technique_audit": "technique_audit_table",
},
}
def _method_differences(packet: dict, narayana: dict, functional: dict, transits: dict) -> list[dict[str, Any]]:
"""Places where two methods or two parameters give different answers."""
out: list[dict[str, Any]] = []
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
kp_profile = dig(packet, f"{KP}.kp_profile")
if isinstance(kp_profile, dict) and kp_profile.get("house_system") != profile.get("house_system"):
out.append({
"topic": "kp_vs_parashari_houses",
"parashari": _pick(profile, ("ayanamsa", "house_system")),
"kp": _pick(kp_profile, ("ayanamsa", "house_system", "status")),
"note": "KP cusps (Placidus, KP ayanamsa) can put a planet in a different house than whole-sign houses.",
})
legacy = dig(narayana, "legacy_comparison.mahadasha")
current = narayana.get("mahadasha")
if isinstance(legacy, dict) and isinstance(current, dict) and legacy.get("sign") != current.get("sign"):
out.append({"topic": "narayana_variant", "default": current, "legacy": legacy})
for row in functional.get("natural_vs_functional_conflicts") or []:
out.append({"topic": "natural_vs_functional", **row})
for row in transits.get("reference_divergences") or []:
out.append({"topic": "transit_reference_points", **row})
if dig(packet, "worksheets.strengths_and_scores.shadbala") not in (None, {}, []):
out.append({
"topic": "shadbala_components",
"note": "Shadbala follows the component method the astrologer chose; other software can flip whether a planet meets its minimum.",
})
return out
def _blocked_states(
domains: dict, shared: list[dict], families: list[dict], evidence: dict, transits: dict, annual: dict,
) -> dict[str, Any]:
labels: dict[str, list[str]] = {
"blocked": [], "not_routed": [], "not_in_domain_route": [],
"parameter_sensitive": [], "not_applicable": [], "withheld": [], "not_computed": [],
}
for name, row in domains.items():
for item in [*(row.get("participation") or []), *(shared if name == "general" else [])]:
identity = f"{name}:{item['id']}"
if item["state"] in UNUSED_REASONS or item["state"] == "withheld":
labels[item["state"]].append(identity)
if item["execution_status"] in ("blocked", "not_applicable", "not_computed"):
labels[item["execution_status"]].append(identity)
for family in families:
status = str(family.get("status") or "")
if status in BLOCKED_STATES:
labels["blocked"].append(f"dasha:{family['family']}")
elif status == "not_applicable":
labels["not_applicable"].append(f"dasha:{family['family']}")
elif status in CONDITIONAL_STATES:
labels["parameter_sensitive"].append(f"dasha:{family['family']}")
for row in evidence.get("technique_audit") or []:
status = str(row.get("status") or "")
if status in BLOCKED_STATES:
labels["blocked"].append(f"audit:{row['technique']}")
elif status in CONDITIONAL_STATES:
labels["parameter_sensitive"].append(f"audit:{row['technique']}")
if not transits.get("planets"):
labels["blocked"].append("transits")
if not dig(transits, "double_transit.checked_houses"):
labels["blocked"].append("general:double_transit")
if annual.get("status") == "blocked":
labels["blocked"].append("annual")
labels["parameter_sensitive"].append("kp")
return {key: value for key, value in labels.items() if value or key in UNUSED_REASONS}
def _birth_parameters(packet: dict, minute_confirmed: bool) -> dict[str, Any]:
"""The chart's calculation inputs. No name and no coordinates."""
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
return {
**_pick(birth, ("date", "time", "tz")),
**_pick(profile, ("ayanamsa", "node_mode", "house_system", "position_mode", "dasha_year_days")),
"minute_confirmed": minute_confirmed,
}
def _birth_precision(full_reading: dict, view: dict, domains: dict, minute_confirmed: bool, window: object = None) -> dict[str, Any]:
divisions = {1}
for domain in domains.values():
divisions.update(int(code[1:]) for code, chart in domain["varga_charts"].items() if isinstance(chart, dict))
# D60 is referenced by the facts' D1–D60 ledger. Keep the existing precision gate.
if minute_confirmed and _varga_chart(view, "D60")[1]:
divisions.add(60)
birth = dig(full_reading, "modules.chart.birth_info") or {}
tolerance = report_birth_window(window, minute_confirmed=minute_confirmed)
return {
"minute_confirmed": minute_confirmed,
"purpose_stability": (
DEFAULT_WINDOW_SCENARIO if tolerance["source"] == DEFAULT_WINDOW_SOURCE else "not_evaluated"
),
"basis": "The purpose-specific interval contract (2026-11-09 interval_rectification handoff) is not integrated.",
"window": {**tolerance, "label_zh": birth_window_label_zh(tolerance)},
"ascendant_margins": ascendant_margins(birth, divisions, window=tolerance),
}
# BUG-2024 (占星师 2026-11-19 第 3 条): the engine's dignity label for a debilitated planet whose
# cancellation rule holds, and the wording the reading is given for it. Same two strings as the chat
# card's NEECHA_BHANGA_ENGINE_LABEL / NEECHA_BHANGA_CARD_LABEL (frontend/src/lib/consultation-evidence-card.ts,
# BUG-2020); tests/test_report_wording_2024.py pins them to that file. The bare 「落陷取消」 read as
# "the debilitation is gone".
# BUG-2151: the self-reference witness note in the data chapters, and the reading's reader words for it.
SELF_REFERENCE_DATA_ZH = "(自我参照,不作独立印证)"
SELF_REFERENCE_READER_ZH = "(这一条以它自己为起点,不另算一条支持)"
NEECHA_BHANGA_ENGINE_LABEL = "落陷取消(Neecha Bhanga)"
# BUG-2030 原值「落陷,落陷取消条件已满足(不等于入旺,也不代表相关困难全部消失)」/ 新值:她 11-19 第二次答复给用户的说法 /
# 原因:分层规则,规则口吻留在后台;与问答卡 NEECHA_BHANGA_CARD_LABEL 保持同一句(report-wording-2024.test.ts)。
# BUG-2163 原值「落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失」/ 新值:她 11-22 §4(E)的短写法加该行的
# 边界「不代表困难全部消失」/ 原因:表格与正文按真实状态分开写(BUG-2155 neecha_witness.NEECHA_SHORT_CELL);引擎标签
# 「落陷取消(Neecha Bhanga)」是默认规则成立,即「已核」。只有另一种读法成立(待核)时写「缓解条件待核」,未计算或只有自我参照
# 时只写「落陷」,不说有缓解。
NEECHA_BHANGA_READER_ZH = "落陷;另有缓解条件,不代表困难全部消失"
NEECHA_CANDIDATE_READER_ZH = "落陷;缓解条件待核"
_DIGNITY_FIELDS = ("d1_dignity", "d9_dignity", "dignity", "status")
_DEBILITATED = frozenset({"落陷(Debilitated)", "落陷", "DEBILITATED", "Debilitated"})
def _neecha_bhanga_reader_label(value: Any, key: str | None = None, states: dict | None = None) -> Any:
"""Every place the facts repeat the engine label (planet rows, lords, yoga participants).
``states`` (``neecha_witness.neecha_states``) turns a planet row keyed by its planet name into the
candidate wording when only another named reading's condition holds (BUG-2163).
"""
states = states or {}
if isinstance(value, dict):
out = {name: _neecha_bhanga_reader_label(item, name, states) for name, item in value.items()}
candidate = states.get(key) == "candidate"
for field in _DIGNITY_FIELDS:
raw = value.get(field)
if raw == NEECHA_BHANGA_ENGINE_LABEL:
label = NEECHA_CANDIDATE_READER_ZH if candidate else NEECHA_BHANGA_READER_ZH
out[field] = label
elif candidate and raw in _DEBILITATED:
label = NEECHA_CANDIDATE_READER_ZH
else:
continue
if f"{field}_zh" in out:
out[f"{field}_zh"] = label
return out
if isinstance(value, list):
return [_neecha_bhanga_reader_label(item, key, states) for item in value]
return NEECHA_BHANGA_READER_ZH if value == NEECHA_BHANGA_ENGINE_LABEL else value
_CONNECTION_PATH_ZH = {
"direct": "直接(是这一宫的宫主,或落在这一宫)",
"same_sign_or_aspect": "同星座或相位",
"sign_exchange": "互换星座",
"dispositor_chain": "定位链(宫主所在星座的主星,一步步往下找)",
"topic_varga": "这一宫的主题分盘",
}
_CONNECTION_LEVEL_ZH = {"md": "大运", "ad": "小运", "pd": "细运"}
_CONNECTION_PD_REASON_ZH = {
# BUG-2151 原值「出生时间没有确认到分钟,细运不用」/ 新值见下 / 原因:生时纠正选定的区间也走这条,读成「没确认」不对。
# 旧报告存下的结构仍带这个码(BUG-2157 起引擎不再产生)。
"birth_time_not_minute_confirmed": "细运的起止会随出生时间前后移动,这一层不用",
# BUG-2163(占星师 2026-11-22 §6.2,G1):细运按出生时间范围内是否稳定来用,不按「确认到分钟」开关。
"pd_range_split": "出生时间范围内的不同时刻落在不同的细运,这一层分开并列,不单独下结论",
"pd_stability_not_assessed": "这次没有评估细运在出生时间范围内是否稳定,这一层不用",
"no_current_pd": "当前细运没有随报告返回",
}
_CONNECTION_REASON_ZH = {
"no_current_dasha": "当前大运没有随报告返回",
"house_lord_missing": "宫主或宫主位置没有随报告返回",
# BUG-2163(§6.3,G2):截断是没算完,不是「没有联系」。
"chain_truncated": "定位链超过计算上限,没有算完",
"chain_missing": "定位链没有随报告返回",
"varga_missing": "主题分盘没有随报告返回",
}
_CONNECTION_USE_RULE = (
"这是一份索引:当前这段时间的主星和各个宫(生活领域)通过哪条路径有联系,路径分开记录。"
"它不是「这件事被激活了」的判定,不计票,路径多不等于证据更强,也不用来提高把握;"
"正文用日常话说这件事和这段时间主导的星有联系,路径名称只在「依据与边界」里写并加白话解释。"
# BUG-2163(§6.3 / §6.4):没算完、没评估不等于查明没有。
"没有列出的宫、没有算完的定位链、尚未评估的主题分盘,都不写成「没有联系」或「不成立」。"
)
def _period_connections(working: dict) -> dict[str, Any] | None:
"""The current period lords' connection paths to each house (BUG-2126, jyotisha-20's BUG-2121).
占星师 2026-11-20 第 1 问: the five paths stay apart and never become one true/false; the table is an
index, not an activation verdict or a vote. Only matched paths are carried (each with its own lords,
levels and one plain fact line); a house whose every path is undetermined carries its reason. Built
with ``attach_indirect_activation`` (computes and stores it when the data chapters were not rendered).
"""
try:
structure = attach_indirect_activation(working)
except Exception: # noqa: BLE001 - an index the reading can do without; never break the facts
return None
if not isinstance(structure, dict) or not structure.get("schema"):
return None
lords = [
_compact({"level": item.get("level"), "level_zh": _CONNECTION_LEVEL_ZH.get(str(item.get("level"))),
"lord": item.get("lord"), "start": item.get("start"), "end": item.get("end")})
for item in structure.get("period_lords") or [] if isinstance(item, dict)
]
pd = structure.get("pd") if isinstance(structure.get("pd"), dict) else {}
houses: dict[str, Any] = {}
undetermined: dict[str, str] = {}
for key, row in (structure.get("houses") or {}).items():
if not isinstance(row, dict):
continue
paths = row.get("paths") if isinstance(row.get("paths"), dict) else {}
matched = []
for name in CONNECTION_PATHS:
path = paths.get(name) if isinstance(paths.get(name), dict) else {}
if path.get("status") != "matched":
continue
hit_lords: dict[str, list[str]] = {}
for hit in path.get("hits") or []:
if isinstance(hit, dict) and isinstance(hit.get("lord"), str):
levels = hit_lords.setdefault(hit["lord"], [])
levels.extend(level for level in hit.get("levels") or [] if level not in levels)
matched.append({
# BUG-2126 follow-up: "route", not "path" — the facts never carry a "path" key
# (test_reading_facts_are_packet_leaves keeps internal leaf paths out of the model input).
"route": name,
"route_zh": _CONNECTION_PATH_ZH.get(name, name),
"lords": [{"lord": lord, "levels": levels} for lord, levels in hit_lords.items()],
"text_zh": path_cell(path, "zh"),
})
if matched:
houses[str(key)] = {"house_lord": row.get("lord"), "paths": matched}
elif (assessed := [p for p in paths.values() if isinstance(p, dict) and p.get("status") != "not_assessed"]) and all(
p.get("status") == "not_determined" for p in assessed):
# BUG-2163: a topic chart that was not assessed (BUG-2157 status not_assessed) does not keep a
# house whose other paths are all undetermined out of this list.
reasons = {str(p.get("reason")) for p in assessed}
reason = next(iter(reasons)) if len(reasons) == 1 else "mixed"
undetermined[str(key)] = _CONNECTION_REASON_ZH.get(reason, "没有判定")
return _compact({
"status": structure.get("status"),
"use_rule": _CONNECTION_USE_RULE,
"period_lords": lords,
"pd_used": bool(pd.get("used")),
"pd_reason_zh": _CONNECTION_PD_REASON_ZH.get(str(pd.get("reason"))) if pd.get("reason") else None,
"houses": houses or None,
"undetermined_houses": undetermined or None,
})
def build_report_reading_facts(
packet: dict,
full_reading: dict,
*,
minute_confirmed: bool,
today: str | None = None,
report_mode: str = "living_consultation",
subject_life_status: str = "unknown",
birth_time_window: object = None,
gender: str | None = None,
birth_input_revision: str | None = None,
subject_ref: str | None = None,
) -> dict[str, Any]:
"""Packet-sourced facts for the reading. Raises on any non-packet consult leaf."""
if report_mode not in ("living_consultation", "historical_replay"):
raise ValueError("unsupported report_mode")
if subject_life_status not in ("living", "deceased", "unknown"):
raise ValueError("unsupported subject_life_status")
if subject_life_status == "deceased" and report_mode == "living_consultation":
raise ValueError("a deceased subject requires historical_replay")
working = _attach_graha_drishti(copy.deepcopy(packet), full_reading)
# BUG-2106 follow-up: store Narayana's second direction reading even when the data chapters were
# not rendered first (the renderer stores it too, BUG-2107; idempotent, writes one key).
ensure_narayana_report_extras(working)
# One detached copy of the packet serves every domain's facts and their leaf check (issue #122).
base = full_data_domain_base(working)
# BUG-1976: the same evidence ids and snapshot id the chat card reads (consult_facts/evidence_ids.py).
from .yoga_status_words import report_yoga_conditions
yoga_layer = report_yoga_conditions(working) if YOGA_LAYER_FOR_IDS else None
reference_for_ids = str(today)[:10] if today else None
raw = build_consult_card_facts(working, list(READING_DOMAINS), minute_confirmed=minute_confirmed, base=base,
yoga_layer=yoga_layer, reference_date=reference_for_ids,
birth_input_revision=birth_input_revision, subject_ref=subject_ref)
rows = {row["domain"]: row for row in raw["domains"]}
for row in rows.values():
assert_fact_leaves(working, row, base=base)
general = rows["general"]
evidence_base = raw.get("evidence_base") or {}
d1_ids = {item["entity"]: item["evidence_id"] for item in evidence_base.get("items") or []
if item.get("kind") == "placement" and item.get("chart_layer") == "D1"}
planets = {}
for name, record in general["planets"].items():
kept = _compact({key: value for key, value in record.items() if key not in ("domain_varga_house", "domain_varga_houses", "domain_varga_hora", "domain_varga_horas")})
if kept.get("present"):
kept.pop("present")
for key in ("d1_dignity", "d9_dignity"):
if isinstance(kept.get(key), str):
kept[f"{key}_zh"] = _dignity_zh(kept[key])
planets[name] = {**kept, **_planet_extras(working, name)}
if name in d1_ids:
planets[name] = {"evidence_id": d1_ids[name], **planets[name]}
ids = [{item.get("id") for item in row.get("participation") or []} for row in rows.values()]
shared = set.intersection(*ids) - {"double_transit"}
view = read_full_data_domain(working, "general", base=base)
shared_rows = _participation(
[item for item in general["participation"] if item["id"] in shared], "general", view, minute_confirmed,
)
transits = _transits(working, full_reading)
checked_houses = dig(transits, "double_transit.checked_houses") or []
domains = {name: _domain(row, view, shared, checked_houses) for name, row in rows.items()}
ascendant = dig(packet, "core_chart.ascendant")
reference_day = str(today or dig(packet, f"{TRANSIT}.target_date") or date.today().isoformat())[:10]
narayana = _narayana(working)
functional = _functional(working)
families = [
row for row in _dasha_families(working, reference_day)
# The dated Narayana is in `timing`; the master pack's copy is not run.
if not (row["family"] == "narayana" and narayana.get("mahadasha"))
]
annual = _annual(working)
evidence = _evidence(working)
sav = dig(working, f"{ASHTAKAVARGA}.sav")
shadbala = dig(working, "worksheets.strengths_and_scores.shadbala.planets")
facts = {
"schema": READING_FACTS_SCHEMA,
# BUG-1976: the calculation snapshot (birth input revision, date, rule versions) the ids belong to.
"snapshot_id": evidence_base.get("snapshot_id"),
"minute_confirmed": minute_confirmed,
"report_mode": report_mode,
"subject_life_status": subject_life_status,
"subject": {"gender": gender if gender in ("female", "male") else "unknown"},
"current_advice_allowed": report_mode == "living_consultation",
"observation_date": today or reference_day,
"birth_parameters": _birth_parameters(working, minute_confirmed),
"birth_precision": _birth_precision(full_reading, view, domains, minute_confirmed, birth_time_window),
"ascendant": _compact({
key: {"status": "value", "check": "path", "value": ascendant.get(key)}
for key in ("sign", "lord", "nakshatra", "degree_in_sign")
if isinstance(ascendant, dict) and ascendant.get(key) is not None
}),
"functional": functional,
"planets": planets,
"houses": _houses(view, working),
# Techniques every domain runs (shadbala, aspects, dashas, transits …), listed once.
"shared_techniques": shared_rows,
"domains": domains,
"special_points": _special_points(working, minute_confirmed),
"jaimini": _jaimini(working),
"yogas": _yogas(working),
"timing": {**_compact(general["timing"]), **_vimshottari(working), "narayana": narayana,
**({"period_connections": connections} if (connections := _period_connections(working)) else {})},
"dasha_families": families,
"transits": transits,
"strengths": {
"shadbala": {
planet: {"evidence_id": shadbala_id(planet),
"minimum_check_status": row.get("minimum_check_status"),
"meets_minimum": row_fields(row)["meets_minimum"]}
for planet, row in (shadbala if isinstance(shadbala, dict) else {}).items()
if isinstance(row, dict)
},
"ashtakavarga_sav": _pick(sav, ("total", "expected_total", "valid")),
"vimsopaka_total": _pick(dig(working, VIMSOPAKA), ("total_score", "total_score_max", "status")),
},
"kp": {
"profile": _pick(dig(working, f"{KP}.kp_profile"), ("ayanamsa", "house_system", "cusp_source", "status")),
"state": "parameter_sensitive",
},
"annual": annual,
"evidence": evidence,
"method_differences": _method_differences(working, narayana, functional, transits),
"blocked_states": _blocked_states(domains, shared_rows, families, evidence, transits, annual),
}
# Astrologer 2026-11-12 Q3-2: the backend fixes each claim type's grade ceiling.
facts["evidence_grades"] = evidence_grades(facts)
return _strip_internal_issue_references(_neecha_bhanga_reader_label(facts, None, _neecha_states(working)))