"""Read-only, date-bound newsroom history for retrospective authoring/review. Reporting dates do not establish publication. This projection deliberately has no access to today's editorial memory, mutable dossier answers or observations. """ from __future__ import annotations import copy import hashlib import json import re import sqlite3 from contextlib import closing from datetime import UTC, date, datetime, timedelta from pathlib import Path MAX_CONTEXT_BYTES = 512 * 1024 MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 MAX_RECORDS = 256 CLASSES = ("published_by_cutoff", "later_reconstructions_or_private", "excluded_later_knowledge") PACKET_PATH = re.compile(r"packets/(?:revisions/)?\d{4}-\d{2}-\d{2}(?:-r\d+)?\.json|packets/preparation-history/[0-9a-f]{64}\.json") def _hash(value: object) -> str: return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode()).hexdigest() def _cutoff(value: date | str) -> str: result = value.isoformat() if isinstance(value, date) and not isinstance(value, datetime) else value if not isinstance(result, str) or date.fromisoformat(result).isoformat() != result: raise ValueError("Historical context requires an ISO calendar cutoff") return result def _instant(value: str | None, *, database=False) -> datetime | None: if not value: return None try: result = datetime.fromisoformat(value) except (TypeError, ValueError): return None if result.tzinfo is None: # The database model's utcnow stores naive UTC. Packet metadata has no # such contract, so an ambiguous private timestamp stays unknown. return result.replace(tzinfo=UTC) if database else None return result.astimezone(UTC) def _time(value: str | None) -> str | None: result = _instant(value, database=True) return result.isoformat() if result else None def _bounded_json(path: Path, boundary: Path) -> tuple[dict, bytes]: if path.is_symlink() or not path.resolve().is_relative_to(boundary.resolve()) or not path.is_file(): raise ValueError("Historical snapshot is missing or escapes its root") if path.stat().st_size > MAX_SNAPSHOT_BYTES: raise ValueError("Historical snapshot exceeds its read budget") with path.open("rb") as stream: data = stream.read(MAX_SNAPSHOT_BYTES + 1) if len(data) > MAX_SNAPSHOT_BYTES: raise ValueError("Historical snapshot exceeds its read budget") value = json.loads(data.decode("utf-8-sig")) if not isinstance(value, dict): raise ValueError("Historical snapshot must be an object") return value, data def _copy(payload: dict, *, public: bool, later_style=False) -> dict: # Compact, whole explicit fields, not a misleading claim to reproduce every # article. The snapshot hash binds the complete localized source payload. fields = ("slug", "title", "summary", "question", "next_test", "red_thread", "thesis") result = {"title": payload.get("title"), "stories": [ {key: copy.deepcopy(story[key]) for key in fields if key in story} for story in payload.get("stories", []) ]} # Older packets can embed whole prior dossiers inside these objects. Keep # the actual question/deadline and named connection, with all source hashes # available for exact lookup, rather than recursively duplicating history. compact = { "next_test": ("test", "owner", "review_date", "scope_note"), "red_thread": ("previous", "current", "next", "previous_date", "previous_story_slug", "previous_packet_hash", "previous_prepared_at", "review_date", "owner"), "thesis": ("text", "signpost", "breaks_if"), } for story in result["stories"]: for name, keys in compact.items(): if isinstance(story.get(name), dict): story[name] = {key: story[name][key] for key in keys if key in story[name]} if public: result["sucre"] = copy.deepcopy(payload.get("sucre")) elif later_style: # No forecasts or retrospective outcome assessments enter this style # reference. This is a later-written comic predecessor, not a memory. column = payload.get("sucre") or {} result["later_written_sucre_for_style_only"] = { "classification": "later_written_style_reference_never_historical_knowledge_or_forecast_evidence", **{key: copy.deepcopy(column[key]) for key in ( "title", "afterword", "target", "mechanism_exposed", "closing_line", ) if key in column}, } return result def _database_records(database: Path, cutoff: str) -> dict: groups = {key: [] for key in CLASSES} end = datetime.combine(date.fromisoformat(cutoff) + timedelta(days=1), datetime.min.time(), UTC) week_start = (date.fromisoformat(cutoff) - timedelta(days=date.fromisoformat(cutoff).weekday())).isoformat() with closing(sqlite3.connect(Path(database).resolve().as_uri() + "?mode=ro", uri=True)) as db: db.row_factory = sqlite3.Row db.execute("PRAGMA query_only=ON") db.execute("BEGIN") for edition_row in db.execute("SELECT * FROM editions WHERE status='published' ORDER BY week_end, number"): edition = dict(edition_row) original = json.loads(edition["payload_json"] or "{}") original_build = original.get("build") or {} rows = [{**edition, "revision_no": 0, "entity_type": "edition"}] rows += [{**dict(row), "entity_type": "edition_revision"} for row in db.execute( "SELECT * FROM edition_revisions WHERE edition_id=? AND status IN ('published','superseded') ORDER BY revision_no", (edition["id"],), )] candidates = [] previous_build = None for row in rows: payload = json.loads(row["payload_json"] or "{}") build = payload.get("build") or {} revision_prepared = (build.get("prepared_at") if previous_build is not None and build.get("packet_id") and build.get("packet_id") != previous_build.get("packet_id") else None) previous_build = build published = _instant(row["published_at"], database=True) localized = {} for locale in ("fr", "en"): translation = db.execute( "SELECT content_json FROM localized_content WHERE entity_type=? AND entity_id=? AND locale=? AND status='published'", (row["entity_type"], row["id"], locale), ).fetchone() if translation: localized[locale] = json.loads(translation["content_json"])["payload"] elif build.get("content_locale", "en") == locale: localized[locale] = payload reporting_cutoff = build.get("research_as_of") or edition["week_end"] publication = { "kind": original_build.get("edition_kind"), "week_start": edition.get("week_start"), "week_end": edition["week_end"], "research_as_of": reporting_cutoff, "prepared_at": original_build.get("prepared_at"), "published_at": _time(edition["published_at"]), "revision_prepared_at": revision_prepared, "revision_published_at": _time(row["published_at"]) if row["revision_no"] else None, } metadata = { "source": "immutable_database_snapshot", "issue_number": edition["number"], "revision_no": row["revision_no"], "publication": publication, "snapshot_published_at": _time(row["published_at"]), "packet_sha256": (build.get("publication_review") or {}).get("packet_sha256") or build.get("packet_sha256"), "snapshot_sha256": _hash(localized), } if published is not None and published < end: candidates.append((published, row["revision_no"], metadata, localized)) elif isinstance(reporting_cutoff, str) and reporting_cutoff <= cutoff and published is not None: groups[CLASSES[1]].append({ **metadata, "classification": "later_publication_not_contemporary_memory", "copy": {locale: _copy(value, public=False, later_style=edition["week_end"] < week_start) for locale, value in localized.items()}, "sucre_forecasts_and_assessments_excluded": True, }) else: groups[CLASSES[2]].append({**metadata, "reason": "later_reporting_or_unknown_publication_time"}) if candidates: # Publication time determines what readers could see. A larger # identity/revision does not establish earlier availability. _, _, metadata, localized = max(candidates, key=lambda item: (item[0], item[1])) groups[CLASSES[0]].append({ **metadata, "classification": "actually_published_by_cutoff", "copy": {locale: _copy(value, public=True) for locale, value in localized.items()}, }) for _, _, prior, _ in candidates: if prior != metadata: groups[CLASSES[2]].append({**prior, "reason": "superseded_before_cutoff"}) return groups def _private_records(root: Path | None, directory: Path | None, cutoff: str, groups: dict) -> None: week_start = (date.fromisoformat(cutoff) - timedelta(days=date.fromisoformat(cutoff).weekday())).isoformat() paths, covered = [], set() if root is not None: root = Path(root).resolve(strict=True) manifest_path = root / "release-provenance.json" if manifest_path.exists() or manifest_path.is_symlink(): manifest, _ = _bounded_json(manifest_path, root) if (manifest.get("schema_version") != 1 or manifest.get("historical_snapshot_classification") != "PRIVATE PREPARATION, NOT APPROVAL OR PUBLICATION" or not isinstance(manifest.get("files"), dict)): raise ValueError("Unsupported historical provenance manifest") for relative, entry in manifest["files"].items(): if not isinstance(entry, dict): raise ValueError("Invalid historical provenance record") if entry.get("kind") not in {"private_preparation", "final_reviewed_packet"}: continue if not PACKET_PATH.fullmatch(relative): raise ValueError("Unsupported historical packet snapshot path") paths.append((root / relative, root, relative, entry)) covered.add((root / relative).resolve()) for base, prefix in ((root / "packets" if root else None, "packets"), (directory, "repository/editorial_packets")): if base is None: continue base = Path(base) if base.is_symlink(): raise ValueError("Historical packet directory cannot be a symbolic link") boundary = root if prefix == "packets" else base.parent.resolve() for path in sorted([*base.glob("*.json"), *(base / "revisions").glob("*.json")]): relative = path.relative_to(base).as_posix() if path.resolve() not in covered and PACKET_PATH.fullmatch(f"packets/{relative}"): paths.append((path, boundary, f"{prefix}/{relative}", None)) covered.add(path.resolve()) if len(paths) > MAX_RECORDS: raise ValueError("Historical private inventory exceeds its record budget") seen = set() for path, boundary, reference, entry in paths: packet, data = _bounded_json(path, boundary) digest, file_digest = _hash(packet), hashlib.sha256(data).hexdigest() if entry and (entry.get("sha256") != file_digest or entry.get("packet_sha256") != digest): raise ValueError("Historical preparation differs from its retained manifest") if digest in seen: continue seen.add(digest) prepared = packet.get("prepared_at") or packet.get("generated_at") reporting = packet.get("research_as_of") or packet.get("week_end") metadata = { "source": "private_preparation", "source_snapshot": reference, "source_manifest": "release-provenance.json" if entry else None, "packet_id": packet.get("packet_id"), "packet_sha256": digest, "file_sha256": file_digest, "prepared_at": prepared, "research_as_of": reporting, "week_start": packet.get("week_start"), "week_end": packet.get("week_end"), "edition_kind": packet.get("edition_kind"), } if isinstance(reporting, str) and reporting <= cutoff and _instant(prepared) is not None: localized = {locale: { "title": packet.get(locale, {}).get("title"), "stories": [{"slug": story.get("slug"), **story.get(locale, {})} for story in packet.get("stories", [])], "sucre": packet.get(locale, {}).get("sucre"), } for locale in ("fr", "en")} groups[CLASSES[1]].append({ **metadata, "classification": "private_preparation_not_proof_of_publication", "prepared_after_cutoff": _instant(prepared).date() > date.fromisoformat(cutoff), "copy": {locale: _copy(value, public=False, later_style=isinstance(packet.get("week_end"), str) and packet["week_end"] < week_start) for locale, value in localized.items()}, "sucre_forecasts_and_assessments_excluded": True, }) else: groups[CLASSES[2]].append({**metadata, "reason": "later_reporting_or_unknown_preparation_time"}) def validate_historical_context(value: dict, cutoff: date | str) -> dict: if (not isinstance(value, dict) or value.get("schema_version") != 1 or value.get("classification") != "read_only_historical_projection" or value.get("cutoff") != _cutoff(cutoff) or any(not isinstance(value.get(key), list) for key in CLASSES)): raise ValueError("Historical projection does not match its cutoff or schema") if _hash({key: item for key, item in value.items() if key != "projection_sha256"}) != value.get("projection_sha256"): raise ValueError("Historical projection hash differs from retained content") if len(json.dumps(value, ensure_ascii=False).encode()) > MAX_CONTEXT_BYTES: raise ValueError("Historical projection exceeds its inline budget; no record was truncated") return copy.deepcopy(value) def load_historical_context(path: Path, cutoff: date | str) -> dict: value, _ = _bounded_json(Path(path), Path(path).parent) return validate_historical_context(value, cutoff) def build_historical_context(database: Path, cutoff: date | str, *, private_provenance_root: Path | None = None, packet_directory: Path | None = None) -> dict: cutoff = _cutoff(cutoff) groups = _database_records(database, cutoff) _private_records(private_provenance_root, packet_directory, cutoff, groups) if sum(len(values) for values in groups.values()) > MAX_RECORDS: raise ValueError("Historical projection exceeds its record budget") # A retained private packet can be byte-identical to a later public edition. # Preserve both provenance records, but share only exactly identical copy. # This avoids filling the model context twice without losing any words. copies = {} for name in CLASSES: for index, record in enumerate(groups[name]): if "copy" not in record: continue digest = _hash(record["copy"]) if digest in copies: record["copy_reference"] = {**copies[digest], "copy_sha256": digest} del record["copy"] else: copies[digest] = {"class": name, "record_index": index} value = { "schema_version": 1, "classification": "read_only_historical_projection", "cutoff": cutoff, "cutoff_policy": "End of the named UTC calendar day, exclusive of the following midnight. Database naive timestamps are UTC by model contract.", "usage": "Only published_by_cutoff establishes contemporary LeDecaf public memory. Later reconstructions/private preparations are comparisons written later, never proof of earlier reader knowledge or source inspection. Earlier reporting-window Sucre in the separately named style-only field may guide comic continuity, never historical claims, reader memories or forecast evidence. Excluded entries supply metadata only. No current dossier answer, follow-up decision, same/later-week Sucre or later forecast assessment is supplied. No historical deadline is a live assignment.", "copy_coverage": "Whole story slug/title/summary/question fields. next_test keeps test/owner/review_date/scope_note; red_thread keeps previous/current/next/previous_date/previous_story_slug/previous_packet_hash/previous_prepared_at/review_date/owner; thesis keeps text/signpost/breaks_if. Nested prior dossiers and assessments are excluded. Contemporary Sucre is complete; later-written earlier-week Sucre has only style/prose fields and excludes structured forecasts/assessments. Identical copies use a zero-based class/record_index copy_reference with their exact copy hash. Hashes bind full source snapshots; omitted article bodies and all approval reports are not reproduced.", **groups, "missing_history": not bool(groups[CLASSES[0]]), } value["projection_sha256"] = _hash(value) return validate_historical_context(value, cutoff)