"""Bounded, dated hypotheses for the private newsroom, never a fact database. Records describe AI interpretations of inspected sources. Hash-linked revisions preserve changes of mind; neither repetition nor confidence makes a claim true. All persistent data lives inside the existing editorial-memory checkpoint. """ from __future__ import annotations import copy import hashlib import ipaddress import json import re from datetime import date, timedelta from urllib.parse import urlsplit MAX_UPDATES = 3 MAX_RECORD_BYTES = 16 * 1024 MAX_CONTEXT_BYTES = 96 * 1024 MAX_CONTEXT_ITEMS = 12 CLASSIFICATION = "AI analytical hypothesis, not established fact or independent evidence" ASSESSMENT_CLASSIFICATION = "Dated AI research assessment; declared source inspection, not a hypothesis, established fact or independent approval" ASSESSMENT_FIELDS = { "target_id", "target_kind", "decision", "reason", "evidence_urls", "access_limits", "update_ids", "next_review_date", "observed_as_of", "publication_refs", "dossier_slug", "source_publication_week_end", "source_story_position", "source_receipt_sha256", "source_artifact_id", "source_context_sha256", "source_prompt_sha256", "source_response_sha256", "source_response_raw_sha256", "classification", "retention_scope", "ingestion_sequence", "observation_sha256", } _ID = re.compile(r"[a-z][a-z0-9-]{2,79}\Z") UPDATE_FIELDS = { "id", "base_revision_sha256", "kind", "status", "dossier_slugs", "proposition", "actors", "mechanism", "confidence", "confidence_reason", "alternative_explanations", "evidence", "evidence_gaps", "disconfirming_test", "review_trigger", "next_review_date", "revision_reason", "publication_refs", } def _bytes(value: object) -> bytes: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() def _hash(value: object) -> str: return hashlib.sha256(_bytes(value)).hexdigest() def _text(value: object, name: str, maximum: int = 1200) -> str: if not isinstance(value, str) or not value.strip() or len(value) > maximum: raise ValueError(f"Analytical {name} must be bounded nonempty text") return value.strip() def _date(value: object) -> date: if not isinstance(value, str): raise ValueError("Analytical dates must be ISO calendar dates") result = date.fromisoformat(value) if result.isoformat() != value: raise ValueError("Analytical dates must be ISO calendar dates") return result def _url(value: object) -> str: result = _text(value, "evidence URL", 2048) parsed = urlsplit(result) host = parsed.hostname or "" if (parsed.scheme not in {"https", "http"} or not host or parsed.username or parsed.password or any(char.isspace() for char in result) or host in {"localhost", "localhost.localdomain"} or host.endswith((".local", ".localhost", ".internal"))): raise ValueError("Analytical evidence needs a public URL without credentials") try: address = ipaddress.ip_address(host) except ValueError: address = None if address is not None and not address.is_global: raise ValueError("Analytical evidence must not address a private network") return result def _list(value: object, name: str, maximum: int, *, minimum: int = 1) -> list: if not isinstance(value, list) or not minimum <= len(value) <= maximum: raise ValueError(f"Analytical {name} must be a bounded list") return value def scope_from_publications(publications: list[dict]) -> list[dict]: """Name source bases and real dossiers without treating published claims as truth.""" return [ {"issue_number": publication["issue_number"], "base_packet_sha256": publication["base_packet_sha256"], "snapshot_sha256": publication["snapshot_sha256"], "story_slug": slug, "dossier_slug": link["dossier_slug"]} for publication in publications for slug, link in publication["links"].items() ] def validate_assessment(record: dict) -> None: """Check the compact retained observation without inventing missing old proof.""" if (not isinstance(record, dict) or set(record) != ASSESSMENT_FIELDS or record["observation_sha256"] != _hash({key: value for key, value in record.items() if key != "observation_sha256"}) or record["classification"] != ASSESSMENT_CLASSIFICATION or record["target_kind"] not in {"story", "hypothesis"} or record["decision"] not in {"assessed", "defer"} or type(record["ingestion_sequence"]) is not int or record["ingestion_sequence"] < 1 or (record["source_story_position"] is not None and ( type(record["source_story_position"]) is not int or record["source_story_position"] < 0))): raise ValueError("Analytical assessment history failed verification") for key in ("source_receipt_sha256", "source_artifact_id", "source_context_sha256", "source_prompt_sha256", "source_response_sha256", "source_response_raw_sha256"): if not isinstance(record[key], str) or not re.fullmatch(r"[a-f0-9]{64}", record[key]): raise ValueError("Analytical assessment source binding is invalid") observed = _date(record["observed_as_of"]) _date(record["source_publication_week_end"]) if not observed < _date(record["next_review_date"]) <= observed + timedelta(days=90): raise ValueError("Analytical assessment review date is invalid") for key in ("target_id", "reason", "access_limits", "retention_scope"): _text(record[key], key) urls = _list(record["evidence_urls"], "assessment sources", 12, minimum=0) for url in urls: _url(url) if record["decision"] == "assessed" and not urls: raise ValueError("An assessed observation requires its declared sources") for identity in _list(record["update_ids"], "assessment update IDs", 3, minimum=0): _text(identity, "update ID", 80) for ref in _list(record["publication_refs"], "assessment publication references", 12): if not isinstance(ref, dict) or set(ref) != {"issue_number", "base_packet_sha256", "snapshot_sha256", "story_slug"}: raise ValueError("Analytical assessment publication reference is invalid") if type(ref["issue_number"]) is not int or ref["issue_number"] < 0: raise ValueError("Analytical assessment publication identity is invalid") _text(ref["story_slug"], "story slug", 200) if any(not isinstance(ref[key], str) or not re.fullmatch(r"[a-f0-9]{64}", ref[key]) for key in ("base_packet_sha256", "snapshot_sha256")): raise ValueError("Analytical assessment publication hash is invalid") if record["dossier_slug"] is not None: _text(record["dossier_slug"], "dossier slug", 200) def project(ledger: dict, *, as_of: str, scope: list[dict], assessments: dict | None = None) -> dict: """Retrieve whole, dated records with explicit omission and stale-base flags.""" cutoff = _date(as_of) if not isinstance(ledger, dict): raise ValueError("Invalid analytical memory ledger") source_bases = {(item["issue_number"], item["story_slug"]): (item["base_packet_sha256"], item["snapshot_sha256"]) for item in scope} candidates = [] for identity, revisions in ledger.items(): if not _ID.fullmatch(identity) or not isinstance(revisions, list) or not revisions: raise ValueError("Invalid analytical revision history") previous_hash = None eligible = [] last_date = None for revision in revisions: if not isinstance(revision, dict) or revision.get("id") != identity: raise ValueError("Invalid analytical revision identity") payload = {key: value for key, value in revision.items() if key != "revision_sha256"} if (revision.get("base_revision_sha256") != previous_hash or revision.get("revision_sha256") != _hash(payload) or revision.get("classification") != CLASSIFICATION): raise ValueError("Analytical revision chain failed verification") observed = _date(revision["observed_at"]) if last_date and observed < last_date: raise ValueError("Analytical revision dates moved backwards") previous_hash, last_date = revision["revision_sha256"], observed if observed <= cutoff: eligible.append(revision) if not eligible: continue current = copy.deepcopy(eligible[-1]) # Old answers remain visible as rejected, never silently reused as facts. current["revision_count_as_of"] = len(eligible) current["source_base_changed"] = any( source_bases.get((item["issue_number"], item["story_slug"])) != (item["base_packet_sha256"], item["snapshot_sha256"]) for item in current["publication_refs"] ) current["review_due"] = current["status"] == "active" and _date(current["next_review_date"]) <= cutoff candidates.append(current) candidates.sort(key=lambda item: ( 0 if item["status"] == "active" and (item["review_due"] or item["source_base_changed"]) else 1 if item["status"] == "active" else 2, item["next_review_date"], item["id"], )) latest_assessments = {} sequences = set() if assessments is not None: if not isinstance(assessments, dict): raise ValueError("Invalid analytical assessment history") for identity, record in assessments.items(): validate_assessment(record) if record["observation_sha256"] != identity or record["ingestion_sequence"] in sequences: raise ValueError("Analytical assessment history failed verification") sequences.add(record["ingestion_sequence"]) if _date(record["observed_as_of"]) > cutoff: continue previous = latest_assessments.get(record["target_id"]) if previous is None or (record["observed_as_of"], record["ingestion_sequence"]) > (previous["observed_as_of"], previous["ingestion_sequence"]): latest_assessments[record["target_id"]] = copy.deepcopy(record) assessment_candidates = sorted(latest_assessments.values(), key=lambda item: ( -_date(item["source_publication_week_end"]).toordinal(), item["source_story_position"] if item["source_story_position"] is not None else 1_000_000, item["target_id"], )) def priority(item): return item["status"] == "active" and (item["review_due"] or item["source_base_changed"]) ordered = ([("hypothesis", item) for item in candidates if priority(item)] + [("assessment", item) for item in assessment_candidates] + [("hypothesis", item) for item in candidates if not priority(item)]) selected, selected_assessments, size, count = [], [], 2, 0 for kind, item in ordered: item_size = len(_bytes(item)) + (1 if count else 0) if count < MAX_CONTEXT_ITEMS and size + item_size <= MAX_CONTEXT_BYTES: (selected if kind == "hypothesis" else selected_assessments).append(item) size += item_size count += 1 result = { "classification": CLASSIFICATION, "as_of": as_of, "records": selected, "available_count": len(candidates), "included_count": len(selected), "omitted_count": len(candidates) - len(selected), "max_records": MAX_CONTEXT_ITEMS, "max_bytes": MAX_CONTEXT_BYTES, "records_bytes": size, "use": "Research leads and competing explanations for author and Sucre. Reinspect sources; never cite memory itself as evidence. Confidence is an AI judgment, not a calibrated probability. Later observations are excluded.", } if assessments is not None: result.update( classification="Untrusted AI analytical memory: separate hypotheses and dated research assessments, not established facts or independent approval", research_assessments=selected_assessments, assessment_available_count=len(assessment_candidates), assessment_included_count=len(selected_assessments), assessment_omitted_count=len(assessment_candidates) - len(selected_assessments), total_available_count=len(candidates) + len(assessment_candidates), total_included_count=count, total_omitted_count=len(candidates) + len(assessment_candidates) - count, assessment_history_count=len(assessments), selection_policy="One combined 12-record/96KiB data bound: due or stale active hypotheses first, then latest eligible research assessment per target in original public editorial story order (newest publication first), then remaining hypotheses. Whole omitted observations remain in private memory. Unknown historical order follows known public order.", ) return result def validate_updates(updates: object, *, context: dict) -> list[dict]: """Validate all additions before a caller changes any persistent state.""" result = copy.deepcopy(_list(updates, "updates", MAX_UPDATES, minimum=0)) as_of = _date(context["as_of"]) scope = context.get("analytical_scope", []) known_refs = {(item["issue_number"], item["base_packet_sha256"], item["snapshot_sha256"], item["story_slug"]) for item in scope} ref_dossiers = {(item["issue_number"], item["base_packet_sha256"], item["snapshot_sha256"], item["story_slug"]): item["dossier_slug"] for item in scope} known_dossiers = {item["dossier_slug"] for item in scope} current = {item["id"]: item for item in context.get("analytical_memory", {}).get("records", [])} seen = set() for item in result: if not isinstance(item, dict): raise ValueError("Analytical update must be an object") if set(item) != UPDATE_FIELDS: raise ValueError("Analytical update fields must match the explicit contract") identity = item.get("id") if not isinstance(identity, str) or not _ID.fullmatch(identity) or identity in seen: raise ValueError("Analytical update needs a distinct stable ID") seen.add(identity) expected = current.get(identity, {}).get("revision_sha256") if item.get("base_revision_sha256") != expected: raise ValueError("Analytical update must name the exact visible revision") if item.get("kind") not in {"hypothesis", "power_model"} or item.get("status") not in {"active", "rejected"}: raise ValueError("Invalid analytical kind or status") if item.get("confidence") not in {"low", "medium", "high"}: raise ValueError("Analytical confidence must be an explicit qualitative judgment") for key in ("proposition", "mechanism", "confidence_reason", "evidence_gaps", "disconfirming_test", "review_trigger", "revision_reason"): item[key] = _text(item.get(key), key) for key, maximum in (("actors", 8), ("alternative_explanations", 3), ("dossier_slugs", 4)): item[key] = [_text(value, key, 600) for value in _list(item.get(key), key, maximum)] if len(set(item["dossier_slugs"])) != len(item["dossier_slugs"]) or not set(item["dossier_slugs"]) <= known_dossiers: raise ValueError("Analytical hypotheses must attach to existing dossiers") refs = _list(item.get("publication_refs"), "publication references", 8) for ref in refs: if (not isinstance(ref, dict) or set(ref) != {"issue_number", "base_packet_sha256", "snapshot_sha256", "story_slug"} or type(ref.get("issue_number")) is not int or (ref.get("issue_number"), ref.get("base_packet_sha256"), ref.get("snapshot_sha256"), ref.get("story_slug")) not in known_refs): raise ValueError("Analytical source base must name an exact published story") if {ref_dossiers[(ref["issue_number"], ref["base_packet_sha256"], ref["snapshot_sha256"], ref["story_slug"])] for ref in refs} != set(item["dossier_slugs"]): raise ValueError("Analytical dossier links must match the referenced published stories") due = _date(item.get("next_review_date")) if not as_of < due <= as_of + timedelta(days=90): raise ValueError("Analytical review must fall within the following 90 days") evidence = _list(item.get("evidence"), "evidence", 8) for source in evidence: if (not isinstance(source, dict) or set(source) != {"url", "source_name", "language", "perspective", "observation", "relation", "published_on", "accessed_on"} or source.get("relation") not in {"supports", "challenges", "context"}): raise ValueError("Analytical evidence requires its relation to the hypothesis") source["url"] = _url(source.get("url")) for key in ("source_name", "language", "perspective", "observation"): source[key] = _text(source.get(key), "source " + key, 1200) accessed = _date(source.get("accessed_on")) if not as_of - timedelta(days=7) <= accessed <= as_of: raise ValueError("Analytical sources need fresh inspection, never a future date") if source.get("published_on") is not None and _date(source["published_on"]) > as_of: raise ValueError("Analytical source publication is after the reporting cutoff") if len(_bytes(item)) > MAX_RECORD_BYTES: raise ValueError("Analytical hypothesis exceeds its per-record budget") return result def append_updates(ledger: dict, updates: list[dict], *, as_of: str) -> None: """Append exact revisions in memory; callers persist the whole batch atomically.""" for item in updates: revisions = ledger.setdefault(item["id"], []) previous = revisions[-1] if revisions else None expected = previous["revision_sha256"] if previous else None if item.get("base_revision_sha256") != expected: raise ValueError("Analytical revision changed or was omitted; rebuild the context") if previous and _date(as_of) < _date(previous["observed_at"]): raise ValueError("Cannot backdate an analytical revision") record = {**copy.deepcopy(item), "observed_at": as_of, "classification": CLASSIFICATION} record["revision_sha256"] = _hash(record) revisions.append(record)