"""Auditable career-role semantics layered on the existing evidence snapshot.""" from __future__ import annotations from datetime import date as calendar_date import json from pathlib import Path from typing import Any _ROOT = Path(__file__).resolve().parents[1] _TAXONOMY = _ROOT / "references" / "career_semantic_taxonomy.json" _PROVENANCE = {"existing_source", "traditional_reference", "research_hypothesis"} _PUBLIC_CASE_SOURCE_TIERS = { "primary", "primary_public_record", "verified_secondary", "public_research", } _RELIABLE_TIME_RATINGS = {"AA", "A", "reliable", "verified"} _SIMILARITY_LEVELS = tuple(f"L{level}" for level in range(6)) _SOURCE_PATHS = { "D1": "modules.chart", "D10": "modules.varga_full.D10_Dasamsa", "A10": "modules.special_lagnas.A10_Karma_Pada", "vimsopaka": "ai_prompt_pack.evidence_snapshot.vimsopaka_semantic_summary", "western": "western.natal", } _REQUIRED_EXECUTION = { "D1": {"D1"}, "D10": {"D10"}, "A10": {"A10"}, "vimsopaka": {"Vimsopaka"}, "western": {"Western"}, } def _get(source: dict[str, Any], path: str) -> Any: current: Any = source for key in path.split("."): if not isinstance(current, dict): return None current = current.get(key) return current def _is_public_url(value: Any) -> bool: return isinstance(value, str) and value.startswith(("https://", "http://")) def _is_iso_date(value: Any) -> bool: if not isinstance(value, str): return False try: return calendar_date.fromisoformat(value).isoformat() == value except ValueError: return False def validate_case_card(card: dict[str, Any] | None) -> dict[str, Any]: """Validate public career-case metadata without retaining case content.""" card = card if isinstance(card, dict) else {} errors: list[str] = [] if not _is_public_url(card.get("source_url")): errors.append("source_url") if card.get("source_tier") not in _PUBLIC_CASE_SOURCE_TIERS: errors.append("source_tier") if not isinstance(card.get("birth_data_provenance"), str) or not card["birth_data_provenance"].strip(): errors.append("birth_data_provenance") if card.get("time_reliability") not in _RELIABLE_TIME_RATINGS: errors.append("time_reliability") event = card.get("career_event") if not isinstance(event, dict): errors.extend(("career_event.date", "career_event.description", "career_event.source_url")) else: if not _is_iso_date(event.get("date")): errors.append("career_event.date") if not isinstance(event.get("description"), str) or not event["description"].strip(): errors.append("career_event.description") if not _is_public_url(event.get("source_url")): errors.append("career_event.source_url") similarity = card.get("similarity") if not isinstance(similarity, dict): errors.append("similarity") similarity = {} elif any(level not in _SIMILARITY_LEVELS or not isinstance(value, str) or not value.strip() for level, value in similarity.items()): errors.append("similarity") if not isinstance(card.get("transferability_boundary"), str) or not card["transferability_boundary"].strip(): errors.append("transferability_boundary") if errors: return {"status": "rejected", "errors": errors} if all(level in similarity for level in _SIMILARITY_LEVELS) and "L4" in similarity: return {"status": "accepted_calibration_candidate", "errors": []} return {"status": "accepted_background_only", "errors": []} def load_taxonomy(path: Path = _TAXONOMY) -> dict[str, Any]: taxonomy = json.loads(path.read_text(encoding="utf-8")) templates = taxonomy.get("signal_templates") domains = taxonomy.get("domains") if not isinstance(templates, dict) or not isinstance(domains, dict): raise ValueError("career taxonomy requires templates and domains") for domain in domains.values(): roles = domain.get("role_clusters") if isinstance(domain, dict) else None if not isinstance(roles, dict): raise ValueError("career taxonomy domain requires role_clusters") for role_id, template_ids in list(roles.items()): if not isinstance(template_ids, list): raise ValueError(f"role {role_id} requires signal template ids") signals = [] for template_id in template_ids: rule = dict(templates.get(template_id) or {}) if not rule: raise ValueError(f"unknown signal template: {template_id}") if rule.get("provenance") not in _PROVENANCE: raise ValueError(f"invalid provenance for {template_id}") required = {"id", "layer", "path", "operator", "value", "weight", "polarity", "note", "provenance"} if not required <= set(rule): raise ValueError(f"incomplete semantic rule: {template_id}") signals.append(rule) roles[role_id] = {"signals": signals} return taxonomy def _matches(rule: dict[str, Any], indian: dict[str, Any], western: dict[str, Any]) -> bool: source = western if rule["layer"].startswith("western") else indian path = rule["path"] if source is indian and path.startswith("modules."): path = path.removeprefix("modules.") value = _get(source, path) if rule["operator"] == "in": return value in rule["value"] if rule["operator"] == "not_in": return value not in rule["value"] return False def build_career_execution_audit( modules: dict[str, Any], western: dict[str, Any] | None, vimsopaka_semantic_summary: dict[str, Any] | None, ) -> list[dict[str, str]]: """Record only the five inputs this semantic classifier consumes.""" modules = modules if isinstance(modules, dict) else {} checks = { "D1": _get(modules, "chart.ascendant"), "D10": _get(modules, "varga_full.D10_Dasamsa"), "A10": _get(modules, "special_lagnas.A10_Karma_Pada"), "Vimsopaka": vimsopaka_semantic_summary if isinstance(vimsopaka_semantic_summary, dict) and vimsopaka_semantic_summary.get("status") == "used" else None, "Western": western, } return [ {"technique": technique, "status": "executed" if value not in (None, {}, [], "") else "blocked"} for technique, value in checks.items() ] def _missing_execution(audit: Any) -> list[str]: rows = audit if isinstance(audit, list) else [] statuses = { str(row.get("technique")): str(row.get("status")) for row in rows if isinstance(row, dict) } return [ key for key, names in _REQUIRED_EXECUTION.items() if not any(statuses.get(name) == "executed" for name in names) ] def _evidence_item(path: str, layer: str, weight: int, note: str, polarity: str = "support") -> dict[str, Any]: return { "id": f"career_semantic:{path}", "layer": layer, "path": path, "weight": weight, "note": note, "provenance": "research_hypothesis", "polarity": polarity, } def _screenwriter_house_evidence(modules: dict[str, Any], western: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Return source-path-only career signals; never retain chart payload values.""" candidates = ( ("modules.chart.planets.Mercury.house", "indian_natal", 3, "D1 third-house communication signal", {3}), ("modules.chart.planets.Venus.house", "indian_natal", 3, "D1 fifth-house creative signal", {5}), ("modules.varga_full.D10_Dasamsa.Mercury.house", "indian_d10", 3, "D10 tenth-house vocational writing signal", {10}), ("modules.varga_full.D10_Dasamsa.Venus.house", "indian_d10", 3, "D10 fifth-house creative execution signal", {5}), ("natal.planets.mercury.house", "western_natal", 2, "Western fifth-house writing signal", {5}), ("natal.planets.venus.house", "western_natal", 2, "Western fifth-house creative signal", {5}), ) support = [] for path, layer, weight, note, expected in candidates: source = western if path.startswith("natal.") else modules lookup_path = path.removeprefix("modules.") if _get(source, lookup_path) in expected: support.append(_evidence_item(path, layer, weight, note)) if _get(western, "natal.angles.mc.ruler") == "Mercury": support.append(_evidence_item("natal.angles.mc.ruler", "western_natal", 3, "MC ruler supports communication vocation")) counter = [] for path, layer in ( ("modules.chart.planets.Saturn.house", "indian_natal"), ("modules.varga_full.D10_Dasamsa.Saturn.house", "indian_d10"), ("natal.planets.saturn.house", "western_natal"), ): source = western if path.startswith("natal.") else modules if _get(source, path.removeprefix("modules.")) in {8, 9, 12}: counter.append(_evidence_item(path, layer, 1, "Saturn in house 8, 9 or 12 counterweight", "counter")) return support, counter def build_career_semantic_profile( modules: dict[str, Any], western: dict[str, Any] | None, vimsopaka_semantic_summary: dict[str, Any] | None, technique_audit: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: modules = modules if isinstance(modules, dict) else {} western = western if isinstance(western, dict) else None source_paths = dict(_SOURCE_PATHS) if isinstance(vimsopaka_semantic_summary, dict) and isinstance(vimsopaka_semantic_summary.get("source_path"), str): source_paths["vimsopaka"] = vimsopaka_semantic_summary["source_path"] missing = [] if not _get(modules, "chart.ascendant"): missing.append("D1") if not _get(modules, "varga_full.D10_Dasamsa"): missing.append("D10") if not _get(modules, "special_lagnas.A10_Karma_Pada"): missing.append("A10") if not isinstance(vimsopaka_semantic_summary, dict) or vimsopaka_semantic_summary.get("status") != "used": missing.append("vimsopaka") if western is None: missing.append("western") missing = list(dict.fromkeys(missing + _missing_execution(technique_audit))) if missing: return { "status": "blocked", "missing_required_evidence": missing, "ranked_domains": [], "ranked_role_clusters": [], "cross_system_conflicts": [], "verification_questions": [], "vimsopaka_source_path": "ai_prompt_pack.evidence_snapshot.vimsopaka_semantic_summary", "source_paths": source_paths, "technique_audit": list(technique_audit or []), } taxonomy = load_taxonomy() domains = [] roles = [] for domain_id, domain in taxonomy["domains"].items(): domain_score = 0 for role_id, role in domain["role_clusters"].items(): support, counter = [], [] score = 0 for rule in role["signals"]: if not _matches(rule, modules, western): continue item = {key: rule[key] for key in ("id", "layer", "path", "weight", "note", "provenance")} if rule["polarity"] == "counter": counter.append(item) score -= int(rule["weight"]) else: support.append(item) score += int(rule["weight"]) if role_id == "screenwriter": house_support, house_counter = _screenwriter_house_evidence(modules, western) support.extend(house_support) counter.extend(house_counter) score += sum(item["weight"] for item in house_support) score -= sum(item["weight"] for item in house_counter) if not support and not counter: continue research_only = support and all(item["provenance"] == "research_hypothesis" for item in support) roles.append({ "id": role_id, "domain": domain_id, "score": score, "supporting_evidence": support, "counter_evidence": counter, "assertion_label": "parameter_sensitive" if research_only else "multi_system_consensus" if any(item["layer"].startswith("western") for item in support) and any(item["layer"].startswith("indian") for item in support) else "single_system_inference", "confidence_cap": "medium" if not research_only else "low", # BUG-2110 (占星师 2026-11-21): no question asking for the user's own history # (was 「该方向是否已有作品、客户、项目或持续训练可供回测?」); same [] as the blocked branch. "verification_questions": [], }) domain_score += score domains.append({"id": domain_id, "score": domain_score}) return { "status": "used", "missing_required_evidence": [], "ranked_domains": sorted(domains, key=lambda item: (-item["score"], item["id"])), "ranked_role_clusters": sorted(roles, key=lambda item: (-item["score"], item["id"])), "cross_system_conflicts": [], # BUG-2110: was 「请用已知职业节点回测候选簇…」, which asks for the user's career history. "verification_questions": [], "vimsopaka_source_path": "ai_prompt_pack.evidence_snapshot.vimsopaka_semantic_summary", "source_paths": source_paths, "technique_audit": list(technique_audit or []), }