File size: 13,434 Bytes
7fd88a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | #!/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())
|