#!/usr/bin/env python3 """ Validate UnsolvedAstronomy v1.1.0 root files against all 12 Publication Gates (Section 3 & Section 13.1 of unsolvedastronomy.md). """ import json import re import sys from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parent.parent LOOKUPS_DIR = ROOT / "data" / "lookups" def load_jsonl(path: Path) -> list[dict]: if not path.exists(): return [] out = [] with path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue out.append(json.loads(line)) return out def load_json_array(path: Path) -> list[dict]: if not path.exists(): return [] return json.loads(path.read_text(encoding="utf-8")) def validate() -> dict: errors = [] warnings = [] categories = json.loads((LOOKUPS_DIR / "categories.json").read_text(encoding="utf-8")) cat_map = {c["id"]: c for c in categories} cat_targets = {c["id"]: c["target_records"] for c in categories} gold_targets = {c["id"]: c["gold_seed_target"] for c in categories} difficulties = json.loads((LOOKUPS_DIR / "difficulty_levels.json").read_text(encoding="utf-8")) diff_ids = {d["id"] for d in difficulties} qtypes_vocab = {q["id"] if isinstance(q, dict) else q for q in json.loads((LOOKUPS_DIR / "question_types.json").read_text(encoding="utf-8"))} obj_vocab = set(json.loads((LOOKUPS_DIR / "object_classes.json").read_text(encoding="utf-8"))) scales_vocab = set(json.loads((LOOKUPS_DIR / "scales.json").read_text(encoding="utf-8"))) wave_vocab = set(json.loads((LOOKUPS_DIR / "wavelengths_and_messengers.json").read_text(encoding="utf-8"))) ev_vocab = set(json.loads((LOOKUPS_DIR / "evidence_states.json").read_text(encoding="utf-8"))) cons_vocab = set(json.loads((LOOKUPS_DIR / "consensus_states.json").read_text(encoding="utf-8"))) rej_vocab = set(json.loads((LOOKUPS_DIR / "rejection_codes.json").read_text(encoding="utf-8"))) sources = load_json_array(ROOT / "source_registry.json") if not sources: errors.append("source_registry.json is missing or empty.") source_map = {s["source_id"]: s for s in sources} for s in sources: sid = s.get("source_id", "UNKNOWN") if not re.match(r"^SRC-AST-\d{6}$", str(sid)): errors.append(f"Invalid source_id format: {sid}") for req in ("source_id", "title", "authors", "year", "source_type", "venue", "tier", "license_note", "verbatim_reuse_allowed"): if req not in s: errors.append(f"Source {sid} missing required field '{req}'") if not any(s.get(k) for k in ("doi", "ads_bibcode", "arxiv_id", "isbn", "url")): errors.append(f"Source {sid} lacks persistent identifier (doi/ads_bibcode/arxiv_id/isbn/url)") published_problems = load_json_array(ROOT / "problems.json") archived_problems = load_json_array(ROOT / "archived_problems.json") all_problems = published_problems + archived_problems if not published_problems: errors.append("problems.json is missing or empty.") expected_pub = sum(cat_targets.values()) if len(published_problems) != expected_pub: errors.append(f"Expected {expected_pub:,} published open/partially_solved problems, got {len(published_problems)}") if len(archived_problems) != 80: errors.append(f"Expected 80 archived/audit problems, got {len(archived_problems)}") seen_ids = set() seen_norm_stmts = {} seen_norm_titles = {} pub_source_counts = Counter() pub_cat_counts = Counter() gold_cat_counts = Counter() all_id_set = {p.get("id") for p in all_problems} for p in all_problems: pid = p.get("id", "UNKNOWN") st = p.get("status") is_pub = st in ("open", "partially_solved") if pid in seen_ids: errors.append(f"Duplicate id: {pid}") seen_ids.add(pid) if not re.match(r"^UAST-\d{6}$", str(pid)): errors.append(f"{pid}: invalid id format") # Gate 1: Provenance Gate srcs = p.get("sources") or [] if not srcs: errors.append(f"{pid}: empty sources list") for s_ref in srcs: sid = s_ref.get("source_id") if sid not in source_map: errors.append(f"{pid}: source_id '{sid}' not found in registry") if s_ref.get("support_type") not in ("direct_open_question", "explicit_open_gap_paraphrased", "historical_context", "status_update"): errors.append(f"{pid}: invalid support_type '{s_ref.get('support_type')}'") if not s_ref.get("locator"): errors.append(f"{pid}: missing locator in source reference") if s_ref.get("verbatim_quote_used") and not source_map.get(sid, {}).get("verbatim_reuse_allowed"): errors.append(f"{pid}: verbatim_quote_used=true on source {sid} without verbatim_reuse_allowed") if is_pub: distinct_sids = {s_ref.get("source_id") for s_ref in srcs if s_ref.get("source_id")} if len(srcs) < 4 or len(distinct_sids) < 4: errors.append(f"{pid}: published record in v1.1 must have >= 4 distinct literature sources, got {len(distinct_sids)}") # Gate 2 & 10: Category, Subcategory, Question Type, Object Classes, Scales, Wavelengths cnum = p.get("category_number") if cnum not in cat_map: errors.append(f"{pid}: invalid category_number {cnum}") else: valid_subcats = set(cat_map[cnum]["subcategories"]) if p.get("subcategory") not in valid_subcats: errors.append(f"{pid}: subcategory '{p.get('subcategory')}' not in category {cnum} subcategories") if p.get("question_type") not in qtypes_vocab: errors.append(f"{pid}: invalid question_type '{p.get('question_type')}'") objs = p.get("object_classes") or [] if not objs or any(o not in obj_vocab for o in objs): errors.append(f"{pid}: invalid or empty object_classes {objs}") scs = p.get("scales") or [] if not scs or any(sc not in scales_vocab for sc in scs): errors.append(f"{pid}: invalid or empty scales {scs}") waves = p.get("wavelengths_and_messengers") or [] if not waves or any(w not in wave_vocab for w in waves): errors.append(f"{pid}: invalid or empty wavelengths_and_messengers {waves}") # Gate 3: Question-Form & Plain Statement Gate stmt = (p.get("statement") or "").strip() plain = (p.get("plain_statement") or "").strip() prec = (p.get("precise_statement") or "").strip() if len(stmt) < 40 or len(plain) < 30 or len(prec) < 40: errors.append(f"{pid}: statement/plain_statement/precise_statement too short") if is_pub and not stmt.endswith("?"): errors.append(f"{pid}: published statement does not end with '?'") if re.search(r"\\[a-zA-Z]+|\$", plain): errors.append(f"{pid}: plain_statement contains raw LaTeX markup: {plain[:80]}") # Gate 5 & 6: Status, Evidence, Consensus if p.get("evidence_state") not in ev_vocab: errors.append(f"{pid}: invalid evidence_state '{p.get('evidence_state')}'") if p.get("consensus_state") not in cons_vocab: errors.append(f"{pid}: invalid consensus_state '{p.get('consensus_state')}'") if not re.match(r"^\d{4}-\d{2}-\d{2}$", str(p.get("status_last_checked", ""))): errors.append(f"{pid}: invalid status_last_checked '{p.get('status_last_checked')}'") if len(p.get("status_justification") or "") < 20: errors.append(f"{pid}: status_justification too short") # Gate 7 & 8: Observational Semantics & Resolution Criteria for arr_field in ("epochs", "observables", "inferred_properties", "selection_effects", "systematic_uncertainties", "degeneracies", "competing_models", "resolution_criteria"): val = p.get(arr_field) if not isinstance(val, list) or len(val) == 0: errors.append(f"{pid}: '{arr_field}' must be a non-empty list") if is_pub and len(p.get("resolution_criteria") or []) < 2: errors.append(f"{pid}: published problem requires >= 2 resolution_criteria") if len(p.get("falsifiability_or_discriminant") or "") < 20: errors.append(f"{pid}: falsifiability_or_discriminant too short") # Gate 9: Deduplication & Archive Review if is_pub: norm = re.sub(r"[^a-z0-9]+", " ", stmt.lower()).strip() if norm in seen_norm_stmts: errors.append(f"{pid}: duplicate normalized statement of {seen_norm_stmts[norm]}") seen_norm_stmts[norm] = pid norm_t = re.sub(r"[^a-z0-9]+", " ", (p.get("title") or "").lower()).strip() if norm_t in seen_norm_titles: errors.append(f"{pid}: duplicate normalized title of {seen_norm_titles[norm_t]}") seen_norm_titles[norm_t] = pid pub_source_counts[srcs[0]["source_id"]] += 1 pub_cat_counts[cnum] += 1 if p.get("is_gold_seed"): gold_cat_counts[cnum] += 1 else: rc = p.get("rejection_code") if rc not in rej_vocab: errors.append(f"{pid}: archived record has invalid rejection_code '{rc}'") if st == "merged_duplicate": dup_target = p.get("duplicate_of") if not dup_target or dup_target not in all_id_set: errors.append(f"{pid}: merged_duplicate record has invalid duplicate_of '{dup_target}'") if p.get("difficulty_level") not in diff_ids: errors.append(f"{pid}: invalid difficulty_level {p.get('difficulty_level')}") # Verify category quotas and Gold Seed quotas for cid, target in cat_targets.items(): if pub_cat_counts[cid] != target: errors.append(f"Category {cid} count {pub_cat_counts[cid]} != target {target}") for cid, gtarget in gold_targets.items(): if gold_cat_counts[cid] != gtarget: errors.append(f"Category {cid} Gold Seed count {gold_cat_counts[cid]} != target {gtarget}") # Gate 12: Source Diversity Gate (max 2.0% of published records per single source) max_per_source = int(0.02 * len(published_problems)) for sid, cnt in pub_source_counts.items(): if cnt > max_per_source: errors.append(f"Source {sid} contributes {cnt} published problems, exceeding 2% cap ({max_per_source})") # Relations check relations = load_jsonl(ROOT / "relations.jsonl") if not relations: errors.append("relations.jsonl is missing or empty.") for rel in relations: if rel.get("source_problem_id") not in all_id_set or rel.get("target_problem_id") not in all_id_set: errors.append(f"Relation {rel.get('relation_id')} references unknown problem ID") # Audits check for audit_file in ("research_results.json", "statement_audit.json"): rows = load_json_array(ROOT / audit_file) if not rows: errors.append(f"{audit_file} is missing or empty") return { "valid": len(errors) == 0, "error_count": len(errors), "warning_count": len(warnings), "errors": errors[:50], "warnings": warnings[:50], "published_count": len(published_problems), "archived_count": len(archived_problems), "gold_seed_count": sum(gold_cat_counts.values()), "distinct_sources_count": len(sources), "max_single_source_share_pct": round(100.0 * max(pub_source_counts.values(), default=0) / max(1, len(published_problems)), 3), "category_counts": dict(sorted(pub_cat_counts.items())), "gold_category_counts": dict(sorted(gold_cat_counts.items())), } if __name__ == "__main__": res = validate() print(json.dumps(res, indent=2)) if not res["valid"]: sys.exit(1)