Claude Fable 5
Deploy v20: engine-driven UI + SES email delivery (replaces v8 prompt wrapper)
7fd88a5 verified Download scripts/opposition_tierra.py from railnexus/value: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/railnexus/value/resolve/main/scripts/opposition_tierra.py
- Command line
-
hf download hf://spaces/railnexus/value/scripts/opposition_tierra.py
-
curl -L -o opposition_tierra.py https://huggingface.co/spaces/railnexus/value/resolve/main/scripts/opposition_tierra.py
13.4 kB
| #!/usr/bin/env python3 | |
| """Opposition Tierra deterministic evidence-pack reviewer. | |
| Usage: | |
| python scripts/opposition_tierra.py --input analysis_pack.json | |
| python scripts/opposition_tierra.py --input analysis_pack.json --output result.json | |
| The script never fetches data and never validates legal truth. It detects missing | |
| provenance, stale/fallback market inputs, unsupported claims, incomplete calculation | |
| records, and unresolved gaps so an independent opposing agent can focus its review. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from agent_version import AGENT_VERSION # noqa: E402 | |
| SCHEMA_VERSION = ".".join(AGENT_VERSION.split(".")[:2]) | |
| SEVERITY_ORDER = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3} | |
| def parse_timestamp(value: str) -> datetime | None: | |
| """Parse an ISO-8601 timestamp and normalize it to UTC.""" | |
| if not value: | |
| return None | |
| try: | |
| parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) | |
| except ValueError: | |
| return None | |
| if parsed.tzinfo is None: | |
| parsed = parsed.replace(tzinfo=timezone.utc) | |
| return parsed.astimezone(timezone.utc) | |
| def parse_data_date(value: str) -> datetime | None: | |
| """Parse ISO dates plus common annual/quarterly/monthly publication labels. | |
| Accepted labels (case-insensitive, separator optional): | |
| ``Q4 2025``, ``2025 Q4``, ``T4 2025``, ``2025 T4`` (INE Tempus quarterly | |
| ``NombrePeriodo`` as emitted by ``update_market_data.latest_ine_period``), | |
| ``2025 M09``, ``2025-09`` (monthly) and bare ``2025`` (annual). | |
| v15 only parsed ``Q4 2025`` and ``2025``; the ``2025 T4`` label produced by | |
| its own collector therefore raised SRC-008 against a genuinely LIVE INE record. | |
| """ | |
| text = value.strip() | |
| parsed = parse_timestamp(text) | |
| if parsed is not None: | |
| return parsed | |
| quarter = (re.fullmatch(r"[QT]([1-4])[\s\-/]*(\d{4})", text, re.IGNORECASE) | |
| or re.fullmatch(r"(\d{4})[\s\-/]*[QT]([1-4])", text, re.IGNORECASE)) | |
| if quarter: | |
| a, b = quarter.groups() | |
| q, year = (int(a), int(b)) if len(a) == 1 else (int(b), int(a)) | |
| return datetime(year, q * 3, 28, tzinfo=timezone.utc) | |
| month = (re.fullmatch(r"(\d{4})[\s\-/]*M?(\d{1,2})", text, re.IGNORECASE)) | |
| if month and 1 <= int(month.group(2)) <= 12: | |
| return datetime(int(month.group(1)), int(month.group(2)), 28, tzinfo=timezone.utc) | |
| year = re.fullmatch(r"(\d{4})", text) | |
| if year: | |
| return datetime(int(year.group(1)), 12, 31, tzinfo=timezone.utc) | |
| return None | |
| def add_challenge(challenges: list[dict[str, Any]], code: str, severity: str, | |
| message: str, remediation: str) -> None: | |
| """Append a normalized challenge record.""" | |
| challenges.append({ | |
| "code": code, | |
| "severity": severity, | |
| "resolution": "UNRESOLVED", | |
| "message": message, | |
| "remediation": remediation, | |
| }) | |
| def review_sources(pack: dict[str, Any], challenges: list[dict[str, Any]], | |
| max_market_age_hours: float, max_market_data_age_days: float, | |
| now: datetime) -> set[str]: | |
| """Validate source identity, live status, URL, and freshness.""" | |
| source_ids: set[str] = set() | |
| sources = pack.get("sources") | |
| if not isinstance(sources, list) or not sources: | |
| add_challenge(challenges, "SRC-001", "CRITICAL", "No sources supplied.", | |
| "Attach source records with IDs, URLs, status, and timestamps.") | |
| return source_ids | |
| for index, source in enumerate(sources): | |
| if not isinstance(source, dict): | |
| add_challenge(challenges, "SRC-002", "HIGH", | |
| f"Source {index} is not an object.", | |
| "Normalize every source as a structured object.") | |
| continue | |
| source_id = str(source.get("id", "")).strip() | |
| if source_id: | |
| source_ids.add(source_id) | |
| else: | |
| add_challenge(challenges, "SRC-003", "HIGH", | |
| f"Source {index} has no stable ID.", | |
| "Assign a unique source ID and link claims to it.") | |
| if not str(source.get("url", "")).startswith(("https://", "http://")): | |
| add_challenge(challenges, "SRC-004", "HIGH", | |
| f"Source {source_id or index} has no valid URL.", | |
| "Record the exact retrieval URL.") | |
| status = str(source.get("status", "")).upper() | |
| if status not in {"LIVE", "OK", "SUCCESS"}: | |
| # v17: carry the collector's own reason (e.g. "INE table 80270 is | |
| # stale: ...") so a STALE source is not confused with normal lag. | |
| reason = str(source.get("error", "")).strip() | |
| add_challenge(challenges, "SRC-005", "HIGH", | |
| f"Source {source_id or index} is not live: {status or 'missing'}." | |
| + (f" Reason: {reason}" if reason else ""), | |
| "Refresh it or make the conclusion conditional.") | |
| retrieved = parse_timestamp(str(source.get("retrieved_at", ""))) | |
| if retrieved is None: | |
| add_challenge(challenges, "SRC-006", "HIGH", | |
| f"Source {source_id or index} has no valid retrieval time.", | |
| "Store an ISO-8601 UTC retrieval timestamp.") | |
| elif source.get("kind") == "market": | |
| age_hours = (now - retrieved).total_seconds() / 3600 | |
| if age_hours > max_market_age_hours: | |
| add_challenge(challenges, "SRC-007", "HIGH", | |
| f"Market source {source_id or index} is {age_hours:.1f} hours old.", | |
| "Download a fresh snapshot or disclose stale data.") | |
| if source.get("kind") == "market" and status in {"LIVE", "OK", "SUCCESS"}: | |
| data_date_value = str(source.get("data_date", "")).strip() | |
| data_date = parse_data_date(data_date_value) | |
| if data_date is None: | |
| add_challenge(challenges, "SRC-008", "HIGH", | |
| f"Market source {source_id or index} has no valid source data date.", | |
| "Record the observation/publication period, not only retrieval time.") | |
| else: | |
| data_age_days = (now - data_date).total_seconds() / 86400 | |
| if data_age_days > max_market_data_age_days: | |
| add_challenge(challenges, "SRC-009", "HIGH", | |
| f"Market source {source_id or index} data is {data_age_days:.0f} days old.", | |
| "Download a current observation or block the current-market conclusion.") | |
| market_sources = [source for source in sources if isinstance(source, dict) | |
| and source.get("kind") == "market"] | |
| if market_sources: | |
| price_roles = {"asking_price", "transaction_price", "valuation_price"} | |
| live_price_sources = [source for source in market_sources | |
| if str(source.get("status", "")).upper() in {"LIVE", "OK", "SUCCESS"} | |
| and source.get("role") in price_roles] | |
| if not live_price_sources: | |
| add_challenge(challenges, "SRC-010", "HIGH", | |
| "No live web source supplies an actual price observation.", | |
| "Add live asking, transaction, or valuation prices; an index alone is insufficient.") | |
| return source_ids | |
| def review_claims(pack: dict[str, Any], source_ids: set[str], | |
| challenges: list[dict[str, Any]]) -> None: | |
| """Detect claims with no evidence or references to unknown sources.""" | |
| claims = pack.get("claims") | |
| if not isinstance(claims, list) or not claims: | |
| add_challenge(challenges, "CLM-001", "HIGH", "No structured claims supplied.", | |
| "List material claims and their evidence IDs.") | |
| return | |
| for index, claim in enumerate(claims): | |
| if not isinstance(claim, dict): | |
| add_challenge(challenges, "CLM-002", "MEDIUM", | |
| f"Claim {index} is not an object.", "Normalize the claim record.") | |
| continue | |
| evidence_ids = claim.get("evidence_ids", []) | |
| if not evidence_ids: | |
| add_challenge(challenges, "CLM-003", "HIGH", | |
| f"Claim {claim.get('id', index)} has no evidence.", | |
| "Link the claim to at least one source or withdraw it.") | |
| continue | |
| unknown = sorted(set(map(str, evidence_ids)) - source_ids) | |
| if unknown: | |
| add_challenge(challenges, "CLM-004", "HIGH", | |
| f"Claim {claim.get('id', index)} references unknown sources: {unknown}.", | |
| "Add the source records or remove unsupported references.") | |
| def review_calculations(pack: dict[str, Any], challenges: list[dict[str, Any]]) -> None: | |
| """Require reproducible formula, inputs, units, and result records.""" | |
| calculations = pack.get("calculations", []) | |
| if not isinstance(calculations, list): | |
| add_challenge(challenges, "CALC-001", "HIGH", "Calculations are not a list.", | |
| "Provide structured calculation records.") | |
| return | |
| required = {"formula", "inputs", "units", "result"} | |
| for index, calc in enumerate(calculations): | |
| if not isinstance(calc, dict): | |
| add_challenge(challenges, "CALC-002", "HIGH", | |
| f"Calculation {index} is not an object.", | |
| "Provide formula, inputs, units, and result.") | |
| continue | |
| missing = sorted(key for key in required if calc.get(key) in (None, "", {})) | |
| if missing: | |
| add_challenge(challenges, "CALC-003", "HIGH", | |
| f"Calculation {calc.get('id', index)} misses {missing}.", | |
| "Make the calculation independently reproducible.") | |
| def review_pack(pack: dict[str, Any], max_market_age_hours: float = 24.0, | |
| max_market_data_age_days: float = 180.0, | |
| now: datetime | None = None) -> dict[str, Any]: | |
| """Return the deterministic Opposition Tierra verdict and challenge register.""" | |
| review_time = now or datetime.now(timezone.utc) | |
| challenges: list[dict[str, Any]] = [] | |
| if not str(pack.get("conclusion", "")).strip(): | |
| add_challenge(challenges, "PACK-001", "CRITICAL", "No conclusion supplied.", | |
| "State the provisional conclusion to be challenged.") | |
| if not str(pack.get("jurisdiction", "")).strip(): | |
| add_challenge(challenges, "PACK-002", "CRITICAL", "Jurisdiction is unconfirmed.", | |
| "Confirm jurisdiction before legal, tax, or market conclusions.") | |
| source_ids = review_sources(pack, challenges, max_market_age_hours, | |
| max_market_data_age_days, review_time) | |
| review_claims(pack, source_ids, challenges) | |
| review_calculations(pack, challenges) | |
| gaps = pack.get("missing_information", []) | |
| if gaps: | |
| add_challenge(challenges, "PACK-003", "MEDIUM", | |
| f"Known missing information remains: {gaps}.", | |
| "Resolve the gaps or carry them into residual dissent.") | |
| challenges.sort(key=lambda item: (SEVERITY_ORDER[item["severity"]], item["code"])) | |
| blocking = [c for c in challenges if c["severity"] in {"CRITICAL", "HIGH"}] | |
| verdict = "BLOCKED" if blocking else ("CONDITIONAL" if challenges else "PASS") | |
| return { | |
| "schema_version": SCHEMA_VERSION, | |
| "agent_version": AGENT_VERSION, | |
| "reviewed_at": review_time.isoformat().replace("+00:00", "Z"), | |
| "reviewer": "Opposition Tierra", | |
| "verdict": verdict, | |
| "green_allowed": not blocking, | |
| "challenge_count": len(challenges), | |
| "challenges": challenges, | |
| "residual_dissent": [c["message"] for c in challenges], | |
| } | |
| def build_parser() -> argparse.ArgumentParser: | |
| """Build the side-effect-free CLI parser.""" | |
| parser = argparse.ArgumentParser(description="Opposition Tierra evidence-pack reviewer") | |
| parser.add_argument("--input", required=True, help="Input evidence-pack JSON") | |
| parser.add_argument("--output", help="Optional result JSON; defaults to stdout") | |
| parser.add_argument("--max-market-age-hours", type=float, default=24.0) | |
| parser.add_argument("--max-market-data-age-days", type=float, default=180.0) | |
| return parser | |
| def main() -> int: | |
| """Run the CLI and return a process exit code.""" | |
| args = build_parser().parse_args() | |
| try: | |
| pack = json.loads(Path(args.input).read_text(encoding="utf-8")) | |
| result = review_pack(pack, args.max_market_age_hours, | |
| args.max_market_data_age_days) | |
| except (OSError, json.JSONDecodeError, TypeError) as exc: | |
| print(json.dumps({"verdict": "ERROR", "error": str(exc)}, ensure_ascii=False)) | |
| return 2 | |
| rendered = json.dumps(result, ensure_ascii=False, indent=2) | |
| if args.output: | |
| Path(args.output).write_text(rendered + "\n", encoding="utf-8") | |
| else: | |
| print(rendered) | |
| return 0 if result["verdict"] == "PASS" else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |