fix(yoga): her detect status layer — effect_assessment and method_review gates, row status fields, shared-lordship dependencies, blocked rows kept apart from yogas (BUG-2299)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
This commit is contained in:
2026-11-24 13:06:24 +08:00
co-authored by Claude Opus 5.5
parent 1810cd7957
commit 9f5158c15d
6 changed files with 292 additions and 24 deletions
+179 -6
View File
@@ -279,12 +279,14 @@ try: # scripts/ on sys.path
_formation_logic as _upstream_formation_logic,
assess_yoga_formation as _upstream_assess_yoga_formation,
)
from report_render.yoga_english_delivery import english_delivery_fields
except ImportError: # package import (scripts.yoga_engine)
from scripts.report_render.yoga_output_guardrails import ( # noqa: F401 - re-exported
yoga_formation_contract,
_formation_logic as _upstream_formation_logic,
assess_yoga_formation as _upstream_assess_yoga_formation,
)
from scripts.report_render.yoga_english_delivery import english_delivery_fields
def _formation_logic(value: Any) -> Any:
@@ -941,6 +943,127 @@ class MissingYogaInput(YogaRuleEvaluationError):
super().__init__("MissingYogaInput", field)
# BUG-2299 (upstream 58f37ee5b `detect`): the five effect statuses her source evaluators
# return; each keeps the structure and source but no traditional verdict as a personal result.
EFFECT_QUALIFICATIONS = {
'source_neutralized': ('木星照射的缓解条件已满足;不据月土同宫判定言语性格。',
'The source-neutralizing Jupiter aspect is present; do not infer a speech trait from the conjunction.'),
'incomplete': ('影响表现的条件资料不全;结构记录不等于个人结论。',
'Expression qualifiers have missing inputs; the structural match is not a personal conclusion.'),
'historical_medical_reference': ('仅保留传统结构,不据此判断疾病、伤残或治疗结果。',
'Historical structure only; no diagnosis, disability or treatment outcome is inferred.'),
'historical_injury_reference': ('仅保留传统结构,不据此判断战争、伤害或死亡事件。',
'Historical structure only; no war, injury or death event is established.'),
'historical_conduct_reference': ('仅保留传统结构,不能据此认定本人或伴侣不忠。',
'Historical structure only; no infidelity or personal conduct is established.'),
}
GATED_EFFECT_STATUSES = frozenset(EFFECT_QUALIFICATIONS)
def _withhold_effects(entry: Dict) -> None:
"""Move the traditional effects (both languages) aside; the row states no verdict."""
entry.setdefault('traditional_effects', entry.get('effects') or [])
entry['effects'] = []
if entry.get('effects_en'):
entry.setdefault('traditional_effects_en', entry['effects_en'])
entry['effects_en'] = []
entry['strength'] = 'conditional'
entry['strength_en'] = 'Conditional'
def _apply_effect_and_method_gates(entry: Dict, rule: Dict, match: Dict) -> None:
"""Her `effect_assessment` and `method_review` gates, then her row status fields.
BUG-2299 (upstream 58f37ee5b `detect`). Was: neither gate existed here; a matched
rule always carried its traditional effects.
"""
gated = False
assessment = match.get('effect_assessment')
if isinstance(assessment, dict) and assessment:
entry['effect_assessment'] = dict(assessment)
status = assessment.get('status')
if status in EFFECT_QUALIFICATIONS:
zh, en = EFFECT_QUALIFICATIONS[status]
zh = assessment.get('summary_zh', zh)
en = assessment.get('summary_en', en)
entry['effect_assessment'].update({'summary_zh': zh, 'summary_en': en})
entry['combination'] = str(entry.get('combination') or '') + ';' + zh
if entry.get('combination_en'):
entry['combination_en'] = str(entry['combination_en']) + ' ' + en
_withhold_effects(entry)
gated = True
if rule.get('method_review'):
entry['method_review'] = dict(rule['method_review'])
if entry['method_review'].get('status') == 'pending':
# Preserve the matched structure and traditional claims without treating
# an unresolved method as adjudicated.
_withhold_effects(entry)
entry.setdefault('condition_status', 'method_requires_review')
gated = True
entry['formation_status'] = entry.get('condition_status', 'conditions_met')
entry['evidence_status'] = 'local_rule_match'
entry['display_status'] = 'candidate_review'
entry['assertion_label'] = 'single_system_inference'
entry['claim_boundary'] = ('Named rule conditions only; external validation and real-life '
'results are not established by detection.')
# Her rows all carry card_eligible=False. Product layer (announced, BUG-2299): the chart
# page reads card_eligible=False as 「暂无法判断」 (BUG-2173), so here it is set only on rows
# a gate restricted; whether every local match should read so is an open question for her.
if gated or entry['formation_status'] != 'conditions_met':
entry['card_eligible'] = False
entry['card_status'] = 'reference_only'
entry['card_block_reason'] = (
'Traditional yoga is detected by the local rule library; independent source/case '
'verification is still required before it can appear as a conclusion card.')
def _blocked_rule_row(rule: Dict, exc: BaseException, ctx: "YogaContext") -> Dict:
"""Her failure row (upstream 58f37ee5b `detect`): neither formed nor ruled out."""
failure_status = ('incomplete_conditions' if isinstance(exc, MissingYogaInput)
else 'not_implemented' if isinstance(exc, UnsupportedYogaCondition)
else 'evaluation_error')
return {
'rule_id': rule.get('id', ''), 'name': rule.get('name', ''),
'name_cn': rule.get('name_cn', ''), 'source': rule.get('source', ''),
'category': rule.get('category') or 'unclassified_rule',
'formation_status': failure_status,
'condition_status': failure_status,
'evidence_status': failure_status,
'unsupported_conditions': getattr(exc, 'conditions', []),
'missing_inputs': getattr(exc, 'fields', []),
'display_status': 'blocked', 'assertion_label': 'blocked',
'card_eligible': False, 'card_status': 'blocked',
'effects': [], 'effects_en': [], 'planets': [],
'strength': 'not_assessed', 'combination': '',
'error_type': type(exc).__name__,
'claim_boundary': 'Rule evaluation failed; no formation or outcome is inferred.',
# An unavailable predicate must not erase its reviewed definition/source or turn
# a source gap into absence.
'source_reference': rule.get('source_reference', rule.get('source', '')),
'combination_en': rule.get('combination_en', ''),
'english_source_reference': rule.get('english_source_reference', ''),
'traditional_effects': list(rule.get('effects') or []),
'traditional_effects_en': list(rule.get('effects_en') or []),
'source_method_notes': list(rule.get('source_method_notes') or []),
'condition_evidence': {
'rule_id': rule.get('id'), 'definition': rule.get('logic'),
'source_reference': rule.get('source_reference', rule.get('source', '')),
'execution_trace': list(getattr(ctx, 'condition_execution_trace', []) or []),
'trace_scope': 'executed_condition_nodes_before_failure; not a successful evaluation',
'participants': {},
},
}
BLOCKED_ROW_STATUSES = frozenset({'incomplete_conditions', 'not_implemented', 'evaluation_error'})
def is_blocked_rule_row(row: Any) -> bool:
"""True for a `detect` row that records a rule evaluation failure (BUG-2299)."""
return (isinstance(row, dict) and row.get('display_status') == 'blocked'
and row.get('formation_status') in BLOCKED_ROW_STATUSES)
def evaluation_failure_row(rule: Dict, exc: BaseException) -> Dict:
"""The record of one rule that could not be evaluated on this chart."""
error_class = getattr(exc, "error_class", None) or type(exc).__name__
@@ -1606,6 +1729,21 @@ class YogaEngine:
entry['formation_checks'] = checks
entry['formation_assessment'] = assess_yoga_formation(entry)
# BUG-2299 (upstream 58f37ee5b): different lordship roles can refer to one
# physical planet. Preserve the literal rule match, but never count roles as
# independent witnesses.
shared = {p: [h for h in range(1, 13) if ctx.lord_of_house(h) == p]
for p in planets_bound}
cancellation = entry.get('formation_evidence') or {}
entry['evidence_dependencies'] = {
'shared_lordships': {p: houses for p, houses in shared.items() if len(houses) > 1},
'participant_positions': {p: {'sign': ctx.sign_of(p), 'house': ctx.house_of(p)}
for p in planets_bound},
'self_reference_only': cancellation.get('self_reference_only'),
'independent_confirmation_count': None,
'claim_boundary': 'Shared planets, lordship roles and overlapping yoga names are not independent confirmations. Formation, strength, activation and outcome require separate assessment.',
}
supporting, limiting, contextual = [], [], []
unassessed = {'functional_benefic_malefic', 'Shadbala', 'Vimsopaka',
'aspect_strength', 'event_timing', 'composite_yoga_strength'}
@@ -1661,15 +1799,22 @@ class YogaEngine:
# 规则匹配。一条规则求值失败(异常)记为 evaluation_failed 并带错误类,
# 不得静默当成不成立(占星师第三轮审查 2026-11-07)。
for rule in self.rules:
# BUG-2299 (upstream 58f37ee5b): her registry English for rules without their own
# English fields; the rule's own fields always win.
rule = dict(english_delivery_fields(rule), **rule)
# BUG-2075 (upstream 19cfd9c0): receipt of the condition nodes this rule actually evaluated.
ctx.condition_execution_trace = []
try:
matches = self._eval_rule(rule, ctx)
except UnsupportedYogaCondition as exc:
unimplemented.append(_not_implemented_row(rule, exc.conditions))
continue
except Exception as exc: # noqa: BLE001 - recorded per rule, see evaluation_failure_row
failures.append(evaluation_failure_row(rule, exc))
if isinstance(exc, UnsupportedYogaCondition):
unimplemented.append(_not_implemented_row(rule, exc.conditions))
else:
failures.append(evaluation_failure_row(rule, exc))
# BUG-2299 (upstream 58f37ee5b): failure is not evidence of absence or a formed
# yoga. Her blocked row stays in `detect`'s list; the product entry points
# (`detect_yogas`, `detect_yogas_with_status`) list it apart, as before.
results.append(_blocked_rule_row(rule, exc, ctx))
continue
for m in matches:
combination = m.get("combination", "")
@@ -1705,6 +1850,9 @@ class YogaEngine:
# BUG-2222 (upstream b6754475): where the traditional meaning comes from.
if rule.get('meaning_source_reference'):
entry['meaning_source_reference'] = rule['meaning_source_reference']
# BUG-2299 (upstream 58f37ee5b): the English source line her renderers read.
if rule.get('english_source_reference'):
entry['english_source_reference'] = rule['english_source_reference']
entry['claim_kind'] = rule.get('claim_kind', 'named_yoga_candidate')
for key in ('legacy_name', 'traditional_effects', 'traditional_effects_en'):
if key in rule:
@@ -1745,7 +1893,12 @@ class YogaEngine:
entry['condition_status'] = 'combustion_requires_review'
entry['traditional_effects'] = entry['effects']
entry['effects'] = []
# BUG-2299 (upstream 58f37ee5b): the English twin moves too.
if entry.get('effects_en'):
entry['traditional_effects_en'] = entry['effects_en']
entry['effects_en'] = []
entry['strength'] = 'conditional'
entry['strength_en'] = 'Conditional'
entry['combustion_witness'] = {
'planet': 'Mercury',
'combust': True,
@@ -1766,7 +1919,15 @@ class YogaEngine:
entry['effects_en'] = []
entry['strength'] = 'conditional'
entry['strength_en'] = 'Conditional'
_apply_effect_and_method_gates(entry, rule, m)
self._attach_interpretive_evidence(entry, ctx)
# BUG-2299 (upstream 58f37ee5b): rules that name the lordships they rely on share
# fact keys, so overlapping rules are listed and never counted as independent votes.
roles = rule.get('evidence_lordship_houses', [])
if roles:
entry['evidence_dependencies']['shared_fact_keys'] = [
f"D1:lord:{house}:{ctx.lord_of_house(house)}:house:{ctx.house_of(ctx.lord_of_house(house))}"
for house in roles]
# BUG-2075 (upstream 19cfd9c0): names and prose are not identities.
# Distinct rules or planetary witnesses may share both; collapse
# only identical results, and never count variants as votes.
@@ -1781,6 +1942,15 @@ class YogaEngine:
# e628118d removed it. The precise rules count the same five planets
# (BUG-1187 / BUG-1206), so nothing they ruled is lost.
# ── 主检测器(同名 JSON 规则为 reference_only) ──
# BUG-2299 (upstream 58f37ee5b): rules sharing a lordship fact name each other.
for entry in results:
dependencies = entry.get('evidence_dependencies', {})
keys = set(dependencies.get('shared_fact_keys', []))
if keys:
dependencies['overlapping_rule_ids'] = sorted({
other['rule_id'] for other in results if other is not entry and
keys.intersection(other.get('evidence_dependencies', {}).get('shared_fact_keys', []))})
dependencies['independent_confirmation_count'] = None
results += main_detector_rows(ctx.planets, ctx.ascendant)
return results
@@ -3475,7 +3645,8 @@ def detect_yogas(planets: Dict[str, Dict], ascendant: str,
skill_dir = os.path.dirname(script_dir)
rules_path = os.path.join(skill_dir, "references", "yoga_rules.json")
engine = YogaEngine(rules_path)
return engine.detect(planets, ascendant, context=context)
# BUG-2299: her blocked rows are listed apart (`detect_yogas_with_status`), not as yogas.
return [row for row in engine.detect(planets, ascendant, context=context) if not is_blocked_rule_row(row)]
def detect_yogas_with_status(planets: Dict[str, Dict], ascendant: str,
@@ -3490,7 +3661,9 @@ def detect_yogas_with_status(planets: Dict[str, Dict], ascendant: str,
script_dir = os.path.dirname(os.path.abspath(__file__))
rules_path = os.path.join(os.path.dirname(script_dir), "references", "yoga_rules.json")
engine = YogaEngine(rules_path)
yogas = engine.detect(planets, ascendant, context=context)
# BUG-2299: her blocked rows (upstream 58f37ee5b) stay out of `yogas`; the same rules are in
# `evaluation_failures` / `unimplemented_rules`, so the /api/yogas shape is unchanged.
yogas = [row for row in engine.detect(planets, ascendant, context=context) if not is_blocked_rule_row(row)]
failures = list(engine.last_evaluation_failures)
unimplemented = list(engine.unimplemented_rules) + list(engine.last_unimplemented)
return {