"""Small private monitoring receipts, never publication authority or approval. Reads retained evidence and fixed public APIs. The optional upload writes only one isolated watchdog key. No models, journal writes, dispatches or retries. """ from __future__ import annotations import argparse import hashlib import json import os import re import sqlite3 import time from datetime import UTC, date, datetime, timedelta from pathlib import Path from zoneinfo import ZoneInfo import requests PREFIX = "watchdog:v1:outcome:" MAX_RECEIPT = 8192 MAX_PUBLIC = 4 * 1024 * 1024 MODES = {"scheduled", "weekly", "preflight", "watchdog_probe", "release_recovery"} DECISIONS = {"approve", "revise", "hold"} HASH = re.compile(r"[a-f0-9]{64}") def friday_for_week(now: datetime) -> date: day = now.astimezone(ZoneInfo("Europe/Berlin")).date() return day + timedelta(days=4 - day.weekday()) def selected_friday(now: datetime, *, action: str = "", target: str = "") -> date: """Bind actual weekly work to its selected week, including late recovery.""" if action == target == "": return friday_for_week(now) if action not in {"prepare", "recover", "file", "noop", "prepare_correction", "preflight"} or not target: raise ValueError("invalid_outcome_selection") if re.fullmatch(r"correction-[a-f0-9]{24}", target): if action not in {"prepare_correction", "recover", "file"}: raise ValueError("invalid_outcome_selection") # A correction alone does not select a weekly edition. A later weekly # continuation is passed instead by the workflow when one was selected. return friday_for_week(now) selected = date.fromisoformat(target) if selected.isoformat() != target or selected.weekday() != 4 or action == "prepare_correction": raise ValueError("invalid_outcome_selection") # Preflight's selector carries the last due Friday, while Thursday readiness # deliberately monitors the upcoming one. Recovery in preflight mode still # has action=recover/file and must keep its actual selected week. return friday_for_week(now) if action == "preflight" else selected def _json(path: Path) -> dict: if path.is_symlink() or not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: raise ValueError("invalid_local_evidence") value = json.loads(path.read_text(encoding="utf-8-sig")) if not isinstance(value, dict): raise ValueError("invalid_local_evidence") return value def _reference(bundle: Path, reference: str) -> Path: if not isinstance(reference, str) or not reference.startswith("bundle:"): raise ValueError("invalid_evidence_reference") path = bundle / reference.removeprefix("bundle:") if not path.resolve().is_relative_to(bundle) or any(part.is_symlink() for part in (path, *path.parents) if part != bundle.parent): raise ValueError("invalid_evidence_reference") return path def _timestamp(value: str) -> str: instant = datetime.fromisoformat(value.replace("Z", "+00:00")) if instant.tzinfo is None: raise ValueError("undated_evidence") return instant.astimezone(UTC).isoformat() def workflow_identity(env: dict, mode: str) -> dict: if mode not in MODES or env.get("GITHUB_REPOSITORY") != "Kilian-n/PRISM": raise ValueError("unexpected_workflow") values = {} for source, key in (("GITHUB_RUN_ID", "run_id"), ("GITHUB_RUN_ATTEMPT", "run_attempt")): raw = env.get(source, "") if not re.fullmatch(r"[1-9][0-9]{0,15}", raw) or int(raw) > 2**53 - 1: raise ValueError("invalid_workflow_identity") values[key] = int(raw) event = env.get("GITHUB_EVENT_NAME") if mode == "release_recovery": # This is automatic recovery following an operator-reviewed release, # not proof of an intervention-free Friday cycle. The workflow's gate # and durable claim validate authorization; this receipt records it. if event != "workflow_run" or values["run_attempt"] != 1: raise ValueError("unexpected_release_recovery_event") provenance = {} for source, key in (("LEDECAF_RELEASE_CI_RUN_ID", "ci_run_id"), ("LEDECAF_RELEASE_PR", "pull_request")): raw = env.get(source, "") if not re.fullmatch(r"[1-9][0-9]{0,15}", raw) or int(raw) > 2**53 - 1: raise ValueError("invalid_release_recovery_identity") provenance[key] = int(raw) tested = env.get("LEDECAF_RELEASE_SHA", "") actual = env.get("LEDECAF_ACTUAL_CHECKOUT", "") ticket = env.get("LEDECAF_RELEASE_TICKET_IDENTITY", "") if not re.fullmatch(r"[a-f0-9]{40}", tested) or actual != tested or not HASH.fullmatch(ticket): raise ValueError("invalid_release_recovery_identity") return {**values, "event": event, "mode": mode, "origin": "reviewed_release_recovery", "release": {**provenance, "tested_sha": tested, "actual_checkout": actual, "ticket_identity": ticket}} if event not in {"schedule", "workflow_dispatch"}: raise ValueError("unexpected_workflow_event") return {**values, "event": event, "mode": mode} def public_json(locale: str) -> dict: if locale not in {"fr", "en"}: raise ValueError("invalid_locale") # Fixed origin only. No redirects, proxy credentials, cookies or retries. with requests.Session() as session: session.trust_env = False with session.get(f"https://ledecaf.com/api/v2/issues/current?locale={locale}", headers={"Accept": "application/json", "Cache-Control": "no-cache", "User-Agent": "LeDecaf-Weekly-Outcome/1.0"}, allow_redirects=False, stream=True, timeout=8) as response: if response.status_code != 200 or response.headers.get("Content-Type", "").split(";")[0] != "application/json": raise ValueError("public_identity_unavailable") content, deadline = bytearray(), time.monotonic() + 12 for chunk in response.iter_content(65536): content.extend(chunk) if len(content) > MAX_PUBLIC or time.monotonic() > deadline: raise ValueError("public_response_limit") return json.loads(content) def _published_identity(bundle: Path, run: dict, packet: dict, digest: str) -> int: from sqlalchemy import create_engine from sqlalchemy.orm import Session from sqlalchemy.pool import NullPool from prism.issue_numbering import public_number from prism.models import Edition database, wal = bundle / "prism.db", bundle / "prism.db-wal" if (database.is_symlink() or not database.is_file() or wal.is_symlink() or (wal.exists() and (not wal.is_file() or wal.stat().st_size))): raise ValueError("unsettled_publication_database") engine = create_engine("sqlite://", creator=lambda: sqlite3.connect(database.as_uri() + "?mode=ro&immutable=1", uri=True), poolclass=NullPool) try: with Session(engine, autoflush=False) as session: issue = session.query(Edition).filter_by(number=run.get("issue"), status="published").one_or_none() build = (json.loads(issue.payload_json).get("build") or {}) if issue else {} if (issue is None or str(issue.week_start) != packet["week_start"] or str(issue.week_end) != packet["week_end"] or (build.get("publication_review") or {}).get("packet_sha256") != digest): raise ValueError("published_identity_mismatch") return public_number(issue, session) finally: engine.dispose() def collect(bundle: Path, *, target: date, workflow: dict, job_status: str, auth_checkpoint: str, publication_checkpoint: str, fetcher=public_json, now: datetime | None = None) -> dict: from ops.reporting_memory import load_review_record from prism.autonomous import packet_hash, validate_reviews now = now or datetime.now(UTC) if target.weekday() != 4 or job_status not in {"success", "failure", "cancelled"}: raise ValueError("invalid_outcome_request") bundle = bundle.resolve() result = {"schema": 1, "target": target.isoformat(), "observed_at": now.isoformat(), "workflow": workflow, "job_status": job_status, "status": "not_started", "reviews": {}, "live_verified_locales": [], "auth_checkpoint": auth_checkpoint == "success", "publication_checkpoint": publication_checkpoint == "success", "scope": "Retained review decisions and fresh public identity checks; not a new factual review."} try: state = _json(bundle / "state.json") if state.get("schema_version") != 1 or not isinstance(state.get("runs"), dict): raise ValueError("invalid_retained_state") run = state.get("runs", {}).get(target.isoformat()) if not run: return result if run.get("run_kind", "weekly") != "weekly" or run.get("target_friday") != target.isoformat(): raise ValueError("wrong_weekly_target") result["status"] = "failed" if run.get("status") == "failed" else "incomplete" held = run.get("stage") == "draft_retired" digest = run.get("held_packet_sha256") if held else run.get("packet_sha256") reference = run.get("held_reporting_record") if held else run.get("reporting_record") if not digest or not reference: return result if not isinstance(digest, str) or not HASH.fullmatch(digest): raise ValueError("invalid_packet_identity") manifest, artifacts = load_review_record(_reference(bundle, reference)) packet = json.loads(artifacts["packet.json"]) packet_path = _reference(bundle, run.get("held_packet_path") if held else run.get("packet_path")) if (manifest["packet_sha256"] != digest or packet_hash(packet) != digest or packet_path.read_bytes() != artifacts["packet.json"] or packet.get("research_as_of") != target.isoformat() or packet.get("week_start") != (target - timedelta(days=4)).isoformat() or packet.get("week_end") != (target + timedelta(days=2)).isoformat() or packet.get("edition_kind") == "retrospective"): raise ValueError("retained_packet_mismatch") result.update(packet_sha256=digest, prepared_at=_timestamp(packet["prepared_at"])) reports = [] for role in ("facts", "editorial"): raw = artifacts[f"{role}.report.json"] report = json.loads(raw) if (report.get("role") != role or report.get("packet_sha256") != digest or report.get("decision") not in DECISIONS): raise ValueError("retained_review_mismatch") if not held and _reference(bundle, run.get("review_paths", {}).get(role)).read_bytes() != raw: raise ValueError("retained_review_mismatch") reports.append(report) result["reviews"][role] = {"decision": report["decision"], "sha256": hashlib.sha256(raw).hexdigest(), "completed_at": _timestamp(report["completed_at"])} if any(report["decision"] != "approve" for report in reports): result["status"] = "held" return result validate_reviews(packet, reports, now=now) result["status"] = "approved_pending_publication" if (run.get("status") != "complete" or run.get("phase") != "published" or run.get("live_verified_locales") != ["fr", "en"]): return result number = _published_identity(bundle, run, packet, digest) result.update(internal_issue=run["issue"], public_issue=number, publication_completed_at=_timestamp(run["updated_at"])) for locale in ("fr", "en"): body = fetcher(locale) issue = body.get("issue") or {} publication = issue.get("publication") or {} if (body.get("version") != "2" or issue.get("number") != number or issue.get("locale") != locale or issue.get("status") != "published" or issue.get("title") != packet[locale]["title"] or (issue.get("publication_review") or {}).get("packet_sha256") != digest or publication.get("research_as_of") != target.isoformat() or publication.get("week_start") != packet["week_start"] or publication.get("week_end") != packet["week_end"]): raise ValueError("live_identity_mismatch") result["live_verified_locales"].append(locale) result["status"] = "published" result["live_checked_at"] = datetime.now(UTC).isoformat() except Exception: # Monitoring cannot publish, repair evidence or reveal arbitrary errors. result.update(status="evidence_unavailable", error="outcome_evidence_could_not_be_verified") return result def publish(receipt: dict, env: dict, *, request=requests.request) -> None: account, namespace = env["CLOUDFLARE_ACCOUNT_ID"], env["LEDECAF_STATE_NAMESPACE"] if not all(re.fullmatch(r"[a-f0-9]{32}", value) for value in (account, namespace)): raise ValueError("invalid_monitor_storage") data = json.dumps(receipt, ensure_ascii=True, separators=(",", ":")).encode() if len(data) > MAX_RECEIPT: raise ValueError("outcome_receipt_too_large") identity = receipt["workflow"] target = date.fromisoformat(receipt["target"]) if (target.isoformat() != receipt["target"] or target.weekday() != 4 or any(type(identity.get(key)) is not int or not 1 <= identity[key] <= 2**53 - 1 for key in ("run_id", "run_attempt"))): raise ValueError("invalid_outcome_storage_identity") key = f"{PREFIX}{receipt['target']}:{identity['run_id']}:{identity['run_attempt']}" url = f"https://api.cloudflare.com/client/v4/accounts/{account}/storage/kv/namespaces/{namespace}/values/{key}" response = request("PUT", url, params={"expiration_ttl": 90 * 86400}, data=data, headers={"Authorization": "Bearer " + env["CLOUDFLARE_API_TOKEN"], "Content-Type": "application/json"}, timeout=12, allow_redirects=False) if response.status_code != 200 or response.json().get("success") is not True: raise ValueError("outcome_storage_unavailable") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bundle", type=Path, required=True) parser.add_argument("--mode", choices=sorted(MODES), required=True) parser.add_argument("--selected-action", default="") parser.add_argument("--selected-target", default="") parser.add_argument("--job-status", required=True) parser.add_argument("--auth-checkpoint", default="") parser.add_argument("--publication-checkpoint", default="") parser.add_argument("--publish", action="store_true") args = parser.parse_args() try: now = datetime.now(UTC) target = selected_friday(now, action=args.selected_action, target=args.selected_target) result = collect(args.bundle, target=target, workflow=workflow_identity(os.environ, args.mode), job_status=args.job_status, auth_checkpoint=args.auth_checkpoint, publication_checkpoint=args.publication_checkpoint, now=now) if args.publish: publish(result, os.environ) print(json.dumps(result, ensure_ascii=True, separators=(",", ":"))) return int(result["status"] == "evidence_unavailable") except Exception: print('{"status":"unavailable","reason":"weekly_outcome_monitor_could_not_complete"}') return 1 if __name__ == "__main__": raise SystemExit(main())