"""Deterministic 5-state BibTeX & Crossref DOI verification CLI.""" from __future__ import annotations import argparse import json import re import sys import urllib.error import urllib.parse import urllib.request from collections import Counter from pathlib import Path from typing import Any, Callable DOI_PATTERN = re.compile(r"10\.\d{4,9}/[-._;()/:A-Za-z0-9]+") ENTRY_HEAD_RE = re.compile(r"@([A-Za-z]+)\s*\{\s*([^,\s]+)\s*,") FIELD_RE = re.compile(r"([A-Za-z][A-Za-z0-9_-]*)\s*=\s*(?:\{((?:[^{}]|\{[^{}]*\})*)\}|\"([^\"]*)\"|(\d+))") def parse_bibtex(text: str) -> list[dict[str, str]]: """Parse common BibTeX entries into dicts preserving cite_key, type, and core fields.""" entries: list[dict[str, str]] = [] chunks = re.split(r"(?=@[A-Za-z]+\s*\{)", text) for chunk in chunks: head = ENTRY_HEAD_RE.match(chunk.strip()) if not head: continue entry: dict[str, str] = {"entry_type": head.group(1).lower(), "cite_key": head.group(2).strip()} body = chunk[head.end() :] for m in FIELD_RE.finditer(body): key = m.group(1).lower() val = next((g for g in m.groups()[1:] if g is not None), "") entry[key] = re.sub(r"\s+", " ", val.strip()) entries.append(entry) return entries def validate_bibtex_offline(entries: list[dict[str, str]]) -> list[str]: """Check duplicate citation keys, missing title/year, and malformed DOIs.""" issues: list[str] = [] counts = Counter(e["cite_key"] for e in entries) for key, n in counts.items(): if n > 1: issues.append(f"Duplicate BibTeX key '{key}' ({n}x).") for e in entries: key = e["cite_key"] if not e.get("title"): issues.append(f"{key}: missing 'title' field.") if not e.get("year") and not e.get("date"): issues.append(f"{key}: missing 'year' field.") doi = e.get("doi", "").strip() if doi and not DOI_PATTERN.fullmatch(doi.rstrip(".,;")): issues.append(f"{key}: malformed DOI syntax '{doi}'.") return issues def _crossref_year(msg: dict[str, Any]) -> str: for field in ("published-print", "published-online", "issued", "created"): parts = (msg.get(field) or {}).get("date-parts") or [] if parts and parts[0]: return str(parts[0][0]) return "" def _default_fetcher(url: str, timeout: float = 8.0) -> tuple[int, str]: req = urllib.request.Request( url, headers={"User-Agent": "alcyone-cite-audit/0.1.0 (https://github.com/alcyonecraft/alcyone-cite-audit)"}, ) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return int(resp.status), resp.read().decode("utf-8", errors="replace") except urllib.error.HTTPError as err: return int(err.code), "" except (urllib.error.URLError, TimeoutError, OSError): return 0, "" def audit_doi_crossref( doi: str, expected_year: str = "", expected_title: str = "", fetcher: Callable[[str, float], tuple[int, str]] | None = None, ) -> dict[str, str]: """Classify one DOI into VERIFIED, METADATA_CONFLICT, RETRACTED_OR_CONCERN, UNRESOLVED_NETWORK, or NOT_FOUND_CONFIRMED.""" clean_doi = doi.strip().rstrip(".,;") if not DOI_PATTERN.fullmatch(clean_doi): return {"doi": clean_doi, "state": "NOT_FOUND_CONFIRMED", "detail": "Invalid DOI format."} fetch = fetcher or _default_fetcher code, body = fetch(f"https://api.crossref.org/works/{urllib.parse.quote(clean_doi, safe='')}", 8.0) if code == 404: return {"doi": clean_doi, "state": "NOT_FOUND_CONFIRMED", "detail": "Crossref returned HTTP 404."} if code != 200 or not body: return {"doi": clean_doi, "state": "UNRESOLVED_NETWORK", "detail": f"HTTP status {code or 'timeout'}."} try: msg = json.loads(body).get("message") or {} except json.JSONDecodeError: return {"doi": clean_doi, "state": "UNRESOLVED_NETWORK", "detail": "Malformed Crossref JSON."} relation = msg.get("relation") or {} update_to = msg.get("update-to") or [] rel_text = json.dumps({"update_to": update_to, "relation": relation}).lower() if "retract" in rel_text or "concern" in rel_text: return {"doi": clean_doi, "state": "RETRACTED_OR_CONCERN", "detail": "Crossref flags retraction or concern."} actual_year = _crossref_year(msg) actual_title = ((msg.get("title") or [""])[0] or "").strip() if expected_year and actual_year and expected_year.strip() != actual_year: return { "doi": clean_doi, "state": "METADATA_CONFLICT", "detail": f"Year mismatch: expected {expected_year}, Crossref={actual_year}.", } if expected_title and actual_title: exp_words = set(re.findall(r"[a-z0-9]{4,}", expected_title.lower())) act_words = set(re.findall(r"[a-z0-9]{4,}", actual_title.lower())) if exp_words and act_words and not (exp_words & act_words): return { "doi": clean_doi, "state": "METADATA_CONFLICT", "detail": f"Title mismatch: Crossref='{actual_title[:80]}'.", } return {"doi": clean_doi, "state": "VERIFIED", "detail": f"{actual_year} | {actual_title[:80]}"} def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="alcyone-cite-audit", description="5-state BibTeX & Crossref DOI auditor.") parser.add_argument("file", help="Path to .bib, .tex, .md, or .txt file") parser.add_argument("--offline", action="store_true", help="Skip live Crossref HTTP lookup and run syntax/key checks") parser.add_argument("--strict", action="store_true", help="Exit 1 on offline issues, conflicts, retractions, or 404 DOIs") args = parser.parse_args(argv) target = Path(args.file) if not target.is_file(): print(f"File not found: {target}", file=sys.stderr) return 2 text = target.read_text(encoding="utf-8", errors="replace") entries = parse_bibtex(text) if target.suffix.lower() == ".bib" else [] offline_issues = validate_bibtex_offline(entries) if entries else [] print(f"Parsed {target.name}: {len(entries)} BibTeX entries, {len(offline_issues)} structural issue(s)") for iss in offline_issues: print(f" [STRUCTURAL] {iss}") bad_live = False if not args.offline: targets: list[tuple[str, str, str, str]] = [] if entries: for e in entries: if e.get("doi"): targets.append((e["cite_key"], e["doi"], e.get("year", ""), e.get("title", ""))) else: seen: set[str] = set() for doi in DOI_PATTERN.findall(text): clean = doi.rstrip(".,;") if clean not in seen: seen.add(clean) targets.append((clean, clean, "", "")) for label, doi, yr, title in targets: res = audit_doi_crossref(doi, expected_year=yr, expected_title=title) print(f" [{res['state']}] {label}: {res['detail']}") if res["state"] in {"METADATA_CONFLICT", "RETRACTED_OR_CONCERN", "NOT_FOUND_CONFIRMED"}: bad_live = True if args.strict and (offline_issues or bad_live): return 1 return 0 if __name__ == "__main__": raise SystemExit(main())