Files
Jyotisha/scripts/preset_evidence/library.py
T

651 lines
33 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.
"""Validate and match the reviewed preset evidence library."""
from __future__ import annotations
import argparse
import ast
import hashlib
import json
import re
import subprocess
import tempfile
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Any, Dict, Iterable, List, Optional
ROOT = Path(__file__).resolve().parents[2]
LIBRARY_DIR = ROOT / "references" / "preset_evidence_library"
ENTRIES_DIR = LIBRARY_DIR / "entries"
SCHEMA_PATH = LIBRARY_DIR / "schema.json"
RECEIPT_PATH = "rulings/review_receipt_20261112.json"
RECEIPT_SHA256 = "426c456f99848c14e0ffd20a8657f7251c24cb9ae555d77a64ddeef402ea801d"
VALIDATOR_VERSION = "preset-library-validator.v2"
MATCHER_VERSION = "preset-library-matcher.v1"
MANIFEST_SCHEMA = "jyotish.preset_evidence_library.verified.v1"
PERMISSIONS = {
"eligible_after_common_gates": "match_allowlist",
"branch_review_required": "branch_review",
"reference_or_gap_only": "reference_only",
}
SPLIT_FROM = "mudda.starting_lord_and_balance"
SPLIT_ID = f"{SPLIT_FROM}.varshaphala_moon"
FORBIDDEN_STATE = re.compile(r"\b(?:formal_case_admitted|production_tuning_allowed|global_closure)\b")
REFERENCE_REASON = "找到相关参考,尚不足以支持所执行分支"
def load_schema() -> Dict[str, Any]:
return json.loads(SCHEMA_PATH.read_bytes())
def load_category_files(entries_dir: Path = ENTRIES_DIR) -> Dict[str, Dict[str, Any]]:
return {path.stem: json.loads(path.read_bytes()) for path in sorted(entries_dir.glob("*.json"))}
def load_entries(entries_dir: Path = ENTRIES_DIR) -> List[Dict[str, Any]]:
return [entry for doc in load_category_files(entries_dir).values() for entry in doc["entries"]]
# ── minimal JSON-schema subset (no third-party dependency) ─────────────────
_TYPES = {"object": dict, "array": list, "string": str, "null": type(None), "boolean": bool, "integer": int}
def _schema_errors(value: Any, schema: Dict[str, Any], root: Dict[str, Any], where: str) -> Iterable[str]:
if "$ref" in schema:
name = schema["$ref"].split("/")[-1]
yield from _schema_errors(value, root["$defs"][name], root, where)
return
if "type" in schema:
types = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]
if not any(type(value) is _TYPES[t] for t in types):
yield f"{where}: expected {types}, got {type(value).__name__}"
return
if "const" in schema and value != schema["const"]:
yield f"{where}: must equal {schema['const']!r}"
if "enum" in schema and value not in schema["enum"]:
yield f"{where}: {value!r} not in {schema['enum']}"
if isinstance(value, str):
if "pattern" in schema and not re.search(schema["pattern"], value):
yield f"{where}: {value!r} does not match {schema['pattern']}"
if len(value) < schema.get("minLength", 0):
yield f"{where}: shorter than {schema['minLength']}"
if isinstance(value, list):
if len(value) < schema.get("minItems", 0):
yield f"{where}: fewer than {schema['minItems']} items"
if "items" in schema:
for index, item in enumerate(value):
yield from _schema_errors(item, schema["items"], root, f"{where}[{index}]")
if isinstance(value, dict):
for key in schema.get("required", []):
if key not in value:
yield f"{where}: missing required field {key!r}"
props = schema.get("properties", {})
for key, item in value.items():
if key in props:
yield from _schema_errors(item, props[key], root, f"{where}.{key}")
elif schema.get("additionalProperties") is False:
yield f"{where}: unexpected field {key!r}"
def schema_errors(doc: Dict[str, Any], schema: Optional[Dict[str, Any]] = None) -> List[str]:
schema = schema or load_schema()
return list(_schema_errors(doc, schema, schema, "$"))
# ── policy checks ───────────────────────────────────────────────────────────
def _compact(text: str) -> str:
"""Whitespace-free, quote-folded text, so PDF line breaks do not hide a verbatim quote."""
text = text.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
return re.sub(r"\s+", "", text)
class LibraryValidationError(ValueError):
def __init__(self, message: str, content_hash: str | None = None):
super().__init__(message)
self.content_hash = content_hash
def _digest(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _canonical_hash(value: Any) -> str:
return _digest(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8"))
def _relative_path(rel: str) -> PurePosixPath:
path = PurePosixPath(rel)
if (not rel or rel == "." or "\\" in rel or ":" in rel or "\x00" in rel
or path.is_absolute() or PureWindowsPath(rel).drive or ".." in path.parts):
raise ValueError(f"unsafe relative path: {rel!r}")
return path
def _inside(root: Path, rel: str) -> Path:
path = root.joinpath(_relative_path(rel)).resolve()
if not path.is_relative_to(root.resolve()):
raise ValueError(f"path resolves outside its root: {rel!r}")
return path
class _FileIndex:
"""Read each referenced file once and keep the hashes used by validation."""
def __init__(self, her_export: Path):
self.her_export = her_export.resolve()
self._cache: dict[str, bytes] = {}
def read(self, rel: str) -> bytes:
path = _inside(self.her_export, rel)
if rel not in self._cache:
self._cache[rel] = path.read_bytes()
return self._cache[rel]
def hashes(self) -> dict[str, str]:
return {path: _digest(data) for path, data in sorted(self._cache.items())}
def _strings(node: Any) -> Iterable[str]:
if isinstance(node, dict):
for key, value in node.items():
yield key
yield from _strings(value)
elif isinstance(node, list):
for value in node:
yield from _strings(value)
elif isinstance(node, str):
yield node
def calibration_filled(entry: dict) -> bool:
cal = entry["event_calibration"]
return (cal["status"] != "not_done" and bool(cal["cases"]) and all(
str(case.get(field) or "").strip() for case in cal["cases"]
for field in ("source", "birth_precision", "event_date", "set")))
def _path_references(entry: dict) -> Iterable[tuple[str, str, str | None, str | None, str]]:
source = entry["source"]
if source["file_path_in_her_repo"]:
yield ("her_export", source["file_path_in_her_repo"], source["sha256"], source["quote_excerpt"], "source")
for material in entry["supporting_materials"]:
yield ("her_export", material["file_path_in_her_repo"], material["sha256"], material.get("quote_excerpt"), "supporting")
for question in entry["open_questions_for_astrologer"]:
yield ("her_export", question["quote_ref"]["file_path_in_her_repo"], None, question["quote"], "question")
replay = entry["calculation_replay"]
for key in ("engine_paths", "test_paths"):
for repo, paths in replay[key].items():
for path in paths:
yield (repo, path, None, None, key)
for chart in replay["charts"]:
artifact = chart["artifact"]
if artifact:
yield (artifact["repo"], artifact["path"], None, None, "chart artifact")
for ref in entry["admission_evidence"]:
yield (ref["repo"], ref["path"], None, None, "historical admission evidence")
def _reviewed_bindings(entry_id: str) -> set[tuple[str, str, str, str]]:
# These identifiers come from the native functions and their execution receipts.
# The five Mahapurusha identifiers share a detector but keep each formation branch.
if entry_id == "functional.pvr_table30":
return {("scripts.functional_benefics::derive_functional_benefic_malefic",
"pvr_integrated_approach_13_2_table_30", "pvr_table30_v1", "table_cell")}
if entry_id == "narayana.dual_lord.rath_p42_43":
return {("scripts.narayana_rath::resolve_dual_lord", rule, "rath_p43_text_first_round7_v1",
f"selected:{rule}") for rule in "abcde"}
if entry_id == SPLIT_FROM:
return {("scripts.tajika_mudda::annual_mudda_dasha",
"astrologer_round5_q7_completed_years_plus_natal_nakshatra_minus_two_mod_nine",
"moon_at_birth_time", "moon_at_birth_time")}
match = re.fullmatch(r"yoga[.]mahapurusha[.](ruchaka|bhadra|sasa|malavya|hamsa)[.](exalted|own)", entry_id)
if match:
kind, branch = match.groups()
planets = {"ruchaka": "mars", "bhadra": "mercury", "sasa": "saturn", "malavya": "venus", "hamsa": "jupiter"}
return {("scripts.main_yoga_detectors::pancha_mahapurusha_rows",
f"main_detector:pancha_mahapurusha:{planets[kind]}",
"pancha_mahapurusha.detect_pancha_mahapurusha", branch)}
return set()
def _binding_errors(entry: dict, our_root: Path | None) -> Iterable[str]:
execution = entry["calculation_execution"]
bindings = execution["bindings"]
active = [binding for binding in bindings if binding["role"] == "active"]
if entry["use_permission"] == "match_allowlist":
if entry["source_support"] != "located" or execution["status"] != "executed" or not active:
yield "allowlist entry requires a located source, executed calculation and an active binding"
expected = _reviewed_bindings(entry["id"])
actual = {(binding["function"], binding["rule_id"], binding["profile_id"], binding["branch_id"])
for binding in active}
if actual != expected:
yield "execution binding differs from the reviewed native rule, profile or branch"
elif active:
yield "only an allowlist entry can have an active binding"
seen = set()
for binding in bindings:
key = (binding["profile_id"], binding["branch_id"])
if key in seen:
yield f"duplicate execution binding {key!r}"
seen.add(key)
try:
module, sep, function = binding["function"].partition("::")
if not sep or not re.fullmatch(r"scripts(?:[.][A-Za-z_][A-Za-z0-9_]*)+", module):
raise ValueError("function must name a repository module and function")
test_rel = _relative_path(binding["test_path"])
if not test_rel.parts or test_rel.parts[0] != "tests" or test_rel.suffix != ".py":
raise ValueError("execution test must be a Python test under tests/")
if our_root is None:
continue
module_path = _inside(our_root, module.replace(".", "/") + ".py")
tree = ast.parse(module_path.read_bytes())
if not any(isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == function
for node in tree.body):
yield f"execution function does not exist: {binding['function']}"
test = _inside(our_root, binding["test_path"])
if not test.is_file() or not test.is_relative_to((our_root / "tests").resolve()):
yield f"execution test does not exist under tests/: {binding['test_path']}"
except (OSError, SyntaxError, ValueError) as error:
yield f"invalid execution binding: {error}"
def _external_check_errors(entry: dict, files: _FileIndex | None, our_root: Path | None) -> Iterable[str]:
check = entry["external_calculation_check"]
if check["status"] == "not_done":
if check["evidence"]:
yield "external calculation not_done but lists evidence"
return
if not check["evidence"]:
yield "external calculation done needs a calculation receipt"
pairs = {(b["profile_id"], b["branch_id"]) for b in entry["calculation_execution"]["bindings"]}
for item in check["evidence"]:
try:
rel = item["path"]
_relative_path(rel)
if (item["profile_id"], item["branch_id"]) not in pairs:
raise ValueError("calculation receipt does not bind an entry profile and branch")
if item["repo"] == "our_repo" and our_root is not None:
data = _inside(our_root, rel).read_bytes()
elif item["repo"] == "her_export" and files is not None:
data = files.read(rel)
else:
continue
if _digest(data) != item["sha256"]:
raise ValueError("calculation receipt hash mismatch")
document = json.loads(data)
expected = {"kind": "external_calculation_check", "status": "passed", "technique_id": entry["match"]["technique_id"],
"profile_id": item["profile_id"], "branch_id": item["branch_id"]}
if not isinstance(document, dict) or any(document.get(key) != value for key, value in expected.items()):
raise ValueError("file is not a matching external calculation receipt")
except (OSError, ValueError) as error:
yield f"invalid external calculation evidence: {error}"
def entry_policy_errors(entry: Dict[str, Any], files: Optional[_FileIndex] = None,
our_root: Path | None = ROOT) -> List[str]:
eid = entry["id"]
errors = []
source = entry["source"]
states = {state for text in _strings(entry) for state in FORBIDDEN_STATE.findall(text)}
errors.extend(f"unsupported policy state: {state}" for state in sorted(states))
for name in ("source", "rule_statement", "applicability_conditions", "exceptions_or_counterexamples"):
block = entry[name]
if block["status"] == "missing" and not block["note"].strip():
errors.append(f"{name} is missing without a note")
if source["status"] != "missing" and not (source["file_path_in_her_repo"] and source["sha256"] and source["locator"]):
errors.append("located or partial source needs a path, sha256 and locator")
if entry["source_support"] != source["status"]:
errors.append("source_support must match source.status")
if entry["calculation_execution"]["status"] != entry["calculation_replay"]["status"]:
errors.append("calculation_execution must match the calculation replay status")
if entry["use_permission"] != PERMISSIONS.get(entry["review"]["decision"]):
errors.append("use_permission must come from the review decision")
errors.extend(_binding_errors(entry, our_root))
errors.extend(_external_check_errors(entry, files, our_root))
cal = entry["event_calibration"]
if cal["status"] != "not_done" and not calibration_filled(entry):
errors.append(f"event_calibration status {cal['status']!r} without complete cases")
if cal["status"] == "not_done" and cal["cases"]:
errors.append("event_calibration not_done but lists cases")
dev_ids = {chart["chart_id"] for chart in entry["calculation_replay"]["charts"]
if chart["role"] == "public_development_calculation_replay"}
for case in cal["cases"]:
if case["set"] == "holdout" and (case["case_id"] in dev_ids or case["case_id"].startswith("public_dev:")):
errors.append(f"public development chart {case['case_id']} used as holdout")
for witness in entry.get("witness_examples", []):
self_reference = witness["planet"] == witness["reference"]
if witness["self_reference"] is not self_reference or (
self_reference and witness["independent_confirmation_allowed"] is not False
):
errors.append("self-reference cannot count as independent confirmation")
if eid == "functional.moon_movable_lagna" and entry.get("lagna_scope") != ["Aries", "Libra", "Capricorn"]:
errors.append("the movable Moon rule applies only to Aries, Libra and Capricorn")
for repo, rel, sha, quote, role in _path_references(entry):
try:
_relative_path(rel)
if repo == "our_repo":
if our_root is not None and not _inside(our_root, rel).is_file():
errors.append(f"our_repo path does not exist: {rel}")
continue
if files is None:
continue
data = files.read(rel)
if sha is not None and _digest(data) != sha:
errors.append(f"{role} sha256 mismatch for {rel}")
if quote and _compact(quote) not in _compact(data.decode("utf-8")):
errors.append(f"{role} quote not found verbatim in {rel}")
except (OSError, ValueError) as error:
errors.append(f"{role} path could not be verified: {error}")
return [f"{eid}: {error}" for error in errors]
def _read_receipt(library_dir: Path) -> dict:
raw = _inside(library_dir, RECEIPT_PATH).read_bytes()
if _digest(raw) != RECEIPT_SHA256:
raise LibraryValidationError("review receipt does not match the authorized copy")
return json.loads(raw)
def _receipt_errors(entry: dict, decisions: dict[str, dict]) -> Iterable[str]:
eid = entry["id"]
review = entry["review"]
ruling_id = SPLIT_FROM if eid == SPLIT_ID else eid
row = decisions.get(ruling_id)
if row is None:
yield f"{eid}: ID is absent from the authorized review receipt"
return
decision = "reference_or_gap_only" if eid == SPLIT_ID else row["review_decision"]
if review != {"decision": decision, "ruling_ref": f"{RECEIPT_PATH}#{ruling_id}"}:
yield f"{eid}: review decision or ruling reference differs from the receipt"
if entry["event_calibration"]["status"] != "not_done":
yield f"{eid}: the authorized review has no event calibration"
source = entry["source"]
if eid != SPLIT_ID and (source["file_path_in_her_repo"], source["sha256"]) != (row["source_path"], row["source_sha256"]):
yield f"{eid}: the reviewed primary source path or sha256 differs from the receipt"
def _library_bytes(entries_dir: Path, library_dir: Path) -> dict[str, bytes]:
raw = {"schema.json": _inside(library_dir, "schema.json").read_bytes()}
for path in sorted(entries_dir.glob("*.json")):
raw[f"entries/{path.name}"] = _inside(entries_dir, path.name).read_bytes()
return raw
def _content_hash(raw: dict[str, bytes]) -> str:
digest = hashlib.sha256()
for path, data in sorted(raw.items()):
digest.update(path.encode("utf-8") + b"\0")
digest.update(str(len(data)).encode("ascii") + b"\0")
digest.update(data)
return digest.hexdigest()
def _validate_snapshot(raw: dict[str, bytes], receipt: dict, files: _FileIndex | None,
our_root: Path | None) -> tuple[list[dict], list[str]]:
schema = json.loads(raw["schema.json"])
decisions = {row["id"]: row for row in receipt["entries"]}
errors = []
entries = []
seen = set()
for name, data in raw.items():
if name == "schema.json":
continue
try:
doc = json.loads(data)
except ValueError as error:
errors.append(f"{name}: invalid JSON: {error}")
continue
document_errors = schema_errors(doc, schema)
errors.extend(f"{name} {error}" for error in document_errors)
if document_errors:
continue
if doc["category_file"] != Path(name).stem:
errors.append(f"{name}: category_file does not match filename")
for entry in doc["entries"]:
eid = entry["id"]
if eid in seen:
errors.append(f"{eid}: duplicate id")
seen.add(eid)
entries.append(entry)
errors.extend(_receipt_errors(entry, decisions))
errors.extend(entry_policy_errors(entry, files, our_root))
expected = set(decisions) | {SPLIT_ID}
if expected - seen:
errors.append(f"reviewed entries missing: {sorted(expected - seen)}")
return entries, errors
def validate(entries_dir: Path = ENTRIES_DIR, her_export: Optional[Path] = None,
our_root: Path = ROOT, *, library_dir: Path = LIBRARY_DIR) -> List[str]:
"""Collect schema and policy errors from every category."""
try:
raw = _library_bytes(entries_dir, library_dir)
receipt = _read_receipt(library_dir)
files = _FileIndex(her_export) if her_export is not None else None
return _validate_snapshot(raw, receipt, files, our_root)[1]
except (OSError, ValueError, KeyError, TypeError) as error:
return [f"library inputs could not be read: {error}"]
def _validate_source_pin(files: _FileIndex, receipt: dict) -> str:
root = files.her_export
git = ["git", "-c", f"safe.directory={root.as_posix()}", "-C", str(root)]
checkout = subprocess.run([*git, "rev-parse", "--show-toplevel", "HEAD"], capture_output=True, text=True)
if checkout.returncode == 0:
top, revision = checkout.stdout.splitlines()
if Path(top).resolve() == root:
for rel, sha in files.hashes().items():
data = subprocess.check_output([*git, "show", f"{revision}:{rel}"])
if _digest(data) != sha:
raise LibraryValidationError(f"source checkout differs from its pinned blob: {rel}")
return revision
export_manifest = _inside(root, "source-manifest.json")
if export_manifest.is_file():
manifest = json.loads(export_manifest.read_bytes())
declared_files = manifest["files"]
else:
manifest = json.loads((LIBRARY_DIR / "VERIFIED.json").read_bytes())
declared_files = manifest["source_files"]
if manifest.get("source_repo_commit") != receipt["source_repo_commit"]:
raise LibraryValidationError("export manifest does not name the reviewed source commit")
for rel, sha in files.hashes().items():
if declared_files.get(rel) != sha:
raise LibraryValidationError(f"source export manifest hash mismatch: {rel}")
return receipt["source_repo_commit"]
def _write_manifest(path: Path, manifest: dict) -> None:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=path.parent,
delete=False) as temp:
temp_path = Path(temp.name)
json.dump(manifest, temp, ensure_ascii=False, indent=2, sort_keys=True)
temp.write("\n")
try:
temp_path.replace(path)
finally:
temp_path.unlink(missing_ok=True)
def _versions(raw: dict[str, bytes], receipt: dict) -> dict[str, str]:
return {"schema": json.loads(raw["schema.json"])["$id"], "ruling": receipt["schema"],
"receipt_sha256": RECEIPT_SHA256, "validator": VALIDATOR_VERSION, "matcher": MATCHER_VERSION}
def load_verified_library(library_dir: Path = LIBRARY_DIR) -> dict:
"""Load entries only when the verified manifest binds the current input bytes."""
content_hash = None
try:
raw = _library_bytes(_inside(library_dir, "entries"), library_dir)
content_hash = _content_hash(raw)
receipt = _read_receipt(library_dir)
manifest = json.loads(_inside(library_dir, "VERIFIED.json").read_bytes())
if (manifest.get("schema") != MANIFEST_SCHEMA or manifest.get("content_sha256") != content_hash
or manifest.get("versions") != _versions(raw, receipt)):
raise LibraryValidationError("verified manifest is stale")
if not isinstance(manifest.get("source_repo_commit"), str) or not re.fullmatch(r"[0-9a-f]{40}", manifest["source_repo_commit"]):
raise LibraryValidationError("verified manifest lacks a source revision")
generated = datetime.fromisoformat(manifest["generated_at"])
if generated.tzinfo is None:
raise LibraryValidationError("verified manifest generation time has no timezone")
source_files = manifest.get("source_files")
if not isinstance(source_files, dict) or not source_files:
raise LibraryValidationError("verified manifest lacks source hashes")
for rel, sha in source_files.items():
_relative_path(rel)
if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{64}", sha):
raise LibraryValidationError("verified manifest has an invalid source hash")
# Developer tests and the external checkout need not be installed at runtime.
entries, errors = _validate_snapshot(raw, receipt, None, None)
if errors:
raise LibraryValidationError("verified library fails its schema or review policy")
expected = {}
for entry in entries:
for repo, rel, sha, _, _ in _path_references(entry):
if repo == "her_export":
expected[rel] = sha or expected.get(rel)
for item in entry["external_calculation_check"]["evidence"]:
if item["repo"] == "her_export":
expected[item["path"]] = item["sha256"]
if set(source_files) != set(expected) or any(sha and source_files[rel] != sha for rel, sha in expected.items()):
raise LibraryValidationError("verified manifest source dependencies do not match the entries")
return {"manifest": manifest, "entries": entries}
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
raise LibraryValidationError(str(error), content_hash) from error
def _entry_trace(entry: dict, technique: dict, domain: str) -> dict:
trace = {"entry_id": entry["id"], "use_permission": entry["use_permission"],
"source_support": entry["source_support"], "calculation_execution": entry["calculation_execution"]["status"],
"external_calculation_check": entry["external_calculation_check"]["status"],
"event_calibration": entry["event_calibration"]["status"], "status": "insufficient"}
if domain not in entry["match"]["domains"]:
return {**trace, "reason": "domain_mismatch"}
if entry["use_permission"] == "reference_only":
return {**trace, "reason": REFERENCE_REASON}
if entry["use_permission"] == "branch_review":
return {**trace, "reason": "branch_review_pending"}
if technique["branch_id"] in ("undecided", "unresolved") or technique["branch_id"].startswith("undecided:"):
return {**trace, "reason": "unresolved_dependency"}
if not technique["executed"] or not technique["input_hash"]:
return {**trace, "reason": "execution_receipt_missing"}
for binding in entry["calculation_execution"]["bindings"]:
if binding["role"] != "active" or (binding["profile_id"], binding["branch_id"]) != (
technique["profile_id"], technique["branch_id"]
):
continue
conflicts = [c["id"] for c in entry["conflicts"] if c["status"] == "open"]
if conflicts:
return {**trace, "status": "conflict", "reason": "open_conflict", "conflicts": conflicts}
return {**trace, "status": "matched", "reason": "executed_branch_supported", "binding": binding}
return {**trace, "reason": "profile_or_branch_mismatch"}
def _technique_trace(raw: dict, domain: str, entries: list[dict], counted: set[str]) -> dict:
technique = {key: raw.get(key) if isinstance(raw.get(key), str) else ""
for key in ("technique_id", "profile_id", "branch_id", "input_hash")}
technique["executed"] = raw.get("executed") is True
candidates = [entry for entry in entries if technique["technique_id"] in (entry["id"], entry["match"]["technique_id"])]
traces = [_entry_trace(entry, technique, domain) for entry in candidates]
statuses = {trace["status"] for trace in traces}
status = "conflict" if "conflict" in statuses else "matched" if "matched" in statuses else "insufficient"
for trace in traces:
if trace["status"] == "matched":
rule = trace["binding"]["rule_id"]
trace["counts_as_independent_support"] = not rule.startswith("main_detector:pancha_mahapurusha:") or rule not in counted
counted.add(rule)
reason = "no_related_entry" if not traces else (
"executed_branch_supported" if status == "matched" else
"open_conflict" if status == "conflict" else traces[0]["reason"])
return {**technique, "status": status, "reason": reason, "entries": traces,
"execution_receipt": {key: technique[key] for key in ("profile_id", "branch_id", "executed", "input_hash")}}
def match_claims(claims: list[dict], facts_fingerprint: str, *, library_dir: Path = LIBRARY_DIR) -> list[dict]:
"""Match only executed, reviewed branches. Facts are supplied by the caller."""
try:
library = load_verified_library(library_dir)
manifest = library["manifest"]
entries = library["entries"]
identity = {key: manifest[key] for key in ("content_sha256", "source_repo_commit", "versions")}
failure = None
except LibraryValidationError as error:
entries = []
identity = {"content_sha256": error.content_hash}
failure = "library_validation_failed"
output = []
for claim in claims:
claim_id = claim.get("claim_id")
domain = claim.get("domain")
deciding = claim.get("deciding_techniques")
if not isinstance(deciding, list):
deciding = []
counted = set()
traces = [_technique_trace(raw if isinstance(raw, dict) else {}, domain, entries, counted) for raw in deciding]
statuses = {trace["status"] for trace in traces}
if failure:
status, reason = "insufficient", failure
elif not traces:
status, reason = "insufficient", "no_deciding_techniques"
elif "conflict" in statuses:
status, reason = "conflict", "deciding_technique_conflict"
elif statuses == {"matched"}:
status, reason = "matched", "all_deciding_techniques_supported"
else:
status, reason = "insufficient", "deciding_technique_insufficient"
fingerprint = _canonical_hash({"library": identity, "domain": domain, "facts_fingerprint": facts_fingerprint,
"techniques": [{"technique_id": trace["technique_id"], **trace["execution_receipt"]} for trace in traces]})
output.append({"claim_id": claim_id, "domain": domain, "status": status, "reason": reason,
"trace": {"claim_id": claim_id, "techniques": traces}, "match_fingerprint": fingerprint,
"event_calibration": "not_done", "live_web": "not_available"})
return output
def summary(entries: List[Dict[str, Any]]) -> Dict[str, Any]:
return {"total": len(entries), "by_category": dict(Counter(e["category"] for e in entries)),
"by_admission": dict(Counter(e["admission_status"] for e in entries)),
"by_review": dict(Counter(e["review"]["decision"] for e in entries)),
"by_event_calibration": dict(Counter(e["event_calibration"]["status"] for e in entries)),
"open_questions": [q["id"] for e in entries for q in e["open_questions_for_astrologer"] if q["status"] == "open"]}
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--her-export", type=Path, help="Checkout or export of the source revision pinned in VERIFIED.json")
source.add_argument("--skip-her-export", action="store_true", help="Development checks only")
parser.add_argument("--write-verified", action="store_true")
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
if args.write_verified and args.skip_her_export:
parser.error("--write-verified requires an explicit --her-export and full validation")
entries = []
errors = []
try:
raw = _library_bytes(ENTRIES_DIR, LIBRARY_DIR)
receipt = _read_receipt(LIBRARY_DIR)
files = None if args.skip_her_export else _FileIndex(args.her_export)
entries, errors = _validate_snapshot(raw, receipt, files, ROOT)
if files is not None and not errors:
source_revision = _validate_source_pin(files, receipt)
if args.write_verified and not errors:
_write_manifest(LIBRARY_DIR / "VERIFIED.json", {
"schema": MANIFEST_SCHEMA, "content_sha256": _content_hash(raw),
"source_repo_commit": source_revision, "source_files": files.hashes(),
"versions": _versions(raw, receipt), "generated_at": datetime.now(timezone.utc).isoformat(),
})
except (OSError, ValueError, KeyError, TypeError, AttributeError, subprocess.CalledProcessError) as error:
errors.append(str(error))
report = {"errors": errors, "summary": summary(entries)}
print(json.dumps(report, ensure_ascii=False, indent=1) if args.json else
"\n".join(errors) or f"ok: {report['summary']}")
return 1 if errors else 0
if __name__ == "__main__":
raise SystemExit(main())